echarts.common.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. (function (global, factory) {
  20. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  21. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  22. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  23. }(this, (function (exports) { 'use strict';
  24. /*! *****************************************************************************
  25. Copyright (c) Microsoft Corporation.
  26. Permission to use, copy, modify, and/or distribute this software for any
  27. purpose with or without fee is hereby granted.
  28. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  30. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  31. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  33. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34. PERFORMANCE OF THIS SOFTWARE.
  35. ***************************************************************************** */
  36. /* global Reflect, Promise */
  37. var extendStatics = function(d, b) {
  38. extendStatics = Object.setPrototypeOf ||
  39. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  40. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  41. return extendStatics(d, b);
  42. };
  43. function __extends(d, b) {
  44. extendStatics(d, b);
  45. function __() { this.constructor = d; }
  46. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  47. }
  48. var __assign = function() {
  49. __assign = Object.assign || function __assign(t) {
  50. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51. s = arguments[i];
  52. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  53. }
  54. return t;
  55. };
  56. return __assign.apply(this, arguments);
  57. };
  58. function __spreadArrays() {
  59. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  60. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  61. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  62. r[k] = a[j];
  63. return r;
  64. }
  65. var Browser = (function () {
  66. function Browser() {
  67. this.firefox = false;
  68. this.ie = false;
  69. this.edge = false;
  70. this.newEdge = false;
  71. this.weChat = false;
  72. }
  73. return Browser;
  74. }());
  75. var Env = (function () {
  76. function Env() {
  77. this.browser = new Browser();
  78. this.node = false;
  79. this.wxa = false;
  80. this.worker = false;
  81. this.canvasSupported = false;
  82. this.svgSupported = false;
  83. this.touchEventsSupported = false;
  84. this.pointerEventsSupported = false;
  85. this.domSupported = false;
  86. }
  87. return Env;
  88. }());
  89. var env = new Env();
  90. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  91. env.wxa = true;
  92. env.canvasSupported = true;
  93. env.touchEventsSupported = true;
  94. }
  95. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  96. env.worker = true;
  97. env.canvasSupported = true;
  98. }
  99. else if (typeof navigator === 'undefined') {
  100. env.node = true;
  101. env.canvasSupported = true;
  102. env.svgSupported = true;
  103. }
  104. else {
  105. detect(navigator.userAgent, env);
  106. }
  107. function detect(ua, env) {
  108. var browser = env.browser;
  109. var firefox = ua.match(/Firefox\/([\d.]+)/);
  110. var ie = ua.match(/MSIE\s([\d.]+)/)
  111. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  112. var edge = ua.match(/Edge?\/([\d.]+)/);
  113. var weChat = (/micromessenger/i).test(ua);
  114. if (firefox) {
  115. browser.firefox = true;
  116. browser.version = firefox[1];
  117. }
  118. if (ie) {
  119. browser.ie = true;
  120. browser.version = ie[1];
  121. }
  122. if (edge) {
  123. browser.edge = true;
  124. browser.version = edge[1];
  125. browser.newEdge = +edge[1].split('.')[0] > 18;
  126. }
  127. if (weChat) {
  128. browser.weChat = true;
  129. }
  130. env.canvasSupported = !!document.createElement('canvas').getContext;
  131. env.svgSupported = typeof SVGRect !== 'undefined';
  132. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  133. env.pointerEventsSupported = 'onpointerdown' in window
  134. && (browser.edge || (browser.ie && +browser.version >= 11));
  135. env.domSupported = typeof document !== 'undefined';
  136. }
  137. var BUILTIN_OBJECT = {
  138. '[object Function]': true,
  139. '[object RegExp]': true,
  140. '[object Date]': true,
  141. '[object Error]': true,
  142. '[object CanvasGradient]': true,
  143. '[object CanvasPattern]': true,
  144. '[object Image]': true,
  145. '[object Canvas]': true
  146. };
  147. var TYPED_ARRAY = {
  148. '[object Int8Array]': true,
  149. '[object Uint8Array]': true,
  150. '[object Uint8ClampedArray]': true,
  151. '[object Int16Array]': true,
  152. '[object Uint16Array]': true,
  153. '[object Int32Array]': true,
  154. '[object Uint32Array]': true,
  155. '[object Float32Array]': true,
  156. '[object Float64Array]': true
  157. };
  158. var objToString = Object.prototype.toString;
  159. var arrayProto = Array.prototype;
  160. var nativeForEach = arrayProto.forEach;
  161. var nativeFilter = arrayProto.filter;
  162. var nativeSlice = arrayProto.slice;
  163. var nativeMap = arrayProto.map;
  164. var ctorFunction = function () { }.constructor;
  165. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  166. var methods = {};
  167. function $override(name, fn) {
  168. methods[name] = fn;
  169. }
  170. var idStart = 0x0907;
  171. function guid() {
  172. return idStart++;
  173. }
  174. function logError() {
  175. var args = [];
  176. for (var _i = 0; _i < arguments.length; _i++) {
  177. args[_i] = arguments[_i];
  178. }
  179. if (typeof console !== 'undefined') {
  180. console.error.apply(console, args);
  181. }
  182. }
  183. function clone(source) {
  184. if (source == null || typeof source !== 'object') {
  185. return source;
  186. }
  187. var result = source;
  188. var typeStr = objToString.call(source);
  189. if (typeStr === '[object Array]') {
  190. if (!isPrimitive(source)) {
  191. result = [];
  192. for (var i = 0, len = source.length; i < len; i++) {
  193. result[i] = clone(source[i]);
  194. }
  195. }
  196. }
  197. else if (TYPED_ARRAY[typeStr]) {
  198. if (!isPrimitive(source)) {
  199. var Ctor = source.constructor;
  200. if (Ctor.from) {
  201. result = Ctor.from(source);
  202. }
  203. else {
  204. result = new Ctor(source.length);
  205. for (var i = 0, len = source.length; i < len; i++) {
  206. result[i] = clone(source[i]);
  207. }
  208. }
  209. }
  210. }
  211. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  212. result = {};
  213. for (var key in source) {
  214. if (source.hasOwnProperty(key)) {
  215. result[key] = clone(source[key]);
  216. }
  217. }
  218. }
  219. return result;
  220. }
  221. function merge(target, source, overwrite) {
  222. if (!isObject(source) || !isObject(target)) {
  223. return overwrite ? clone(source) : target;
  224. }
  225. for (var key in source) {
  226. if (source.hasOwnProperty(key)) {
  227. var targetProp = target[key];
  228. var sourceProp = source[key];
  229. if (isObject(sourceProp)
  230. && isObject(targetProp)
  231. && !isArray(sourceProp)
  232. && !isArray(targetProp)
  233. && !isDom(sourceProp)
  234. && !isDom(targetProp)
  235. && !isBuiltInObject(sourceProp)
  236. && !isBuiltInObject(targetProp)
  237. && !isPrimitive(sourceProp)
  238. && !isPrimitive(targetProp)) {
  239. merge(targetProp, sourceProp, overwrite);
  240. }
  241. else if (overwrite || !(key in target)) {
  242. target[key] = clone(source[key]);
  243. }
  244. }
  245. }
  246. return target;
  247. }
  248. function mergeAll(targetAndSources, overwrite) {
  249. var result = targetAndSources[0];
  250. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  251. result = merge(result, targetAndSources[i], overwrite);
  252. }
  253. return result;
  254. }
  255. function extend(target, source) {
  256. if (Object.assign) {
  257. Object.assign(target, source);
  258. }
  259. else {
  260. for (var key in source) {
  261. if (source.hasOwnProperty(key)) {
  262. target[key] = source[key];
  263. }
  264. }
  265. }
  266. return target;
  267. }
  268. function defaults(target, source, overlay) {
  269. var keysArr = keys(source);
  270. for (var i = 0; i < keysArr.length; i++) {
  271. var key = keysArr[i];
  272. if ((overlay ? source[key] != null : target[key] == null)) {
  273. target[key] = source[key];
  274. }
  275. }
  276. return target;
  277. }
  278. var createCanvas = function () {
  279. return methods.createCanvas();
  280. };
  281. methods.createCanvas = function () {
  282. return document.createElement('canvas');
  283. };
  284. function indexOf(array, value) {
  285. if (array) {
  286. if (array.indexOf) {
  287. return array.indexOf(value);
  288. }
  289. for (var i = 0, len = array.length; i < len; i++) {
  290. if (array[i] === value) {
  291. return i;
  292. }
  293. }
  294. }
  295. return -1;
  296. }
  297. function inherits(clazz, baseClazz) {
  298. var clazzPrototype = clazz.prototype;
  299. function F() { }
  300. F.prototype = baseClazz.prototype;
  301. clazz.prototype = new F();
  302. for (var prop in clazzPrototype) {
  303. if (clazzPrototype.hasOwnProperty(prop)) {
  304. clazz.prototype[prop] = clazzPrototype[prop];
  305. }
  306. }
  307. clazz.prototype.constructor = clazz;
  308. clazz.superClass = baseClazz;
  309. }
  310. function mixin(target, source, override) {
  311. target = 'prototype' in target ? target.prototype : target;
  312. source = 'prototype' in source ? source.prototype : source;
  313. if (Object.getOwnPropertyNames) {
  314. var keyList = Object.getOwnPropertyNames(source);
  315. for (var i = 0; i < keyList.length; i++) {
  316. var key = keyList[i];
  317. if (key !== 'constructor') {
  318. if ((override ? source[key] != null : target[key] == null)) {
  319. target[key] = source[key];
  320. }
  321. }
  322. }
  323. }
  324. else {
  325. defaults(target, source, override);
  326. }
  327. }
  328. function isArrayLike(data) {
  329. if (!data) {
  330. return false;
  331. }
  332. if (typeof data === 'string') {
  333. return false;
  334. }
  335. return typeof data.length === 'number';
  336. }
  337. function each(arr, cb, context) {
  338. if (!(arr && cb)) {
  339. return;
  340. }
  341. if (arr.forEach && arr.forEach === nativeForEach) {
  342. arr.forEach(cb, context);
  343. }
  344. else if (arr.length === +arr.length) {
  345. for (var i = 0, len = arr.length; i < len; i++) {
  346. cb.call(context, arr[i], i, arr);
  347. }
  348. }
  349. else {
  350. for (var key in arr) {
  351. if (arr.hasOwnProperty(key)) {
  352. cb.call(context, arr[key], key, arr);
  353. }
  354. }
  355. }
  356. }
  357. function map(arr, cb, context) {
  358. if (!arr) {
  359. return [];
  360. }
  361. if (!cb) {
  362. return slice(arr);
  363. }
  364. if (arr.map && arr.map === nativeMap) {
  365. return arr.map(cb, context);
  366. }
  367. else {
  368. var result = [];
  369. for (var i = 0, len = arr.length; i < len; i++) {
  370. result.push(cb.call(context, arr[i], i, arr));
  371. }
  372. return result;
  373. }
  374. }
  375. function reduce(arr, cb, memo, context) {
  376. if (!(arr && cb)) {
  377. return;
  378. }
  379. for (var i = 0, len = arr.length; i < len; i++) {
  380. memo = cb.call(context, memo, arr[i], i, arr);
  381. }
  382. return memo;
  383. }
  384. function filter(arr, cb, context) {
  385. if (!arr) {
  386. return [];
  387. }
  388. if (!cb) {
  389. return slice(arr);
  390. }
  391. if (arr.filter && arr.filter === nativeFilter) {
  392. return arr.filter(cb, context);
  393. }
  394. else {
  395. var result = [];
  396. for (var i = 0, len = arr.length; i < len; i++) {
  397. if (cb.call(context, arr[i], i, arr)) {
  398. result.push(arr[i]);
  399. }
  400. }
  401. return result;
  402. }
  403. }
  404. function find(arr, cb, context) {
  405. if (!(arr && cb)) {
  406. return;
  407. }
  408. for (var i = 0, len = arr.length; i < len; i++) {
  409. if (cb.call(context, arr[i], i, arr)) {
  410. return arr[i];
  411. }
  412. }
  413. }
  414. function keys(obj) {
  415. if (!obj) {
  416. return [];
  417. }
  418. if (Object.keys) {
  419. return Object.keys(obj);
  420. }
  421. var keyList = [];
  422. for (var key in obj) {
  423. if (obj.hasOwnProperty(key)) {
  424. keyList.push(key);
  425. }
  426. }
  427. return keyList;
  428. }
  429. function bindPolyfill(func, context) {
  430. var args = [];
  431. for (var _i = 2; _i < arguments.length; _i++) {
  432. args[_i - 2] = arguments[_i];
  433. }
  434. return function () {
  435. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  436. };
  437. }
  438. var bind = (protoFunction && isFunction(protoFunction.bind))
  439. ? protoFunction.call.bind(protoFunction.bind)
  440. : bindPolyfill;
  441. function curry(func) {
  442. var args = [];
  443. for (var _i = 1; _i < arguments.length; _i++) {
  444. args[_i - 1] = arguments[_i];
  445. }
  446. return function () {
  447. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  448. };
  449. }
  450. function isArray(value) {
  451. if (Array.isArray) {
  452. return Array.isArray(value);
  453. }
  454. return objToString.call(value) === '[object Array]';
  455. }
  456. function isFunction(value) {
  457. return typeof value === 'function';
  458. }
  459. function isString(value) {
  460. return typeof value === 'string';
  461. }
  462. function isStringSafe(value) {
  463. return objToString.call(value) === '[object String]';
  464. }
  465. function isNumber(value) {
  466. return typeof value === 'number';
  467. }
  468. function isObject(value) {
  469. var type = typeof value;
  470. return type === 'function' || (!!value && type === 'object');
  471. }
  472. function isBuiltInObject(value) {
  473. return !!BUILTIN_OBJECT[objToString.call(value)];
  474. }
  475. function isTypedArray(value) {
  476. return !!TYPED_ARRAY[objToString.call(value)];
  477. }
  478. function isDom(value) {
  479. return typeof value === 'object'
  480. && typeof value.nodeType === 'number'
  481. && typeof value.ownerDocument === 'object';
  482. }
  483. function isGradientObject(value) {
  484. return value.colorStops != null;
  485. }
  486. function isPatternObject(value) {
  487. return value.image != null;
  488. }
  489. function isRegExp(value) {
  490. return objToString.call(value) === '[object RegExp]';
  491. }
  492. function eqNaN(value) {
  493. return value !== value;
  494. }
  495. function retrieve() {
  496. var args = [];
  497. for (var _i = 0; _i < arguments.length; _i++) {
  498. args[_i] = arguments[_i];
  499. }
  500. for (var i = 0, len = args.length; i < len; i++) {
  501. if (args[i] != null) {
  502. return args[i];
  503. }
  504. }
  505. }
  506. function retrieve2(value0, value1) {
  507. return value0 != null
  508. ? value0
  509. : value1;
  510. }
  511. function retrieve3(value0, value1, value2) {
  512. return value0 != null
  513. ? value0
  514. : value1 != null
  515. ? value1
  516. : value2;
  517. }
  518. function slice(arr) {
  519. var args = [];
  520. for (var _i = 1; _i < arguments.length; _i++) {
  521. args[_i - 1] = arguments[_i];
  522. }
  523. return nativeSlice.apply(arr, args);
  524. }
  525. function normalizeCssArray(val) {
  526. if (typeof (val) === 'number') {
  527. return [val, val, val, val];
  528. }
  529. var len = val.length;
  530. if (len === 2) {
  531. return [val[0], val[1], val[0], val[1]];
  532. }
  533. else if (len === 3) {
  534. return [val[0], val[1], val[2], val[1]];
  535. }
  536. return val;
  537. }
  538. function assert(condition, message) {
  539. if (!condition) {
  540. throw new Error(message);
  541. }
  542. }
  543. function trim(str) {
  544. if (str == null) {
  545. return null;
  546. }
  547. else if (typeof str.trim === 'function') {
  548. return str.trim();
  549. }
  550. else {
  551. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  552. }
  553. }
  554. var primitiveKey = '__ec_primitive__';
  555. function setAsPrimitive(obj) {
  556. obj[primitiveKey] = true;
  557. }
  558. function isPrimitive(obj) {
  559. return obj[primitiveKey];
  560. }
  561. var HashMap = (function () {
  562. function HashMap(obj) {
  563. this.data = {};
  564. var isArr = isArray(obj);
  565. this.data = {};
  566. var thisMap = this;
  567. (obj instanceof HashMap)
  568. ? obj.each(visit)
  569. : (obj && each(obj, visit));
  570. function visit(value, key) {
  571. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  572. }
  573. }
  574. HashMap.prototype.get = function (key) {
  575. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  576. };
  577. HashMap.prototype.set = function (key, value) {
  578. return (this.data[key] = value);
  579. };
  580. HashMap.prototype.each = function (cb, context) {
  581. for (var key in this.data) {
  582. if (this.data.hasOwnProperty(key)) {
  583. cb.call(context, this.data[key], key);
  584. }
  585. }
  586. };
  587. HashMap.prototype.keys = function () {
  588. return keys(this.data);
  589. };
  590. HashMap.prototype.removeKey = function (key) {
  591. delete this.data[key];
  592. };
  593. return HashMap;
  594. }());
  595. function createHashMap(obj) {
  596. return new HashMap(obj);
  597. }
  598. function concatArray(a, b) {
  599. var newArray = new a.constructor(a.length + b.length);
  600. for (var i = 0; i < a.length; i++) {
  601. newArray[i] = a[i];
  602. }
  603. var offset = a.length;
  604. for (var i = 0; i < b.length; i++) {
  605. newArray[i + offset] = b[i];
  606. }
  607. return newArray;
  608. }
  609. function createObject(proto, properties) {
  610. var obj;
  611. if (Object.create) {
  612. obj = Object.create(proto);
  613. }
  614. else {
  615. var StyleCtor = function () { };
  616. StyleCtor.prototype = proto;
  617. obj = new StyleCtor();
  618. }
  619. if (properties) {
  620. extend(obj, properties);
  621. }
  622. return obj;
  623. }
  624. function hasOwn(own, prop) {
  625. return own.hasOwnProperty(prop);
  626. }
  627. function noop() { }
  628. var util = /*#__PURE__*/Object.freeze({
  629. __proto__: null,
  630. $override: $override,
  631. guid: guid,
  632. logError: logError,
  633. clone: clone,
  634. merge: merge,
  635. mergeAll: mergeAll,
  636. extend: extend,
  637. defaults: defaults,
  638. createCanvas: createCanvas,
  639. indexOf: indexOf,
  640. inherits: inherits,
  641. mixin: mixin,
  642. isArrayLike: isArrayLike,
  643. each: each,
  644. map: map,
  645. reduce: reduce,
  646. filter: filter,
  647. find: find,
  648. keys: keys,
  649. bind: bind,
  650. curry: curry,
  651. isArray: isArray,
  652. isFunction: isFunction,
  653. isString: isString,
  654. isStringSafe: isStringSafe,
  655. isNumber: isNumber,
  656. isObject: isObject,
  657. isBuiltInObject: isBuiltInObject,
  658. isTypedArray: isTypedArray,
  659. isDom: isDom,
  660. isGradientObject: isGradientObject,
  661. isPatternObject: isPatternObject,
  662. isRegExp: isRegExp,
  663. eqNaN: eqNaN,
  664. retrieve: retrieve,
  665. retrieve2: retrieve2,
  666. retrieve3: retrieve3,
  667. slice: slice,
  668. normalizeCssArray: normalizeCssArray,
  669. assert: assert,
  670. trim: trim,
  671. setAsPrimitive: setAsPrimitive,
  672. isPrimitive: isPrimitive,
  673. HashMap: HashMap,
  674. createHashMap: createHashMap,
  675. concatArray: concatArray,
  676. createObject: createObject,
  677. hasOwn: hasOwn,
  678. noop: noop
  679. });
  680. function create(x, y) {
  681. if (x == null) {
  682. x = 0;
  683. }
  684. if (y == null) {
  685. y = 0;
  686. }
  687. return [x, y];
  688. }
  689. function copy(out, v) {
  690. out[0] = v[0];
  691. out[1] = v[1];
  692. return out;
  693. }
  694. function clone$1(v) {
  695. return [v[0], v[1]];
  696. }
  697. function set(out, a, b) {
  698. out[0] = a;
  699. out[1] = b;
  700. return out;
  701. }
  702. function add(out, v1, v2) {
  703. out[0] = v1[0] + v2[0];
  704. out[1] = v1[1] + v2[1];
  705. return out;
  706. }
  707. function scaleAndAdd(out, v1, v2, a) {
  708. out[0] = v1[0] + v2[0] * a;
  709. out[1] = v1[1] + v2[1] * a;
  710. return out;
  711. }
  712. function sub(out, v1, v2) {
  713. out[0] = v1[0] - v2[0];
  714. out[1] = v1[1] - v2[1];
  715. return out;
  716. }
  717. function len(v) {
  718. return Math.sqrt(lenSquare(v));
  719. }
  720. var length = len;
  721. function lenSquare(v) {
  722. return v[0] * v[0] + v[1] * v[1];
  723. }
  724. var lengthSquare = lenSquare;
  725. function mul(out, v1, v2) {
  726. out[0] = v1[0] * v2[0];
  727. out[1] = v1[1] * v2[1];
  728. return out;
  729. }
  730. function div(out, v1, v2) {
  731. out[0] = v1[0] / v2[0];
  732. out[1] = v1[1] / v2[1];
  733. return out;
  734. }
  735. function dot(v1, v2) {
  736. return v1[0] * v2[0] + v1[1] * v2[1];
  737. }
  738. function scale(out, v, s) {
  739. out[0] = v[0] * s;
  740. out[1] = v[1] * s;
  741. return out;
  742. }
  743. function normalize(out, v) {
  744. var d = len(v);
  745. if (d === 0) {
  746. out[0] = 0;
  747. out[1] = 0;
  748. }
  749. else {
  750. out[0] = v[0] / d;
  751. out[1] = v[1] / d;
  752. }
  753. return out;
  754. }
  755. function distance(v1, v2) {
  756. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  757. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  758. }
  759. var dist = distance;
  760. function distanceSquare(v1, v2) {
  761. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  762. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  763. }
  764. var distSquare = distanceSquare;
  765. function negate(out, v) {
  766. out[0] = -v[0];
  767. out[1] = -v[1];
  768. return out;
  769. }
  770. function lerp(out, v1, v2, t) {
  771. out[0] = v1[0] + t * (v2[0] - v1[0]);
  772. out[1] = v1[1] + t * (v2[1] - v1[1]);
  773. return out;
  774. }
  775. function applyTransform(out, v, m) {
  776. var x = v[0];
  777. var y = v[1];
  778. out[0] = m[0] * x + m[2] * y + m[4];
  779. out[1] = m[1] * x + m[3] * y + m[5];
  780. return out;
  781. }
  782. function min(out, v1, v2) {
  783. out[0] = Math.min(v1[0], v2[0]);
  784. out[1] = Math.min(v1[1], v2[1]);
  785. return out;
  786. }
  787. function max(out, v1, v2) {
  788. out[0] = Math.max(v1[0], v2[0]);
  789. out[1] = Math.max(v1[1], v2[1]);
  790. return out;
  791. }
  792. var vector = /*#__PURE__*/Object.freeze({
  793. __proto__: null,
  794. create: create,
  795. copy: copy,
  796. clone: clone$1,
  797. set: set,
  798. add: add,
  799. scaleAndAdd: scaleAndAdd,
  800. sub: sub,
  801. len: len,
  802. length: length,
  803. lenSquare: lenSquare,
  804. lengthSquare: lengthSquare,
  805. mul: mul,
  806. div: div,
  807. dot: dot,
  808. scale: scale,
  809. normalize: normalize,
  810. distance: distance,
  811. dist: dist,
  812. distanceSquare: distanceSquare,
  813. distSquare: distSquare,
  814. negate: negate,
  815. lerp: lerp,
  816. applyTransform: applyTransform,
  817. min: min,
  818. max: max
  819. });
  820. var Param = (function () {
  821. function Param(target, e) {
  822. this.target = target;
  823. this.topTarget = e && e.topTarget;
  824. }
  825. return Param;
  826. }());
  827. var Draggable = (function () {
  828. function Draggable(handler) {
  829. this.handler = handler;
  830. handler.on('mousedown', this._dragStart, this);
  831. handler.on('mousemove', this._drag, this);
  832. handler.on('mouseup', this._dragEnd, this);
  833. }
  834. Draggable.prototype._dragStart = function (e) {
  835. var draggingTarget = e.target;
  836. while (draggingTarget && !draggingTarget.draggable) {
  837. draggingTarget = draggingTarget.parent;
  838. }
  839. if (draggingTarget) {
  840. this._draggingTarget = draggingTarget;
  841. draggingTarget.dragging = true;
  842. this._x = e.offsetX;
  843. this._y = e.offsetY;
  844. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  845. }
  846. };
  847. Draggable.prototype._drag = function (e) {
  848. var draggingTarget = this._draggingTarget;
  849. if (draggingTarget) {
  850. var x = e.offsetX;
  851. var y = e.offsetY;
  852. var dx = x - this._x;
  853. var dy = y - this._y;
  854. this._x = x;
  855. this._y = y;
  856. draggingTarget.drift(dx, dy, e);
  857. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  858. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  859. var lastDropTarget = this._dropTarget;
  860. this._dropTarget = dropTarget;
  861. if (draggingTarget !== dropTarget) {
  862. if (lastDropTarget && dropTarget !== lastDropTarget) {
  863. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  864. }
  865. if (dropTarget && dropTarget !== lastDropTarget) {
  866. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  867. }
  868. }
  869. }
  870. };
  871. Draggable.prototype._dragEnd = function (e) {
  872. var draggingTarget = this._draggingTarget;
  873. if (draggingTarget) {
  874. draggingTarget.dragging = false;
  875. }
  876. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  877. if (this._dropTarget) {
  878. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  879. }
  880. this._draggingTarget = null;
  881. this._dropTarget = null;
  882. };
  883. return Draggable;
  884. }());
  885. var Eventful = (function () {
  886. function Eventful(eventProcessors) {
  887. if (eventProcessors) {
  888. this._$eventProcessor = eventProcessors;
  889. }
  890. }
  891. Eventful.prototype.on = function (event, query, handler, context) {
  892. if (!this._$handlers) {
  893. this._$handlers = {};
  894. }
  895. var _h = this._$handlers;
  896. if (typeof query === 'function') {
  897. context = handler;
  898. handler = query;
  899. query = null;
  900. }
  901. if (!handler || !event) {
  902. return this;
  903. }
  904. var eventProcessor = this._$eventProcessor;
  905. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  906. query = eventProcessor.normalizeQuery(query);
  907. }
  908. if (!_h[event]) {
  909. _h[event] = [];
  910. }
  911. for (var i = 0; i < _h[event].length; i++) {
  912. if (_h[event][i].h === handler) {
  913. return this;
  914. }
  915. }
  916. var wrap = {
  917. h: handler,
  918. query: query,
  919. ctx: (context || this),
  920. callAtLast: handler.zrEventfulCallAtLast
  921. };
  922. var lastIndex = _h[event].length - 1;
  923. var lastWrap = _h[event][lastIndex];
  924. (lastWrap && lastWrap.callAtLast)
  925. ? _h[event].splice(lastIndex, 0, wrap)
  926. : _h[event].push(wrap);
  927. return this;
  928. };
  929. Eventful.prototype.isSilent = function (eventName) {
  930. var _h = this._$handlers;
  931. return !_h || !_h[eventName] || !_h[eventName].length;
  932. };
  933. Eventful.prototype.off = function (eventType, handler) {
  934. var _h = this._$handlers;
  935. if (!_h) {
  936. return this;
  937. }
  938. if (!eventType) {
  939. this._$handlers = {};
  940. return this;
  941. }
  942. if (handler) {
  943. if (_h[eventType]) {
  944. var newList = [];
  945. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  946. if (_h[eventType][i].h !== handler) {
  947. newList.push(_h[eventType][i]);
  948. }
  949. }
  950. _h[eventType] = newList;
  951. }
  952. if (_h[eventType] && _h[eventType].length === 0) {
  953. delete _h[eventType];
  954. }
  955. }
  956. else {
  957. delete _h[eventType];
  958. }
  959. return this;
  960. };
  961. Eventful.prototype.trigger = function (eventType) {
  962. var args = [];
  963. for (var _i = 1; _i < arguments.length; _i++) {
  964. args[_i - 1] = arguments[_i];
  965. }
  966. if (!this._$handlers) {
  967. return this;
  968. }
  969. var _h = this._$handlers[eventType];
  970. var eventProcessor = this._$eventProcessor;
  971. if (_h) {
  972. var argLen = args.length;
  973. var len = _h.length;
  974. for (var i = 0; i < len; i++) {
  975. var hItem = _h[i];
  976. if (eventProcessor
  977. && eventProcessor.filter
  978. && hItem.query != null
  979. && !eventProcessor.filter(eventType, hItem.query)) {
  980. continue;
  981. }
  982. switch (argLen) {
  983. case 0:
  984. hItem.h.call(hItem.ctx);
  985. break;
  986. case 1:
  987. hItem.h.call(hItem.ctx, args[0]);
  988. break;
  989. case 2:
  990. hItem.h.call(hItem.ctx, args[0], args[1]);
  991. break;
  992. default:
  993. hItem.h.apply(hItem.ctx, args);
  994. break;
  995. }
  996. }
  997. }
  998. eventProcessor && eventProcessor.afterTrigger
  999. && eventProcessor.afterTrigger(eventType);
  1000. return this;
  1001. };
  1002. Eventful.prototype.triggerWithContext = function (type) {
  1003. if (!this._$handlers) {
  1004. return this;
  1005. }
  1006. var _h = this._$handlers[type];
  1007. var eventProcessor = this._$eventProcessor;
  1008. if (_h) {
  1009. var args = arguments;
  1010. var argLen = args.length;
  1011. var ctx = args[argLen - 1];
  1012. var len = _h.length;
  1013. for (var i = 0; i < len; i++) {
  1014. var hItem = _h[i];
  1015. if (eventProcessor
  1016. && eventProcessor.filter
  1017. && hItem.query != null
  1018. && !eventProcessor.filter(type, hItem.query)) {
  1019. continue;
  1020. }
  1021. switch (argLen) {
  1022. case 0:
  1023. hItem.h.call(ctx);
  1024. break;
  1025. case 1:
  1026. hItem.h.call(ctx, args[0]);
  1027. break;
  1028. case 2:
  1029. hItem.h.call(ctx, args[0], args[1]);
  1030. break;
  1031. default:
  1032. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. eventProcessor && eventProcessor.afterTrigger
  1038. && eventProcessor.afterTrigger(type);
  1039. return this;
  1040. };
  1041. return Eventful;
  1042. }());
  1043. var LN2 = Math.log(2);
  1044. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1045. var cacheKey = rowMask + '-' + colMask;
  1046. var fullRank = rows.length;
  1047. if (detCache.hasOwnProperty(cacheKey)) {
  1048. return detCache[cacheKey];
  1049. }
  1050. if (rank === 1) {
  1051. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1052. return rows[rowStart][colStart];
  1053. }
  1054. var subRowMask = rowMask | (1 << rowStart);
  1055. var subRowStart = rowStart + 1;
  1056. while (rowMask & (1 << subRowStart)) {
  1057. subRowStart++;
  1058. }
  1059. var sum = 0;
  1060. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1061. var colTag = 1 << j;
  1062. if (!(colTag & colMask)) {
  1063. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1064. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1065. colLocalIdx++;
  1066. }
  1067. }
  1068. detCache[cacheKey] = sum;
  1069. return sum;
  1070. }
  1071. function buildTransformer(src, dest) {
  1072. var mA = [
  1073. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1074. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1075. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1076. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1077. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1078. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1079. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1080. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1081. ];
  1082. var detCache = {};
  1083. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1084. if (det === 0) {
  1085. return;
  1086. }
  1087. var vh = [];
  1088. for (var i = 0; i < 8; i++) {
  1089. for (var j = 0; j < 8; j++) {
  1090. vh[j] == null && (vh[j] = 0);
  1091. vh[j] += ((i + j) % 2 ? -1 : 1)
  1092. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1093. / det * dest[i];
  1094. }
  1095. }
  1096. return function (out, srcPointX, srcPointY) {
  1097. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1098. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1099. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1100. };
  1101. }
  1102. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1103. var _calcOut = [];
  1104. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1105. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1106. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1107. }
  1108. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1109. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1110. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1111. var markers = prepareCoordMarkers(el, saved);
  1112. var transformer = preparePointerTransformer(markers, saved, inverse);
  1113. if (transformer) {
  1114. transformer(out, inX, inY);
  1115. return true;
  1116. }
  1117. }
  1118. return false;
  1119. }
  1120. function prepareCoordMarkers(el, saved) {
  1121. var markers = saved.markers;
  1122. if (markers) {
  1123. return markers;
  1124. }
  1125. markers = saved.markers = [];
  1126. var propLR = ['left', 'right'];
  1127. var propTB = ['top', 'bottom'];
  1128. for (var i = 0; i < 4; i++) {
  1129. var marker = document.createElement('div');
  1130. var stl = marker.style;
  1131. var idxLR = i % 2;
  1132. var idxTB = (i >> 1) % 2;
  1133. stl.cssText = [
  1134. 'position: absolute',
  1135. 'visibility: hidden',
  1136. 'padding: 0',
  1137. 'margin: 0',
  1138. 'border-width: 0',
  1139. 'user-select: none',
  1140. 'width:0',
  1141. 'height:0',
  1142. propLR[idxLR] + ':0',
  1143. propTB[idxTB] + ':0',
  1144. propLR[1 - idxLR] + ':auto',
  1145. propTB[1 - idxTB] + ':auto',
  1146. ''
  1147. ].join('!important;');
  1148. el.appendChild(marker);
  1149. markers.push(marker);
  1150. }
  1151. return markers;
  1152. }
  1153. function preparePointerTransformer(markers, saved, inverse) {
  1154. var transformerName = inverse ? 'invTrans' : 'trans';
  1155. var transformer = saved[transformerName];
  1156. var oldSrcCoords = saved.srcCoords;
  1157. var srcCoords = [];
  1158. var destCoords = [];
  1159. var oldCoordTheSame = true;
  1160. for (var i = 0; i < 4; i++) {
  1161. var rect = markers[i].getBoundingClientRect();
  1162. var ii = 2 * i;
  1163. var x = rect.left;
  1164. var y = rect.top;
  1165. srcCoords.push(x, y);
  1166. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1167. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1168. }
  1169. return (oldCoordTheSame && transformer)
  1170. ? transformer
  1171. : (saved.srcCoords = srcCoords,
  1172. saved[transformerName] = inverse
  1173. ? buildTransformer(destCoords, srcCoords)
  1174. : buildTransformer(srcCoords, destCoords));
  1175. }
  1176. function isCanvasEl(el) {
  1177. return el.nodeName.toUpperCase() === 'CANVAS';
  1178. }
  1179. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1180. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1181. var _calcOut$1 = [];
  1182. function clientToLocal(el, e, out, calculate) {
  1183. out = out || {};
  1184. if (calculate || !env.canvasSupported) {
  1185. calculateZrXY(el, e, out);
  1186. }
  1187. else if (env.browser.firefox
  1188. && e.layerX != null
  1189. && e.layerX !== e.offsetX) {
  1190. out.zrX = e.layerX;
  1191. out.zrY = e.layerY;
  1192. }
  1193. else if (e.offsetX != null) {
  1194. out.zrX = e.offsetX;
  1195. out.zrY = e.offsetY;
  1196. }
  1197. else {
  1198. calculateZrXY(el, e, out);
  1199. }
  1200. return out;
  1201. }
  1202. function calculateZrXY(el, e, out) {
  1203. if (env.domSupported && el.getBoundingClientRect) {
  1204. var ex = e.clientX;
  1205. var ey = e.clientY;
  1206. if (isCanvasEl(el)) {
  1207. var box = el.getBoundingClientRect();
  1208. out.zrX = ex - box.left;
  1209. out.zrY = ey - box.top;
  1210. return;
  1211. }
  1212. else {
  1213. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1214. out.zrX = _calcOut$1[0];
  1215. out.zrY = _calcOut$1[1];
  1216. return;
  1217. }
  1218. }
  1219. }
  1220. out.zrX = out.zrY = 0;
  1221. }
  1222. function getNativeEvent(e) {
  1223. return e
  1224. || window.event;
  1225. }
  1226. function normalizeEvent(el, e, calculate) {
  1227. e = getNativeEvent(e);
  1228. if (e.zrX != null) {
  1229. return e;
  1230. }
  1231. var eventType = e.type;
  1232. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1233. if (!isTouch) {
  1234. clientToLocal(el, e, e, calculate);
  1235. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1236. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1237. }
  1238. else {
  1239. var touch = eventType !== 'touchend'
  1240. ? e.targetTouches[0]
  1241. : e.changedTouches[0];
  1242. touch && clientToLocal(el, touch, e, calculate);
  1243. }
  1244. var button = e.button;
  1245. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1246. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1247. }
  1248. return e;
  1249. }
  1250. function getWheelDeltaMayPolyfill(e) {
  1251. var rawWheelDelta = e.wheelDelta;
  1252. if (rawWheelDelta) {
  1253. return rawWheelDelta;
  1254. }
  1255. var deltaX = e.deltaX;
  1256. var deltaY = e.deltaY;
  1257. if (deltaX == null || deltaY == null) {
  1258. return rawWheelDelta;
  1259. }
  1260. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1261. var sign = deltaY > 0 ? -1
  1262. : deltaY < 0 ? 1
  1263. : deltaX > 0 ? -1
  1264. : 1;
  1265. return 3 * delta * sign;
  1266. }
  1267. function addEventListener(el, name, handler, opt) {
  1268. if (isDomLevel2) {
  1269. el.addEventListener(name, handler, opt);
  1270. }
  1271. else {
  1272. el.attachEvent('on' + name, handler);
  1273. }
  1274. }
  1275. function removeEventListener(el, name, handler, opt) {
  1276. if (isDomLevel2) {
  1277. el.removeEventListener(name, handler, opt);
  1278. }
  1279. else {
  1280. el.detachEvent('on' + name, handler);
  1281. }
  1282. }
  1283. var stop = isDomLevel2
  1284. ? function (e) {
  1285. e.preventDefault();
  1286. e.stopPropagation();
  1287. e.cancelBubble = true;
  1288. }
  1289. : function (e) {
  1290. e.returnValue = false;
  1291. e.cancelBubble = true;
  1292. };
  1293. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1294. return e.which === 2 || e.which === 3;
  1295. }
  1296. var GestureMgr = (function () {
  1297. function GestureMgr() {
  1298. this._track = [];
  1299. }
  1300. GestureMgr.prototype.recognize = function (event, target, root) {
  1301. this._doTrack(event, target, root);
  1302. return this._recognize(event);
  1303. };
  1304. GestureMgr.prototype.clear = function () {
  1305. this._track.length = 0;
  1306. return this;
  1307. };
  1308. GestureMgr.prototype._doTrack = function (event, target, root) {
  1309. var touches = event.touches;
  1310. if (!touches) {
  1311. return;
  1312. }
  1313. var trackItem = {
  1314. points: [],
  1315. touches: [],
  1316. target: target,
  1317. event: event
  1318. };
  1319. for (var i = 0, len = touches.length; i < len; i++) {
  1320. var touch = touches[i];
  1321. var pos = clientToLocal(root, touch, {});
  1322. trackItem.points.push([pos.zrX, pos.zrY]);
  1323. trackItem.touches.push(touch);
  1324. }
  1325. this._track.push(trackItem);
  1326. };
  1327. GestureMgr.prototype._recognize = function (event) {
  1328. for (var eventName in recognizers) {
  1329. if (recognizers.hasOwnProperty(eventName)) {
  1330. var gestureInfo = recognizers[eventName](this._track, event);
  1331. if (gestureInfo) {
  1332. return gestureInfo;
  1333. }
  1334. }
  1335. }
  1336. };
  1337. return GestureMgr;
  1338. }());
  1339. function dist$1(pointPair) {
  1340. var dx = pointPair[1][0] - pointPair[0][0];
  1341. var dy = pointPair[1][1] - pointPair[0][1];
  1342. return Math.sqrt(dx * dx + dy * dy);
  1343. }
  1344. function center(pointPair) {
  1345. return [
  1346. (pointPair[0][0] + pointPair[1][0]) / 2,
  1347. (pointPair[0][1] + pointPair[1][1]) / 2
  1348. ];
  1349. }
  1350. var recognizers = {
  1351. pinch: function (tracks, event) {
  1352. var trackLen = tracks.length;
  1353. if (!trackLen) {
  1354. return;
  1355. }
  1356. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1357. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1358. if (pinchPre
  1359. && pinchPre.length > 1
  1360. && pinchEnd
  1361. && pinchEnd.length > 1) {
  1362. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1363. !isFinite(pinchScale) && (pinchScale = 1);
  1364. event.pinchScale = pinchScale;
  1365. var pinchCenter = center(pinchEnd);
  1366. event.pinchX = pinchCenter[0];
  1367. event.pinchY = pinchCenter[1];
  1368. return {
  1369. type: 'pinch',
  1370. target: tracks[0].target,
  1371. event: event
  1372. };
  1373. }
  1374. }
  1375. };
  1376. var SILENT = 'silent';
  1377. function makeEventPacket(eveType, targetInfo, event) {
  1378. return {
  1379. type: eveType,
  1380. event: event,
  1381. target: targetInfo.target,
  1382. topTarget: targetInfo.topTarget,
  1383. cancelBubble: false,
  1384. offsetX: event.zrX,
  1385. offsetY: event.zrY,
  1386. gestureEvent: event.gestureEvent,
  1387. pinchX: event.pinchX,
  1388. pinchY: event.pinchY,
  1389. pinchScale: event.pinchScale,
  1390. wheelDelta: event.zrDelta,
  1391. zrByTouch: event.zrByTouch,
  1392. which: event.which,
  1393. stop: stopEvent
  1394. };
  1395. }
  1396. function stopEvent() {
  1397. stop(this.event);
  1398. }
  1399. var EmptyProxy = (function (_super) {
  1400. __extends(EmptyProxy, _super);
  1401. function EmptyProxy() {
  1402. var _this = _super !== null && _super.apply(this, arguments) || this;
  1403. _this.handler = null;
  1404. return _this;
  1405. }
  1406. EmptyProxy.prototype.dispose = function () { };
  1407. EmptyProxy.prototype.setCursor = function () { };
  1408. return EmptyProxy;
  1409. }(Eventful));
  1410. var HoveredResult = (function () {
  1411. function HoveredResult(x, y) {
  1412. this.x = x;
  1413. this.y = y;
  1414. }
  1415. return HoveredResult;
  1416. }());
  1417. var handlerNames = [
  1418. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1419. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1420. ];
  1421. var Handler = (function (_super) {
  1422. __extends(Handler, _super);
  1423. function Handler(storage, painter, proxy, painterRoot) {
  1424. var _this = _super.call(this) || this;
  1425. _this._hovered = new HoveredResult(0, 0);
  1426. _this.storage = storage;
  1427. _this.painter = painter;
  1428. _this.painterRoot = painterRoot;
  1429. proxy = proxy || new EmptyProxy();
  1430. _this.proxy = null;
  1431. _this.setHandlerProxy(proxy);
  1432. _this._draggingMgr = new Draggable(_this);
  1433. return _this;
  1434. }
  1435. Handler.prototype.setHandlerProxy = function (proxy) {
  1436. if (this.proxy) {
  1437. this.proxy.dispose();
  1438. }
  1439. if (proxy) {
  1440. each(handlerNames, function (name) {
  1441. proxy.on && proxy.on(name, this[name], this);
  1442. }, this);
  1443. proxy.handler = this;
  1444. }
  1445. this.proxy = proxy;
  1446. };
  1447. Handler.prototype.mousemove = function (event) {
  1448. var x = event.zrX;
  1449. var y = event.zrY;
  1450. var isOutside = isOutsideBoundary(this, x, y);
  1451. var lastHovered = this._hovered;
  1452. var lastHoveredTarget = lastHovered.target;
  1453. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1454. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1455. lastHoveredTarget = lastHovered.target;
  1456. }
  1457. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  1458. var hoveredTarget = hovered.target;
  1459. var proxy = this.proxy;
  1460. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1461. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1462. this.dispatchToElement(lastHovered, 'mouseout', event);
  1463. }
  1464. this.dispatchToElement(hovered, 'mousemove', event);
  1465. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1466. this.dispatchToElement(hovered, 'mouseover', event);
  1467. }
  1468. };
  1469. Handler.prototype.mouseout = function (event) {
  1470. var eventControl = event.zrEventControl;
  1471. if (eventControl !== 'only_globalout') {
  1472. this.dispatchToElement(this._hovered, 'mouseout', event);
  1473. }
  1474. if (eventControl !== 'no_globalout') {
  1475. this.trigger('globalout', { type: 'globalout', event: event });
  1476. }
  1477. };
  1478. Handler.prototype.resize = function () {
  1479. this._hovered = new HoveredResult(0, 0);
  1480. };
  1481. Handler.prototype.dispatch = function (eventName, eventArgs) {
  1482. var handler = this[eventName];
  1483. handler && handler.call(this, eventArgs);
  1484. };
  1485. Handler.prototype.dispose = function () {
  1486. this.proxy.dispose();
  1487. this.storage = null;
  1488. this.proxy = null;
  1489. this.painter = null;
  1490. };
  1491. Handler.prototype.setCursorStyle = function (cursorStyle) {
  1492. var proxy = this.proxy;
  1493. proxy.setCursor && proxy.setCursor(cursorStyle);
  1494. };
  1495. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  1496. targetInfo = targetInfo || {};
  1497. var el = targetInfo.target;
  1498. if (el && el.silent) {
  1499. return;
  1500. }
  1501. var eventKey = ('on' + eventName);
  1502. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1503. while (el) {
  1504. el[eventKey]
  1505. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  1506. el.trigger(eventName, eventPacket);
  1507. el = el.__hostTarget ? el.__hostTarget : el.parent;
  1508. if (eventPacket.cancelBubble) {
  1509. break;
  1510. }
  1511. }
  1512. if (!eventPacket.cancelBubble) {
  1513. this.trigger(eventName, eventPacket);
  1514. if (this.painter && this.painter.eachOtherLayer) {
  1515. this.painter.eachOtherLayer(function (layer) {
  1516. if (typeof (layer[eventKey]) === 'function') {
  1517. layer[eventKey].call(layer, eventPacket);
  1518. }
  1519. if (layer.trigger) {
  1520. layer.trigger(eventName, eventPacket);
  1521. }
  1522. });
  1523. }
  1524. }
  1525. };
  1526. Handler.prototype.findHover = function (x, y, exclude) {
  1527. var list = this.storage.getDisplayList();
  1528. var out = new HoveredResult(x, y);
  1529. for (var i = list.length - 1; i >= 0; i--) {
  1530. var hoverCheckResult = void 0;
  1531. if (list[i] !== exclude
  1532. && !list[i].ignore
  1533. && (hoverCheckResult = isHover(list[i], x, y))) {
  1534. !out.topTarget && (out.topTarget = list[i]);
  1535. if (hoverCheckResult !== SILENT) {
  1536. out.target = list[i];
  1537. break;
  1538. }
  1539. }
  1540. }
  1541. return out;
  1542. };
  1543. Handler.prototype.processGesture = function (event, stage) {
  1544. if (!this._gestureMgr) {
  1545. this._gestureMgr = new GestureMgr();
  1546. }
  1547. var gestureMgr = this._gestureMgr;
  1548. stage === 'start' && gestureMgr.clear();
  1549. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  1550. stage === 'end' && gestureMgr.clear();
  1551. if (gestureInfo) {
  1552. var type = gestureInfo.type;
  1553. event.gestureEvent = type;
  1554. var res = new HoveredResult();
  1555. res.target = gestureInfo.target;
  1556. this.dispatchToElement(res, type, gestureInfo.event);
  1557. }
  1558. };
  1559. return Handler;
  1560. }(Eventful));
  1561. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1562. Handler.prototype[name] = function (event) {
  1563. var x = event.zrX;
  1564. var y = event.zrY;
  1565. var isOutside = isOutsideBoundary(this, x, y);
  1566. var hovered;
  1567. var hoveredTarget;
  1568. if (name !== 'mouseup' || !isOutside) {
  1569. hovered = this.findHover(x, y);
  1570. hoveredTarget = hovered.target;
  1571. }
  1572. if (name === 'mousedown') {
  1573. this._downEl = hoveredTarget;
  1574. this._downPoint = [event.zrX, event.zrY];
  1575. this._upEl = hoveredTarget;
  1576. }
  1577. else if (name === 'mouseup') {
  1578. this._upEl = hoveredTarget;
  1579. }
  1580. else if (name === 'click') {
  1581. if (this._downEl !== this._upEl
  1582. || !this._downPoint
  1583. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  1584. return;
  1585. }
  1586. this._downPoint = null;
  1587. }
  1588. this.dispatchToElement(hovered, name, event);
  1589. };
  1590. });
  1591. function isHover(displayable, x, y) {
  1592. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1593. var el = displayable;
  1594. var isSilent = void 0;
  1595. var ignoreClip = false;
  1596. while (el) {
  1597. if (el.ignoreClip) {
  1598. ignoreClip = true;
  1599. }
  1600. if (!ignoreClip) {
  1601. var clipPath = el.getClipPath();
  1602. if (clipPath && !clipPath.contain(x, y)) {
  1603. return false;
  1604. }
  1605. if (el.silent) {
  1606. isSilent = true;
  1607. }
  1608. }
  1609. var hostEl = el.__hostTarget;
  1610. el = hostEl ? hostEl : el.parent;
  1611. }
  1612. return isSilent ? SILENT : true;
  1613. }
  1614. return false;
  1615. }
  1616. function isOutsideBoundary(handlerInstance, x, y) {
  1617. var painter = handlerInstance.painter;
  1618. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  1619. }
  1620. function create$1() {
  1621. return [1, 0, 0, 1, 0, 0];
  1622. }
  1623. function identity(out) {
  1624. out[0] = 1;
  1625. out[1] = 0;
  1626. out[2] = 0;
  1627. out[3] = 1;
  1628. out[4] = 0;
  1629. out[5] = 0;
  1630. return out;
  1631. }
  1632. function copy$1(out, m) {
  1633. out[0] = m[0];
  1634. out[1] = m[1];
  1635. out[2] = m[2];
  1636. out[3] = m[3];
  1637. out[4] = m[4];
  1638. out[5] = m[5];
  1639. return out;
  1640. }
  1641. function mul$1(out, m1, m2) {
  1642. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1643. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1644. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1645. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1646. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1647. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1648. out[0] = out0;
  1649. out[1] = out1;
  1650. out[2] = out2;
  1651. out[3] = out3;
  1652. out[4] = out4;
  1653. out[5] = out5;
  1654. return out;
  1655. }
  1656. function translate(out, a, v) {
  1657. out[0] = a[0];
  1658. out[1] = a[1];
  1659. out[2] = a[2];
  1660. out[3] = a[3];
  1661. out[4] = a[4] + v[0];
  1662. out[5] = a[5] + v[1];
  1663. return out;
  1664. }
  1665. function rotate(out, a, rad) {
  1666. var aa = a[0];
  1667. var ac = a[2];
  1668. var atx = a[4];
  1669. var ab = a[1];
  1670. var ad = a[3];
  1671. var aty = a[5];
  1672. var st = Math.sin(rad);
  1673. var ct = Math.cos(rad);
  1674. out[0] = aa * ct + ab * st;
  1675. out[1] = -aa * st + ab * ct;
  1676. out[2] = ac * ct + ad * st;
  1677. out[3] = -ac * st + ct * ad;
  1678. out[4] = ct * atx + st * aty;
  1679. out[5] = ct * aty - st * atx;
  1680. return out;
  1681. }
  1682. function scale$1(out, a, v) {
  1683. var vx = v[0];
  1684. var vy = v[1];
  1685. out[0] = a[0] * vx;
  1686. out[1] = a[1] * vy;
  1687. out[2] = a[2] * vx;
  1688. out[3] = a[3] * vy;
  1689. out[4] = a[4] * vx;
  1690. out[5] = a[5] * vy;
  1691. return out;
  1692. }
  1693. function invert(out, a) {
  1694. var aa = a[0];
  1695. var ac = a[2];
  1696. var atx = a[4];
  1697. var ab = a[1];
  1698. var ad = a[3];
  1699. var aty = a[5];
  1700. var det = aa * ad - ab * ac;
  1701. if (!det) {
  1702. return null;
  1703. }
  1704. det = 1.0 / det;
  1705. out[0] = ad * det;
  1706. out[1] = -ab * det;
  1707. out[2] = -ac * det;
  1708. out[3] = aa * det;
  1709. out[4] = (ac * aty - ad * atx) * det;
  1710. out[5] = (ab * atx - aa * aty) * det;
  1711. return out;
  1712. }
  1713. function clone$2(a) {
  1714. var b = create$1();
  1715. copy$1(b, a);
  1716. return b;
  1717. }
  1718. var matrix = /*#__PURE__*/Object.freeze({
  1719. __proto__: null,
  1720. create: create$1,
  1721. identity: identity,
  1722. copy: copy$1,
  1723. mul: mul$1,
  1724. translate: translate,
  1725. rotate: rotate,
  1726. scale: scale$1,
  1727. invert: invert,
  1728. clone: clone$2
  1729. });
  1730. var mIdentity = identity;
  1731. var EPSILON = 5e-5;
  1732. function isNotAroundZero(val) {
  1733. return val > EPSILON || val < -EPSILON;
  1734. }
  1735. var scaleTmp = [];
  1736. var tmpTransform = [];
  1737. var originTransform = create$1();
  1738. var abs = Math.abs;
  1739. var Transformable = (function () {
  1740. function Transformable() {
  1741. }
  1742. Transformable.prototype.setPosition = function (arr) {
  1743. this.x = arr[0];
  1744. this.y = arr[1];
  1745. };
  1746. Transformable.prototype.setScale = function (arr) {
  1747. this.scaleX = arr[0];
  1748. this.scaleY = arr[1];
  1749. };
  1750. Transformable.prototype.setOrigin = function (arr) {
  1751. this.originX = arr[0];
  1752. this.originY = arr[1];
  1753. };
  1754. Transformable.prototype.needLocalTransform = function () {
  1755. return isNotAroundZero(this.rotation)
  1756. || isNotAroundZero(this.x)
  1757. || isNotAroundZero(this.y)
  1758. || isNotAroundZero(this.scaleX - 1)
  1759. || isNotAroundZero(this.scaleY - 1);
  1760. };
  1761. Transformable.prototype.updateTransform = function () {
  1762. var parent = this.parent;
  1763. var parentHasTransform = parent && parent.transform;
  1764. var needLocalTransform = this.needLocalTransform();
  1765. var m = this.transform;
  1766. if (!(needLocalTransform || parentHasTransform)) {
  1767. m && mIdentity(m);
  1768. return;
  1769. }
  1770. m = m || create$1();
  1771. if (needLocalTransform) {
  1772. this.getLocalTransform(m);
  1773. }
  1774. else {
  1775. mIdentity(m);
  1776. }
  1777. if (parentHasTransform) {
  1778. if (needLocalTransform) {
  1779. mul$1(m, parent.transform, m);
  1780. }
  1781. else {
  1782. copy$1(m, parent.transform);
  1783. }
  1784. }
  1785. this.transform = m;
  1786. this._resolveGlobalScaleRatio(m);
  1787. };
  1788. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  1789. var globalScaleRatio = this.globalScaleRatio;
  1790. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  1791. this.getGlobalScale(scaleTmp);
  1792. var relX = scaleTmp[0] < 0 ? -1 : 1;
  1793. var relY = scaleTmp[1] < 0 ? -1 : 1;
  1794. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  1795. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  1796. m[0] *= sx;
  1797. m[1] *= sx;
  1798. m[2] *= sy;
  1799. m[3] *= sy;
  1800. }
  1801. this.invTransform = this.invTransform || create$1();
  1802. invert(this.invTransform, m);
  1803. };
  1804. Transformable.prototype.getLocalTransform = function (m) {
  1805. return Transformable.getLocalTransform(this, m);
  1806. };
  1807. Transformable.prototype.getComputedTransform = function () {
  1808. var transformNode = this;
  1809. var ancestors = [];
  1810. while (transformNode) {
  1811. ancestors.push(transformNode);
  1812. transformNode = transformNode.parent;
  1813. }
  1814. while (transformNode = ancestors.pop()) {
  1815. transformNode.updateTransform();
  1816. }
  1817. return this.transform;
  1818. };
  1819. Transformable.prototype.setLocalTransform = function (m) {
  1820. if (!m) {
  1821. return;
  1822. }
  1823. var sx = m[0] * m[0] + m[1] * m[1];
  1824. var sy = m[2] * m[2] + m[3] * m[3];
  1825. if (isNotAroundZero(sx - 1)) {
  1826. sx = Math.sqrt(sx);
  1827. }
  1828. if (isNotAroundZero(sy - 1)) {
  1829. sy = Math.sqrt(sy);
  1830. }
  1831. if (m[0] < 0) {
  1832. sx = -sx;
  1833. }
  1834. if (m[3] < 0) {
  1835. sy = -sy;
  1836. }
  1837. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1838. if (sx < 0 && sy < 0) {
  1839. this.rotation += Math.PI;
  1840. sx = -sx;
  1841. sy = -sy;
  1842. }
  1843. this.x = m[4];
  1844. this.y = m[5];
  1845. this.scaleX = sx;
  1846. this.scaleY = sy;
  1847. };
  1848. Transformable.prototype.decomposeTransform = function () {
  1849. if (!this.transform) {
  1850. return;
  1851. }
  1852. var parent = this.parent;
  1853. var m = this.transform;
  1854. if (parent && parent.transform) {
  1855. mul$1(tmpTransform, parent.invTransform, m);
  1856. m = tmpTransform;
  1857. }
  1858. var ox = this.originX;
  1859. var oy = this.originY;
  1860. if (ox || oy) {
  1861. originTransform[4] = ox;
  1862. originTransform[5] = oy;
  1863. mul$1(tmpTransform, m, originTransform);
  1864. tmpTransform[4] -= ox;
  1865. tmpTransform[5] -= oy;
  1866. m = tmpTransform;
  1867. }
  1868. this.setLocalTransform(m);
  1869. };
  1870. Transformable.prototype.getGlobalScale = function (out) {
  1871. var m = this.transform;
  1872. out = out || [];
  1873. if (!m) {
  1874. out[0] = 1;
  1875. out[1] = 1;
  1876. return out;
  1877. }
  1878. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1879. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1880. if (m[0] < 0) {
  1881. out[0] = -out[0];
  1882. }
  1883. if (m[3] < 0) {
  1884. out[1] = -out[1];
  1885. }
  1886. return out;
  1887. };
  1888. Transformable.prototype.transformCoordToLocal = function (x, y) {
  1889. var v2 = [x, y];
  1890. var invTransform = this.invTransform;
  1891. if (invTransform) {
  1892. applyTransform(v2, v2, invTransform);
  1893. }
  1894. return v2;
  1895. };
  1896. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  1897. var v2 = [x, y];
  1898. var transform = this.transform;
  1899. if (transform) {
  1900. applyTransform(v2, v2, transform);
  1901. }
  1902. return v2;
  1903. };
  1904. Transformable.prototype.getLineScale = function () {
  1905. var m = this.transform;
  1906. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  1907. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  1908. : 1;
  1909. };
  1910. Transformable.getLocalTransform = function (target, m) {
  1911. m = m || [];
  1912. mIdentity(m);
  1913. var ox = target.originX || 0;
  1914. var oy = target.originY || 0;
  1915. var sx = target.scaleX;
  1916. var sy = target.scaleY;
  1917. var rotation = target.rotation || 0;
  1918. var x = target.x;
  1919. var y = target.y;
  1920. m[4] -= ox;
  1921. m[5] -= oy;
  1922. m[0] *= sx;
  1923. m[1] *= sy;
  1924. m[2] *= sx;
  1925. m[3] *= sy;
  1926. m[4] *= sx;
  1927. m[5] *= sy;
  1928. if (rotation) {
  1929. rotate(m, m, rotation);
  1930. }
  1931. m[4] += ox;
  1932. m[5] += oy;
  1933. m[4] += x;
  1934. m[5] += y;
  1935. return m;
  1936. };
  1937. Transformable.initDefaultProps = (function () {
  1938. var proto = Transformable.prototype;
  1939. proto.x = 0;
  1940. proto.y = 0;
  1941. proto.scaleX = 1;
  1942. proto.scaleY = 1;
  1943. proto.originX = 0;
  1944. proto.originY = 0;
  1945. proto.rotation = 0;
  1946. proto.globalScaleRatio = 1;
  1947. })();
  1948. return Transformable;
  1949. }());
  1950. var easing = {
  1951. linear: function (k) {
  1952. return k;
  1953. },
  1954. quadraticIn: function (k) {
  1955. return k * k;
  1956. },
  1957. quadraticOut: function (k) {
  1958. return k * (2 - k);
  1959. },
  1960. quadraticInOut: function (k) {
  1961. if ((k *= 2) < 1) {
  1962. return 0.5 * k * k;
  1963. }
  1964. return -0.5 * (--k * (k - 2) - 1);
  1965. },
  1966. cubicIn: function (k) {
  1967. return k * k * k;
  1968. },
  1969. cubicOut: function (k) {
  1970. return --k * k * k + 1;
  1971. },
  1972. cubicInOut: function (k) {
  1973. if ((k *= 2) < 1) {
  1974. return 0.5 * k * k * k;
  1975. }
  1976. return 0.5 * ((k -= 2) * k * k + 2);
  1977. },
  1978. quarticIn: function (k) {
  1979. return k * k * k * k;
  1980. },
  1981. quarticOut: function (k) {
  1982. return 1 - (--k * k * k * k);
  1983. },
  1984. quarticInOut: function (k) {
  1985. if ((k *= 2) < 1) {
  1986. return 0.5 * k * k * k * k;
  1987. }
  1988. return -0.5 * ((k -= 2) * k * k * k - 2);
  1989. },
  1990. quinticIn: function (k) {
  1991. return k * k * k * k * k;
  1992. },
  1993. quinticOut: function (k) {
  1994. return --k * k * k * k * k + 1;
  1995. },
  1996. quinticInOut: function (k) {
  1997. if ((k *= 2) < 1) {
  1998. return 0.5 * k * k * k * k * k;
  1999. }
  2000. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2001. },
  2002. sinusoidalIn: function (k) {
  2003. return 1 - Math.cos(k * Math.PI / 2);
  2004. },
  2005. sinusoidalOut: function (k) {
  2006. return Math.sin(k * Math.PI / 2);
  2007. },
  2008. sinusoidalInOut: function (k) {
  2009. return 0.5 * (1 - Math.cos(Math.PI * k));
  2010. },
  2011. exponentialIn: function (k) {
  2012. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2013. },
  2014. exponentialOut: function (k) {
  2015. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2016. },
  2017. exponentialInOut: function (k) {
  2018. if (k === 0) {
  2019. return 0;
  2020. }
  2021. if (k === 1) {
  2022. return 1;
  2023. }
  2024. if ((k *= 2) < 1) {
  2025. return 0.5 * Math.pow(1024, k - 1);
  2026. }
  2027. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2028. },
  2029. circularIn: function (k) {
  2030. return 1 - Math.sqrt(1 - k * k);
  2031. },
  2032. circularOut: function (k) {
  2033. return Math.sqrt(1 - (--k * k));
  2034. },
  2035. circularInOut: function (k) {
  2036. if ((k *= 2) < 1) {
  2037. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2038. }
  2039. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2040. },
  2041. elasticIn: function (k) {
  2042. var s;
  2043. var a = 0.1;
  2044. var p = 0.4;
  2045. if (k === 0) {
  2046. return 0;
  2047. }
  2048. if (k === 1) {
  2049. return 1;
  2050. }
  2051. if (!a || a < 1) {
  2052. a = 1;
  2053. s = p / 4;
  2054. }
  2055. else {
  2056. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2057. }
  2058. return -(a * Math.pow(2, 10 * (k -= 1))
  2059. * Math.sin((k - s) * (2 * Math.PI) / p));
  2060. },
  2061. elasticOut: function (k) {
  2062. var s;
  2063. var a = 0.1;
  2064. var p = 0.4;
  2065. if (k === 0) {
  2066. return 0;
  2067. }
  2068. if (k === 1) {
  2069. return 1;
  2070. }
  2071. if (!a || a < 1) {
  2072. a = 1;
  2073. s = p / 4;
  2074. }
  2075. else {
  2076. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2077. }
  2078. return (a * Math.pow(2, -10 * k)
  2079. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2080. },
  2081. elasticInOut: function (k) {
  2082. var s;
  2083. var a = 0.1;
  2084. var p = 0.4;
  2085. if (k === 0) {
  2086. return 0;
  2087. }
  2088. if (k === 1) {
  2089. return 1;
  2090. }
  2091. if (!a || a < 1) {
  2092. a = 1;
  2093. s = p / 4;
  2094. }
  2095. else {
  2096. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2097. }
  2098. if ((k *= 2) < 1) {
  2099. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2100. * Math.sin((k - s) * (2 * Math.PI) / p));
  2101. }
  2102. return a * Math.pow(2, -10 * (k -= 1))
  2103. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2104. },
  2105. backIn: function (k) {
  2106. var s = 1.70158;
  2107. return k * k * ((s + 1) * k - s);
  2108. },
  2109. backOut: function (k) {
  2110. var s = 1.70158;
  2111. return --k * k * ((s + 1) * k + s) + 1;
  2112. },
  2113. backInOut: function (k) {
  2114. var s = 1.70158 * 1.525;
  2115. if ((k *= 2) < 1) {
  2116. return 0.5 * (k * k * ((s + 1) * k - s));
  2117. }
  2118. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2119. },
  2120. bounceIn: function (k) {
  2121. return 1 - easing.bounceOut(1 - k);
  2122. },
  2123. bounceOut: function (k) {
  2124. if (k < (1 / 2.75)) {
  2125. return 7.5625 * k * k;
  2126. }
  2127. else if (k < (2 / 2.75)) {
  2128. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2129. }
  2130. else if (k < (2.5 / 2.75)) {
  2131. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2132. }
  2133. else {
  2134. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2135. }
  2136. },
  2137. bounceInOut: function (k) {
  2138. if (k < 0.5) {
  2139. return easing.bounceIn(k * 2) * 0.5;
  2140. }
  2141. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2142. }
  2143. };
  2144. var Clip = (function () {
  2145. function Clip(opts) {
  2146. this._initialized = false;
  2147. this._startTime = 0;
  2148. this._pausedTime = 0;
  2149. this._paused = false;
  2150. this._life = opts.life || 1000;
  2151. this._delay = opts.delay || 0;
  2152. this.loop = opts.loop == null ? false : opts.loop;
  2153. this.gap = opts.gap || 0;
  2154. this.easing = opts.easing || 'linear';
  2155. this.onframe = opts.onframe;
  2156. this.ondestroy = opts.ondestroy;
  2157. this.onrestart = opts.onrestart;
  2158. }
  2159. Clip.prototype.step = function (globalTime, deltaTime) {
  2160. if (!this._initialized) {
  2161. this._startTime = globalTime + this._delay;
  2162. this._initialized = true;
  2163. }
  2164. if (this._paused) {
  2165. this._pausedTime += deltaTime;
  2166. return;
  2167. }
  2168. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2169. if (percent < 0) {
  2170. percent = 0;
  2171. }
  2172. percent = Math.min(percent, 1);
  2173. var easing$1 = this.easing;
  2174. var easingFunc = typeof easing$1 === 'string'
  2175. ? easing[easing$1] : easing$1;
  2176. var schedule = typeof easingFunc === 'function'
  2177. ? easingFunc(percent)
  2178. : percent;
  2179. this.onframe && this.onframe(schedule);
  2180. if (percent === 1) {
  2181. if (this.loop) {
  2182. this._restart(globalTime);
  2183. this.onrestart && this.onrestart();
  2184. }
  2185. else {
  2186. return true;
  2187. }
  2188. }
  2189. return false;
  2190. };
  2191. Clip.prototype._restart = function (globalTime) {
  2192. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2193. this._startTime = globalTime - remainder + this.gap;
  2194. this._pausedTime = 0;
  2195. };
  2196. Clip.prototype.pause = function () {
  2197. this._paused = true;
  2198. };
  2199. Clip.prototype.resume = function () {
  2200. this._paused = false;
  2201. };
  2202. return Clip;
  2203. }());
  2204. var Entry = (function () {
  2205. function Entry(val) {
  2206. this.value = val;
  2207. }
  2208. return Entry;
  2209. }());
  2210. var LinkedList = (function () {
  2211. function LinkedList() {
  2212. this._len = 0;
  2213. }
  2214. LinkedList.prototype.insert = function (val) {
  2215. var entry = new Entry(val);
  2216. this.insertEntry(entry);
  2217. return entry;
  2218. };
  2219. LinkedList.prototype.insertEntry = function (entry) {
  2220. if (!this.head) {
  2221. this.head = this.tail = entry;
  2222. }
  2223. else {
  2224. this.tail.next = entry;
  2225. entry.prev = this.tail;
  2226. entry.next = null;
  2227. this.tail = entry;
  2228. }
  2229. this._len++;
  2230. };
  2231. LinkedList.prototype.remove = function (entry) {
  2232. var prev = entry.prev;
  2233. var next = entry.next;
  2234. if (prev) {
  2235. prev.next = next;
  2236. }
  2237. else {
  2238. this.head = next;
  2239. }
  2240. if (next) {
  2241. next.prev = prev;
  2242. }
  2243. else {
  2244. this.tail = prev;
  2245. }
  2246. entry.next = entry.prev = null;
  2247. this._len--;
  2248. };
  2249. LinkedList.prototype.len = function () {
  2250. return this._len;
  2251. };
  2252. LinkedList.prototype.clear = function () {
  2253. this.head = this.tail = null;
  2254. this._len = 0;
  2255. };
  2256. return LinkedList;
  2257. }());
  2258. var LRU = (function () {
  2259. function LRU(maxSize) {
  2260. this._list = new LinkedList();
  2261. this._maxSize = 10;
  2262. this._map = {};
  2263. this._maxSize = maxSize;
  2264. }
  2265. LRU.prototype.put = function (key, value) {
  2266. var list = this._list;
  2267. var map = this._map;
  2268. var removed = null;
  2269. if (map[key] == null) {
  2270. var len = list.len();
  2271. var entry = this._lastRemovedEntry;
  2272. if (len >= this._maxSize && len > 0) {
  2273. var leastUsedEntry = list.head;
  2274. list.remove(leastUsedEntry);
  2275. delete map[leastUsedEntry.key];
  2276. removed = leastUsedEntry.value;
  2277. this._lastRemovedEntry = leastUsedEntry;
  2278. }
  2279. if (entry) {
  2280. entry.value = value;
  2281. }
  2282. else {
  2283. entry = new Entry(value);
  2284. }
  2285. entry.key = key;
  2286. list.insertEntry(entry);
  2287. map[key] = entry;
  2288. }
  2289. return removed;
  2290. };
  2291. LRU.prototype.get = function (key) {
  2292. var entry = this._map[key];
  2293. var list = this._list;
  2294. if (entry != null) {
  2295. if (entry !== list.tail) {
  2296. list.remove(entry);
  2297. list.insertEntry(entry);
  2298. }
  2299. return entry.value;
  2300. }
  2301. };
  2302. LRU.prototype.clear = function () {
  2303. this._list.clear();
  2304. this._map = {};
  2305. };
  2306. LRU.prototype.len = function () {
  2307. return this._list.len();
  2308. };
  2309. return LRU;
  2310. }());
  2311. var kCSSColorTable = {
  2312. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  2313. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  2314. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  2315. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  2316. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  2317. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  2318. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  2319. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  2320. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  2321. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  2322. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  2323. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  2324. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  2325. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  2326. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  2327. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  2328. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  2329. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  2330. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  2331. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  2332. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  2333. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  2334. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  2335. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  2336. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  2337. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  2338. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  2339. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  2340. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  2341. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  2342. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  2343. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  2344. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  2345. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  2346. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  2347. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  2348. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  2349. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  2350. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  2351. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  2352. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  2353. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  2354. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  2355. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  2356. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  2357. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  2358. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  2359. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  2360. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  2361. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  2362. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  2363. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  2364. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  2365. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  2366. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  2367. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  2368. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  2369. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  2370. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  2371. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  2372. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  2373. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  2374. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  2375. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  2376. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  2377. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  2378. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  2379. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  2380. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  2381. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  2382. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  2383. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  2384. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  2385. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  2386. };
  2387. function clampCssByte(i) {
  2388. i = Math.round(i);
  2389. return i < 0 ? 0 : i > 255 ? 255 : i;
  2390. }
  2391. function clampCssAngle(i) {
  2392. i = Math.round(i);
  2393. return i < 0 ? 0 : i > 360 ? 360 : i;
  2394. }
  2395. function clampCssFloat(f) {
  2396. return f < 0 ? 0 : f > 1 ? 1 : f;
  2397. }
  2398. function parseCssInt(val) {
  2399. var str = val;
  2400. if (str.length && str.charAt(str.length - 1) === '%') {
  2401. return clampCssByte(parseFloat(str) / 100 * 255);
  2402. }
  2403. return clampCssByte(parseInt(str, 10));
  2404. }
  2405. function parseCssFloat(val) {
  2406. var str = val;
  2407. if (str.length && str.charAt(str.length - 1) === '%') {
  2408. return clampCssFloat(parseFloat(str) / 100);
  2409. }
  2410. return clampCssFloat(parseFloat(str));
  2411. }
  2412. function cssHueToRgb(m1, m2, h) {
  2413. if (h < 0) {
  2414. h += 1;
  2415. }
  2416. else if (h > 1) {
  2417. h -= 1;
  2418. }
  2419. if (h * 6 < 1) {
  2420. return m1 + (m2 - m1) * h * 6;
  2421. }
  2422. if (h * 2 < 1) {
  2423. return m2;
  2424. }
  2425. if (h * 3 < 2) {
  2426. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  2427. }
  2428. return m1;
  2429. }
  2430. function lerpNumber(a, b, p) {
  2431. return a + (b - a) * p;
  2432. }
  2433. function setRgba(out, r, g, b, a) {
  2434. out[0] = r;
  2435. out[1] = g;
  2436. out[2] = b;
  2437. out[3] = a;
  2438. return out;
  2439. }
  2440. function copyRgba(out, a) {
  2441. out[0] = a[0];
  2442. out[1] = a[1];
  2443. out[2] = a[2];
  2444. out[3] = a[3];
  2445. return out;
  2446. }
  2447. var colorCache = new LRU(20);
  2448. var lastRemovedArr = null;
  2449. function putToCache(colorStr, rgbaArr) {
  2450. if (lastRemovedArr) {
  2451. copyRgba(lastRemovedArr, rgbaArr);
  2452. }
  2453. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2454. }
  2455. function parse(colorStr, rgbaArr) {
  2456. if (!colorStr) {
  2457. return;
  2458. }
  2459. rgbaArr = rgbaArr || [];
  2460. var cached = colorCache.get(colorStr);
  2461. if (cached) {
  2462. return copyRgba(rgbaArr, cached);
  2463. }
  2464. colorStr = colorStr + '';
  2465. var str = colorStr.replace(/ /g, '').toLowerCase();
  2466. if (str in kCSSColorTable) {
  2467. copyRgba(rgbaArr, kCSSColorTable[str]);
  2468. putToCache(colorStr, rgbaArr);
  2469. return rgbaArr;
  2470. }
  2471. var strLen = str.length;
  2472. if (str.charAt(0) === '#') {
  2473. if (strLen === 4 || strLen === 5) {
  2474. var iv = parseInt(str.slice(1, 4), 16);
  2475. if (!(iv >= 0 && iv <= 0xfff)) {
  2476. setRgba(rgbaArr, 0, 0, 0, 1);
  2477. return;
  2478. }
  2479. 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);
  2480. putToCache(colorStr, rgbaArr);
  2481. return rgbaArr;
  2482. }
  2483. else if (strLen === 7 || strLen === 9) {
  2484. var iv = parseInt(str.slice(1, 7), 16);
  2485. if (!(iv >= 0 && iv <= 0xffffff)) {
  2486. setRgba(rgbaArr, 0, 0, 0, 1);
  2487. return;
  2488. }
  2489. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  2490. putToCache(colorStr, rgbaArr);
  2491. return rgbaArr;
  2492. }
  2493. return;
  2494. }
  2495. var op = str.indexOf('(');
  2496. var ep = str.indexOf(')');
  2497. if (op !== -1 && ep + 1 === strLen) {
  2498. var fname = str.substr(0, op);
  2499. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2500. var alpha = 1;
  2501. switch (fname) {
  2502. case 'rgba':
  2503. if (params.length !== 4) {
  2504. return params.length === 3
  2505. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  2506. : setRgba(rgbaArr, 0, 0, 0, 1);
  2507. }
  2508. alpha = parseCssFloat(params.pop());
  2509. case 'rgb':
  2510. if (params.length !== 3) {
  2511. setRgba(rgbaArr, 0, 0, 0, 1);
  2512. return;
  2513. }
  2514. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  2515. putToCache(colorStr, rgbaArr);
  2516. return rgbaArr;
  2517. case 'hsla':
  2518. if (params.length !== 4) {
  2519. setRgba(rgbaArr, 0, 0, 0, 1);
  2520. return;
  2521. }
  2522. params[3] = parseCssFloat(params[3]);
  2523. hsla2rgba(params, rgbaArr);
  2524. putToCache(colorStr, rgbaArr);
  2525. return rgbaArr;
  2526. case 'hsl':
  2527. if (params.length !== 3) {
  2528. setRgba(rgbaArr, 0, 0, 0, 1);
  2529. return;
  2530. }
  2531. hsla2rgba(params, rgbaArr);
  2532. putToCache(colorStr, rgbaArr);
  2533. return rgbaArr;
  2534. default:
  2535. return;
  2536. }
  2537. }
  2538. setRgba(rgbaArr, 0, 0, 0, 1);
  2539. return;
  2540. }
  2541. function hsla2rgba(hsla, rgba) {
  2542. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  2543. var s = parseCssFloat(hsla[1]);
  2544. var l = parseCssFloat(hsla[2]);
  2545. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2546. var m1 = l * 2 - m2;
  2547. rgba = rgba || [];
  2548. 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);
  2549. if (hsla.length === 4) {
  2550. rgba[3] = hsla[3];
  2551. }
  2552. return rgba;
  2553. }
  2554. function rgba2hsla(rgba) {
  2555. if (!rgba) {
  2556. return;
  2557. }
  2558. var R = rgba[0] / 255;
  2559. var G = rgba[1] / 255;
  2560. var B = rgba[2] / 255;
  2561. var vMin = Math.min(R, G, B);
  2562. var vMax = Math.max(R, G, B);
  2563. var delta = vMax - vMin;
  2564. var L = (vMax + vMin) / 2;
  2565. var H;
  2566. var S;
  2567. if (delta === 0) {
  2568. H = 0;
  2569. S = 0;
  2570. }
  2571. else {
  2572. if (L < 0.5) {
  2573. S = delta / (vMax + vMin);
  2574. }
  2575. else {
  2576. S = delta / (2 - vMax - vMin);
  2577. }
  2578. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2579. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2580. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2581. if (R === vMax) {
  2582. H = deltaB - deltaG;
  2583. }
  2584. else if (G === vMax) {
  2585. H = (1 / 3) + deltaR - deltaB;
  2586. }
  2587. else if (B === vMax) {
  2588. H = (2 / 3) + deltaG - deltaR;
  2589. }
  2590. if (H < 0) {
  2591. H += 1;
  2592. }
  2593. if (H > 1) {
  2594. H -= 1;
  2595. }
  2596. }
  2597. var hsla = [H * 360, S, L];
  2598. if (rgba[3] != null) {
  2599. hsla.push(rgba[3]);
  2600. }
  2601. return hsla;
  2602. }
  2603. function lift(color, level) {
  2604. var colorArr = parse(color);
  2605. if (colorArr) {
  2606. for (var i = 0; i < 3; i++) {
  2607. if (level < 0) {
  2608. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2609. }
  2610. else {
  2611. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2612. }
  2613. if (colorArr[i] > 255) {
  2614. colorArr[i] = 255;
  2615. }
  2616. else if (colorArr[i] < 0) {
  2617. colorArr[i] = 0;
  2618. }
  2619. }
  2620. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2621. }
  2622. }
  2623. function toHex(color) {
  2624. var colorArr = parse(color);
  2625. if (colorArr) {
  2626. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  2627. }
  2628. }
  2629. function fastLerp(normalizedValue, colors, out) {
  2630. if (!(colors && colors.length)
  2631. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  2632. return;
  2633. }
  2634. out = out || [];
  2635. var value = normalizedValue * (colors.length - 1);
  2636. var leftIndex = Math.floor(value);
  2637. var rightIndex = Math.ceil(value);
  2638. var leftColor = colors[leftIndex];
  2639. var rightColor = colors[rightIndex];
  2640. var dv = value - leftIndex;
  2641. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  2642. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  2643. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  2644. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  2645. return out;
  2646. }
  2647. var fastMapToColor = fastLerp;
  2648. function lerp$1(normalizedValue, colors, fullOutput) {
  2649. if (!(colors && colors.length)
  2650. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  2651. return;
  2652. }
  2653. var value = normalizedValue * (colors.length - 1);
  2654. var leftIndex = Math.floor(value);
  2655. var rightIndex = Math.ceil(value);
  2656. var leftColor = parse(colors[leftIndex]);
  2657. var rightColor = parse(colors[rightIndex]);
  2658. var dv = value - leftIndex;
  2659. var color = stringify([
  2660. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  2661. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  2662. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  2663. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  2664. ], 'rgba');
  2665. return fullOutput
  2666. ? {
  2667. color: color,
  2668. leftIndex: leftIndex,
  2669. rightIndex: rightIndex,
  2670. value: value
  2671. }
  2672. : color;
  2673. }
  2674. var mapToColor = lerp$1;
  2675. function modifyHSL(color, h, s, l) {
  2676. var colorArr = parse(color);
  2677. if (color) {
  2678. colorArr = rgba2hsla(colorArr);
  2679. h != null && (colorArr[0] = clampCssAngle(h));
  2680. s != null && (colorArr[1] = parseCssFloat(s));
  2681. l != null && (colorArr[2] = parseCssFloat(l));
  2682. return stringify(hsla2rgba(colorArr), 'rgba');
  2683. }
  2684. }
  2685. function modifyAlpha(color, alpha) {
  2686. var colorArr = parse(color);
  2687. if (colorArr && alpha != null) {
  2688. colorArr[3] = clampCssFloat(alpha);
  2689. return stringify(colorArr, 'rgba');
  2690. }
  2691. }
  2692. function stringify(arrColor, type) {
  2693. if (!arrColor || !arrColor.length) {
  2694. return;
  2695. }
  2696. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  2697. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  2698. colorStr += ',' + arrColor[3];
  2699. }
  2700. return type + '(' + colorStr + ')';
  2701. }
  2702. function lum(color, backgroundLum) {
  2703. var arr = parse(color);
  2704. return arr
  2705. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  2706. + (1 - arr[3]) * backgroundLum
  2707. : 0;
  2708. }
  2709. function random() {
  2710. var r = Math.round(Math.random() * 255);
  2711. var g = Math.round(Math.random() * 255);
  2712. var b = Math.round(Math.random() * 255);
  2713. return 'rgb(' + r + ',' + g + ',' + b + ')';
  2714. }
  2715. var color = /*#__PURE__*/Object.freeze({
  2716. __proto__: null,
  2717. parse: parse,
  2718. lift: lift,
  2719. toHex: toHex,
  2720. fastLerp: fastLerp,
  2721. fastMapToColor: fastMapToColor,
  2722. lerp: lerp$1,
  2723. mapToColor: mapToColor,
  2724. modifyHSL: modifyHSL,
  2725. modifyAlpha: modifyAlpha,
  2726. stringify: stringify,
  2727. lum: lum,
  2728. random: random
  2729. });
  2730. var arraySlice = Array.prototype.slice;
  2731. function interpolateNumber(p0, p1, percent) {
  2732. return (p1 - p0) * percent + p0;
  2733. }
  2734. function step(p0, p1, percent) {
  2735. return percent > 0.5 ? p1 : p0;
  2736. }
  2737. function interpolate1DArray(out, p0, p1, percent) {
  2738. var len = p0.length;
  2739. for (var i = 0; i < len; i++) {
  2740. out[i] = interpolateNumber(p0[i], p1[i], percent);
  2741. }
  2742. }
  2743. function interpolate2DArray(out, p0, p1, percent) {
  2744. var len = p0.length;
  2745. var len2 = len && p0[0].length;
  2746. for (var i = 0; i < len; i++) {
  2747. if (!out[i]) {
  2748. out[i] = [];
  2749. }
  2750. for (var j = 0; j < len2; j++) {
  2751. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  2752. }
  2753. }
  2754. }
  2755. function add1DArray(out, p0, p1, sign) {
  2756. var len = p0.length;
  2757. for (var i = 0; i < len; i++) {
  2758. out[i] = p0[i] + p1[i] * sign;
  2759. }
  2760. return out;
  2761. }
  2762. function add2DArray(out, p0, p1, sign) {
  2763. var len = p0.length;
  2764. var len2 = len && p0[0].length;
  2765. for (var i = 0; i < len; i++) {
  2766. if (!out[i]) {
  2767. out[i] = [];
  2768. }
  2769. for (var j = 0; j < len2; j++) {
  2770. out[i][j] = p0[i][j] + p1[i][j] * sign;
  2771. }
  2772. }
  2773. return out;
  2774. }
  2775. function fillArray(val0, val1, arrDim) {
  2776. var arr0 = val0;
  2777. var arr1 = val1;
  2778. if (!arr0.push || !arr1.push) {
  2779. return;
  2780. }
  2781. var arr0Len = arr0.length;
  2782. var arr1Len = arr1.length;
  2783. if (arr0Len !== arr1Len) {
  2784. var isPreviousLarger = arr0Len > arr1Len;
  2785. if (isPreviousLarger) {
  2786. arr0.length = arr1Len;
  2787. }
  2788. else {
  2789. for (var i = arr0Len; i < arr1Len; i++) {
  2790. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  2791. }
  2792. }
  2793. }
  2794. var len2 = arr0[0] && arr0[0].length;
  2795. for (var i = 0; i < arr0.length; i++) {
  2796. if (arrDim === 1) {
  2797. if (isNaN(arr0[i])) {
  2798. arr0[i] = arr1[i];
  2799. }
  2800. }
  2801. else {
  2802. for (var j = 0; j < len2; j++) {
  2803. if (isNaN(arr0[i][j])) {
  2804. arr0[i][j] = arr1[i][j];
  2805. }
  2806. }
  2807. }
  2808. }
  2809. }
  2810. function is1DArraySame(arr0, arr1) {
  2811. var len = arr0.length;
  2812. if (len !== arr1.length) {
  2813. return false;
  2814. }
  2815. for (var i = 0; i < len; i++) {
  2816. if (arr0[i] !== arr1[i]) {
  2817. return false;
  2818. }
  2819. }
  2820. return true;
  2821. }
  2822. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  2823. var v0 = (p2 - p0) * 0.5;
  2824. var v1 = (p3 - p1) * 0.5;
  2825. return (2 * (p1 - p2) + v0 + v1) * t3
  2826. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  2827. + v0 * t + p1;
  2828. }
  2829. function catmullRomInterpolate1DArray(out, p0, p1, p2, p3, t, t2, t3) {
  2830. var len = p0.length;
  2831. for (var i = 0; i < len; i++) {
  2832. out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3);
  2833. }
  2834. }
  2835. function catmullRomInterpolate2DArray(out, p0, p1, p2, p3, t, t2, t3) {
  2836. var len = p0.length;
  2837. var len2 = p0[0].length;
  2838. for (var i = 0; i < len; i++) {
  2839. if (!out[i]) {
  2840. out[1] = [];
  2841. }
  2842. for (var j = 0; j < len2; j++) {
  2843. out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3);
  2844. }
  2845. }
  2846. }
  2847. function cloneValue(value) {
  2848. if (isArrayLike(value)) {
  2849. var len = value.length;
  2850. if (isArrayLike(value[0])) {
  2851. var ret = [];
  2852. for (var i = 0; i < len; i++) {
  2853. ret.push(arraySlice.call(value[i]));
  2854. }
  2855. return ret;
  2856. }
  2857. return arraySlice.call(value);
  2858. }
  2859. return value;
  2860. }
  2861. function rgba2String(rgba) {
  2862. rgba[0] = Math.floor(rgba[0]);
  2863. rgba[1] = Math.floor(rgba[1]);
  2864. rgba[2] = Math.floor(rgba[2]);
  2865. return 'rgba(' + rgba.join(',') + ')';
  2866. }
  2867. function guessArrayDim(value) {
  2868. return isArrayLike(value && value[0]) ? 2 : 1;
  2869. }
  2870. var tmpRgba = [0, 0, 0, 0];
  2871. var Track = (function () {
  2872. function Track(propName) {
  2873. this.keyframes = [];
  2874. this.maxTime = 0;
  2875. this.arrDim = 0;
  2876. this.interpolable = true;
  2877. this._needsSort = false;
  2878. this._isAllValueEqual = true;
  2879. this._lastFrame = 0;
  2880. this._lastFramePercent = 0;
  2881. this.propName = propName;
  2882. }
  2883. Track.prototype.isFinished = function () {
  2884. return this._finished;
  2885. };
  2886. Track.prototype.setFinished = function () {
  2887. this._finished = true;
  2888. if (this._additiveTrack) {
  2889. this._additiveTrack.setFinished();
  2890. }
  2891. };
  2892. Track.prototype.needsAnimate = function () {
  2893. return !this._isAllValueEqual && this.keyframes.length >= 2 && this.interpolable;
  2894. };
  2895. Track.prototype.getAdditiveTrack = function () {
  2896. return this._additiveTrack;
  2897. };
  2898. Track.prototype.addKeyframe = function (time, value) {
  2899. if (time >= this.maxTime) {
  2900. this.maxTime = time;
  2901. }
  2902. else {
  2903. this._needsSort = true;
  2904. }
  2905. var keyframes = this.keyframes;
  2906. var len = keyframes.length;
  2907. if (this.interpolable) {
  2908. if (isArrayLike(value)) {
  2909. var arrayDim = guessArrayDim(value);
  2910. if (len > 0 && this.arrDim !== arrayDim) {
  2911. this.interpolable = false;
  2912. return;
  2913. }
  2914. if (arrayDim === 1 && typeof value[0] !== 'number'
  2915. || arrayDim === 2 && typeof value[0][0] !== 'number') {
  2916. this.interpolable = false;
  2917. return;
  2918. }
  2919. if (len > 0) {
  2920. var lastFrame = keyframes[len - 1];
  2921. if (this._isAllValueEqual) {
  2922. if (arrayDim === 1) {
  2923. if (!is1DArraySame(value, lastFrame.value)) {
  2924. this._isAllValueEqual = false;
  2925. }
  2926. }
  2927. else {
  2928. this._isAllValueEqual = false;
  2929. }
  2930. }
  2931. }
  2932. this.arrDim = arrayDim;
  2933. }
  2934. else {
  2935. if (this.arrDim > 0) {
  2936. this.interpolable = false;
  2937. return;
  2938. }
  2939. if (typeof value === 'string') {
  2940. var colorArray = parse(value);
  2941. if (colorArray) {
  2942. value = colorArray;
  2943. this.isValueColor = true;
  2944. }
  2945. else {
  2946. this.interpolable = false;
  2947. }
  2948. }
  2949. else if (typeof value !== 'number') {
  2950. this.interpolable = false;
  2951. return;
  2952. }
  2953. if (this._isAllValueEqual && len > 0) {
  2954. var lastFrame = keyframes[len - 1];
  2955. if (this.isValueColor && !is1DArraySame(lastFrame.value, value)) {
  2956. this._isAllValueEqual = false;
  2957. }
  2958. else if (lastFrame.value !== value) {
  2959. this._isAllValueEqual = false;
  2960. }
  2961. }
  2962. }
  2963. }
  2964. var kf = {
  2965. time: time,
  2966. value: value,
  2967. percent: 0
  2968. };
  2969. this.keyframes.push(kf);
  2970. return kf;
  2971. };
  2972. Track.prototype.prepare = function (additiveTrack) {
  2973. var kfs = this.keyframes;
  2974. if (this._needsSort) {
  2975. kfs.sort(function (a, b) {
  2976. return a.time - b.time;
  2977. });
  2978. }
  2979. var arrDim = this.arrDim;
  2980. var kfsLen = kfs.length;
  2981. var lastKf = kfs[kfsLen - 1];
  2982. for (var i = 0; i < kfsLen; i++) {
  2983. kfs[i].percent = kfs[i].time / this.maxTime;
  2984. if (arrDim > 0 && i !== kfsLen - 1) {
  2985. fillArray(kfs[i].value, lastKf.value, arrDim);
  2986. }
  2987. }
  2988. if (additiveTrack
  2989. && this.needsAnimate()
  2990. && additiveTrack.needsAnimate()
  2991. && arrDim === additiveTrack.arrDim
  2992. && this.isValueColor === additiveTrack.isValueColor
  2993. && !additiveTrack._finished) {
  2994. this._additiveTrack = additiveTrack;
  2995. var startValue = kfs[0].value;
  2996. for (var i = 0; i < kfsLen; i++) {
  2997. if (arrDim === 0) {
  2998. if (this.isValueColor) {
  2999. kfs[i].additiveValue
  3000. = add1DArray([], kfs[i].value, startValue, -1);
  3001. }
  3002. else {
  3003. kfs[i].additiveValue = kfs[i].value - startValue;
  3004. }
  3005. }
  3006. else if (arrDim === 1) {
  3007. kfs[i].additiveValue = add1DArray([], kfs[i].value, startValue, -1);
  3008. }
  3009. else if (arrDim === 2) {
  3010. kfs[i].additiveValue = add2DArray([], kfs[i].value, startValue, -1);
  3011. }
  3012. }
  3013. }
  3014. };
  3015. Track.prototype.step = function (target, percent) {
  3016. if (this._finished) {
  3017. return;
  3018. }
  3019. if (this._additiveTrack && this._additiveTrack._finished) {
  3020. this._additiveTrack = null;
  3021. }
  3022. var isAdditive = this._additiveTrack != null;
  3023. var valueKey = isAdditive ? 'additiveValue' : 'value';
  3024. var keyframes = this.keyframes;
  3025. var kfsNum = this.keyframes.length;
  3026. var propName = this.propName;
  3027. var arrDim = this.arrDim;
  3028. var isValueColor = this.isValueColor;
  3029. var frameIdx;
  3030. if (percent < 0) {
  3031. frameIdx = 0;
  3032. }
  3033. else if (percent < this._lastFramePercent) {
  3034. var start = Math.min(this._lastFrame + 1, kfsNum - 1);
  3035. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  3036. if (keyframes[frameIdx].percent <= percent) {
  3037. break;
  3038. }
  3039. }
  3040. frameIdx = Math.min(frameIdx, kfsNum - 2);
  3041. }
  3042. else {
  3043. for (frameIdx = this._lastFrame; frameIdx < kfsNum; frameIdx++) {
  3044. if (keyframes[frameIdx].percent > percent) {
  3045. break;
  3046. }
  3047. }
  3048. frameIdx = Math.min(frameIdx - 1, kfsNum - 2);
  3049. }
  3050. var nextFrame = keyframes[frameIdx + 1];
  3051. var frame = keyframes[frameIdx];
  3052. if (!(frame && nextFrame)) {
  3053. return;
  3054. }
  3055. this._lastFrame = frameIdx;
  3056. this._lastFramePercent = percent;
  3057. var range = (nextFrame.percent - frame.percent);
  3058. if (range === 0) {
  3059. return;
  3060. }
  3061. var w = (percent - frame.percent) / range;
  3062. var targetArr = isAdditive ? this._additiveValue
  3063. : (isValueColor ? tmpRgba : target[propName]);
  3064. if ((arrDim > 0 || isValueColor) && !targetArr) {
  3065. targetArr = this._additiveValue = [];
  3066. }
  3067. if (this.useSpline) {
  3068. var p1 = keyframes[frameIdx][valueKey];
  3069. var p0 = keyframes[frameIdx === 0 ? frameIdx : frameIdx - 1][valueKey];
  3070. var p2 = keyframes[frameIdx > kfsNum - 2 ? kfsNum - 1 : frameIdx + 1][valueKey];
  3071. var p3 = keyframes[frameIdx > kfsNum - 3 ? kfsNum - 1 : frameIdx + 2][valueKey];
  3072. if (arrDim > 0) {
  3073. arrDim === 1
  3074. ? catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w)
  3075. : catmullRomInterpolate2DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3076. }
  3077. else if (isValueColor) {
  3078. catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3079. if (!isAdditive) {
  3080. target[propName] = rgba2String(targetArr);
  3081. }
  3082. }
  3083. else {
  3084. var value = void 0;
  3085. if (!this.interpolable) {
  3086. value = p2;
  3087. }
  3088. else {
  3089. value = catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w);
  3090. }
  3091. if (isAdditive) {
  3092. this._additiveValue = value;
  3093. }
  3094. else {
  3095. target[propName] = value;
  3096. }
  3097. }
  3098. }
  3099. else {
  3100. if (arrDim > 0) {
  3101. arrDim === 1
  3102. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  3103. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3104. }
  3105. else if (isValueColor) {
  3106. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3107. if (!isAdditive) {
  3108. target[propName] = rgba2String(targetArr);
  3109. }
  3110. }
  3111. else {
  3112. var value = void 0;
  3113. if (!this.interpolable) {
  3114. value = step(frame[valueKey], nextFrame[valueKey], w);
  3115. }
  3116. else {
  3117. value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  3118. }
  3119. if (isAdditive) {
  3120. this._additiveValue = value;
  3121. }
  3122. else {
  3123. target[propName] = value;
  3124. }
  3125. }
  3126. }
  3127. if (isAdditive) {
  3128. this._addToTarget(target);
  3129. }
  3130. };
  3131. Track.prototype._addToTarget = function (target) {
  3132. var arrDim = this.arrDim;
  3133. var propName = this.propName;
  3134. var additiveValue = this._additiveValue;
  3135. if (arrDim === 0) {
  3136. if (this.isValueColor) {
  3137. parse(target[propName], tmpRgba);
  3138. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  3139. target[propName] = rgba2String(tmpRgba);
  3140. }
  3141. else {
  3142. target[propName] = target[propName] + additiveValue;
  3143. }
  3144. }
  3145. else if (arrDim === 1) {
  3146. add1DArray(target[propName], target[propName], additiveValue, 1);
  3147. }
  3148. else if (arrDim === 2) {
  3149. add2DArray(target[propName], target[propName], additiveValue, 1);
  3150. }
  3151. };
  3152. return Track;
  3153. }());
  3154. var Animator = (function () {
  3155. function Animator(target, loop, additiveTo) {
  3156. this._tracks = {};
  3157. this._trackKeys = [];
  3158. this._delay = 0;
  3159. this._maxTime = 0;
  3160. this._paused = false;
  3161. this._started = 0;
  3162. this._clip = null;
  3163. this._target = target;
  3164. this._loop = loop;
  3165. if (loop && additiveTo) {
  3166. logError('Can\' use additive animation on looped animation.');
  3167. return;
  3168. }
  3169. this._additiveAnimators = additiveTo;
  3170. }
  3171. Animator.prototype.getTarget = function () {
  3172. return this._target;
  3173. };
  3174. Animator.prototype.changeTarget = function (target) {
  3175. this._target = target;
  3176. };
  3177. Animator.prototype.when = function (time, props) {
  3178. return this.whenWithKeys(time, props, keys(props));
  3179. };
  3180. Animator.prototype.whenWithKeys = function (time, props, propNames) {
  3181. var tracks = this._tracks;
  3182. for (var i = 0; i < propNames.length; i++) {
  3183. var propName = propNames[i];
  3184. var track = tracks[propName];
  3185. if (!track) {
  3186. track = tracks[propName] = new Track(propName);
  3187. var initialValue = void 0;
  3188. var additiveTrack = this._getAdditiveTrack(propName);
  3189. if (additiveTrack) {
  3190. var lastFinalKf = additiveTrack.keyframes[additiveTrack.keyframes.length - 1];
  3191. initialValue = lastFinalKf && lastFinalKf.value;
  3192. if (additiveTrack.isValueColor && initialValue) {
  3193. initialValue = rgba2String(initialValue);
  3194. }
  3195. }
  3196. else {
  3197. initialValue = this._target[propName];
  3198. }
  3199. if (initialValue == null) {
  3200. continue;
  3201. }
  3202. if (time !== 0) {
  3203. track.addKeyframe(0, cloneValue(initialValue));
  3204. }
  3205. this._trackKeys.push(propName);
  3206. }
  3207. track.addKeyframe(time, cloneValue(props[propName]));
  3208. }
  3209. this._maxTime = Math.max(this._maxTime, time);
  3210. return this;
  3211. };
  3212. Animator.prototype.pause = function () {
  3213. this._clip.pause();
  3214. this._paused = true;
  3215. };
  3216. Animator.prototype.resume = function () {
  3217. this._clip.resume();
  3218. this._paused = false;
  3219. };
  3220. Animator.prototype.isPaused = function () {
  3221. return !!this._paused;
  3222. };
  3223. Animator.prototype._doneCallback = function () {
  3224. this._setTracksFinished();
  3225. this._clip = null;
  3226. var doneList = this._doneList;
  3227. if (doneList) {
  3228. var len = doneList.length;
  3229. for (var i = 0; i < len; i++) {
  3230. doneList[i].call(this);
  3231. }
  3232. }
  3233. };
  3234. Animator.prototype._abortedCallback = function () {
  3235. this._setTracksFinished();
  3236. var animation = this.animation;
  3237. var abortedList = this._abortedList;
  3238. if (animation) {
  3239. animation.removeClip(this._clip);
  3240. }
  3241. this._clip = null;
  3242. if (abortedList) {
  3243. for (var i = 0; i < abortedList.length; i++) {
  3244. abortedList[i].call(this);
  3245. }
  3246. }
  3247. };
  3248. Animator.prototype._setTracksFinished = function () {
  3249. var tracks = this._tracks;
  3250. var tracksKeys = this._trackKeys;
  3251. for (var i = 0; i < tracksKeys.length; i++) {
  3252. tracks[tracksKeys[i]].setFinished();
  3253. }
  3254. };
  3255. Animator.prototype._getAdditiveTrack = function (trackName) {
  3256. var additiveTrack;
  3257. var additiveAnimators = this._additiveAnimators;
  3258. if (additiveAnimators) {
  3259. for (var i = 0; i < additiveAnimators.length; i++) {
  3260. var track = additiveAnimators[i].getTrack(trackName);
  3261. if (track) {
  3262. additiveTrack = track;
  3263. }
  3264. }
  3265. }
  3266. return additiveTrack;
  3267. };
  3268. Animator.prototype.start = function (easing, forceAnimate) {
  3269. if (this._started > 0) {
  3270. return;
  3271. }
  3272. this._started = 1;
  3273. var self = this;
  3274. var tracks = [];
  3275. for (var i = 0; i < this._trackKeys.length; i++) {
  3276. var propName = this._trackKeys[i];
  3277. var track = this._tracks[propName];
  3278. var additiveTrack = this._getAdditiveTrack(propName);
  3279. var kfs = track.keyframes;
  3280. track.prepare(additiveTrack);
  3281. if (track.needsAnimate()) {
  3282. tracks.push(track);
  3283. }
  3284. else if (!track.interpolable) {
  3285. var lastKf = kfs[kfs.length - 1];
  3286. if (lastKf) {
  3287. self._target[track.propName] = lastKf.value;
  3288. }
  3289. }
  3290. }
  3291. if (tracks.length || forceAnimate) {
  3292. var clip = new Clip({
  3293. life: this._maxTime,
  3294. loop: this._loop,
  3295. delay: this._delay,
  3296. onframe: function (percent) {
  3297. self._started = 2;
  3298. var additiveAnimators = self._additiveAnimators;
  3299. if (additiveAnimators) {
  3300. var stillHasAdditiveAnimator = false;
  3301. for (var i = 0; i < additiveAnimators.length; i++) {
  3302. if (additiveAnimators[i]._clip) {
  3303. stillHasAdditiveAnimator = true;
  3304. break;
  3305. }
  3306. }
  3307. if (!stillHasAdditiveAnimator) {
  3308. self._additiveAnimators = null;
  3309. }
  3310. }
  3311. for (var i = 0; i < tracks.length; i++) {
  3312. tracks[i].step(self._target, percent);
  3313. }
  3314. var onframeList = self._onframeList;
  3315. if (onframeList) {
  3316. for (var i = 0; i < onframeList.length; i++) {
  3317. onframeList[i](self._target, percent);
  3318. }
  3319. }
  3320. },
  3321. ondestroy: function () {
  3322. self._doneCallback();
  3323. }
  3324. });
  3325. this._clip = clip;
  3326. if (this.animation) {
  3327. this.animation.addClip(clip);
  3328. }
  3329. if (easing && easing !== 'spline') {
  3330. clip.easing = easing;
  3331. }
  3332. }
  3333. else {
  3334. this._doneCallback();
  3335. }
  3336. return this;
  3337. };
  3338. Animator.prototype.stop = function (forwardToLast) {
  3339. if (!this._clip) {
  3340. return;
  3341. }
  3342. var clip = this._clip;
  3343. if (forwardToLast) {
  3344. clip.onframe(1);
  3345. }
  3346. this._abortedCallback();
  3347. };
  3348. Animator.prototype.delay = function (time) {
  3349. this._delay = time;
  3350. return this;
  3351. };
  3352. Animator.prototype.during = function (cb) {
  3353. if (cb) {
  3354. if (!this._onframeList) {
  3355. this._onframeList = [];
  3356. }
  3357. this._onframeList.push(cb);
  3358. }
  3359. return this;
  3360. };
  3361. Animator.prototype.done = function (cb) {
  3362. if (cb) {
  3363. if (!this._doneList) {
  3364. this._doneList = [];
  3365. }
  3366. this._doneList.push(cb);
  3367. }
  3368. return this;
  3369. };
  3370. Animator.prototype.aborted = function (cb) {
  3371. if (cb) {
  3372. if (!this._abortedList) {
  3373. this._abortedList = [];
  3374. }
  3375. this._abortedList.push(cb);
  3376. }
  3377. return this;
  3378. };
  3379. Animator.prototype.getClip = function () {
  3380. return this._clip;
  3381. };
  3382. Animator.prototype.getTrack = function (propName) {
  3383. return this._tracks[propName];
  3384. };
  3385. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  3386. if (!propNames.length || !this._clip) {
  3387. return true;
  3388. }
  3389. var tracks = this._tracks;
  3390. var tracksKeys = this._trackKeys;
  3391. for (var i = 0; i < propNames.length; i++) {
  3392. var track = tracks[propNames[i]];
  3393. if (track) {
  3394. if (forwardToLast) {
  3395. track.step(this._target, 1);
  3396. }
  3397. else if (this._started === 1) {
  3398. track.step(this._target, 0);
  3399. }
  3400. track.setFinished();
  3401. }
  3402. }
  3403. var allAborted = true;
  3404. for (var i = 0; i < tracksKeys.length; i++) {
  3405. if (!tracks[tracksKeys[i]].isFinished()) {
  3406. allAborted = false;
  3407. break;
  3408. }
  3409. }
  3410. if (allAborted) {
  3411. this._abortedCallback();
  3412. }
  3413. return allAborted;
  3414. };
  3415. Animator.prototype.saveFinalToTarget = function (target, trackKeys) {
  3416. if (!target) {
  3417. return;
  3418. }
  3419. trackKeys = trackKeys || this._trackKeys;
  3420. for (var i = 0; i < trackKeys.length; i++) {
  3421. var propName = trackKeys[i];
  3422. var track = this._tracks[propName];
  3423. if (!track || track.isFinished()) {
  3424. continue;
  3425. }
  3426. var kfs = track.keyframes;
  3427. var lastKf = kfs[kfs.length - 1];
  3428. if (lastKf) {
  3429. var val = cloneValue(lastKf.value);
  3430. if (track.isValueColor) {
  3431. val = rgba2String(val);
  3432. }
  3433. target[propName] = val;
  3434. }
  3435. }
  3436. };
  3437. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  3438. trackKeys = trackKeys || keys(finalProps);
  3439. for (var i = 0; i < trackKeys.length; i++) {
  3440. var propName = trackKeys[i];
  3441. var track = this._tracks[propName];
  3442. if (!track) {
  3443. continue;
  3444. }
  3445. var kfs = track.keyframes;
  3446. if (kfs.length > 1) {
  3447. var lastKf = kfs.pop();
  3448. track.addKeyframe(lastKf.time, finalProps[propName]);
  3449. track.prepare(track.getAdditiveTrack());
  3450. }
  3451. }
  3452. };
  3453. return Animator;
  3454. }());
  3455. var Point = (function () {
  3456. function Point(x, y) {
  3457. this.x = x || 0;
  3458. this.y = y || 0;
  3459. }
  3460. Point.prototype.copy = function (other) {
  3461. this.x = other.x;
  3462. this.y = other.y;
  3463. return this;
  3464. };
  3465. Point.prototype.clone = function () {
  3466. return new Point(this.x, this.y);
  3467. };
  3468. Point.prototype.set = function (x, y) {
  3469. this.x = x;
  3470. this.y = y;
  3471. return this;
  3472. };
  3473. Point.prototype.equal = function (other) {
  3474. return other.x === this.x && other.y === this.y;
  3475. };
  3476. Point.prototype.add = function (other) {
  3477. this.x += other.x;
  3478. this.y += other.y;
  3479. return this;
  3480. };
  3481. Point.prototype.scale = function (scalar) {
  3482. this.x *= scalar;
  3483. this.y *= scalar;
  3484. };
  3485. Point.prototype.scaleAndAdd = function (other, scalar) {
  3486. this.x += other.x * scalar;
  3487. this.y += other.y * scalar;
  3488. };
  3489. Point.prototype.sub = function (other) {
  3490. this.x -= other.x;
  3491. this.y -= other.y;
  3492. return this;
  3493. };
  3494. Point.prototype.dot = function (other) {
  3495. return this.x * other.x + this.y * other.y;
  3496. };
  3497. Point.prototype.len = function () {
  3498. return Math.sqrt(this.x * this.x + this.y * this.y);
  3499. };
  3500. Point.prototype.lenSquare = function () {
  3501. return this.x * this.x + this.y * this.y;
  3502. };
  3503. Point.prototype.normalize = function () {
  3504. var len = this.len();
  3505. this.x /= len;
  3506. this.y /= len;
  3507. return this;
  3508. };
  3509. Point.prototype.distance = function (other) {
  3510. var dx = this.x - other.x;
  3511. var dy = this.y - other.y;
  3512. return Math.sqrt(dx * dx + dy * dy);
  3513. };
  3514. Point.prototype.distanceSquare = function (other) {
  3515. var dx = this.x - other.x;
  3516. var dy = this.y - other.y;
  3517. return dx * dx + dy * dy;
  3518. };
  3519. Point.prototype.negate = function () {
  3520. this.x = -this.x;
  3521. this.y = -this.y;
  3522. return this;
  3523. };
  3524. Point.prototype.transform = function (m) {
  3525. if (!m) {
  3526. return;
  3527. }
  3528. var x = this.x;
  3529. var y = this.y;
  3530. this.x = m[0] * x + m[2] * y + m[4];
  3531. this.y = m[1] * x + m[3] * y + m[5];
  3532. return this;
  3533. };
  3534. Point.prototype.toArray = function (out) {
  3535. out[0] = this.x;
  3536. out[1] = this.y;
  3537. return out;
  3538. };
  3539. Point.prototype.fromArray = function (input) {
  3540. this.x = input[0];
  3541. this.y = input[1];
  3542. };
  3543. Point.set = function (p, x, y) {
  3544. p.x = x;
  3545. p.y = y;
  3546. };
  3547. Point.copy = function (p, p2) {
  3548. p.x = p2.x;
  3549. p.y = p2.y;
  3550. };
  3551. Point.len = function (p) {
  3552. return Math.sqrt(p.x * p.x + p.y * p.y);
  3553. };
  3554. Point.lenSquare = function (p) {
  3555. return p.x * p.x + p.y * p.y;
  3556. };
  3557. Point.dot = function (p0, p1) {
  3558. return p0.x * p1.x + p0.y * p1.y;
  3559. };
  3560. Point.add = function (out, p0, p1) {
  3561. out.x = p0.x + p1.x;
  3562. out.y = p0.y + p1.y;
  3563. };
  3564. Point.sub = function (out, p0, p1) {
  3565. out.x = p0.x - p1.x;
  3566. out.y = p0.y - p1.y;
  3567. };
  3568. Point.scale = function (out, p0, scalar) {
  3569. out.x = p0.x * scalar;
  3570. out.y = p0.y * scalar;
  3571. };
  3572. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  3573. out.x = p0.x + p1.x * scalar;
  3574. out.y = p0.y + p1.y * scalar;
  3575. };
  3576. Point.lerp = function (out, p0, p1, t) {
  3577. var onet = 1 - t;
  3578. out.x = onet * p0.x + t * p1.x;
  3579. out.y = onet * p0.y + t * p1.y;
  3580. };
  3581. return Point;
  3582. }());
  3583. var mathMin = Math.min;
  3584. var mathMax = Math.max;
  3585. var lt = new Point();
  3586. var rb = new Point();
  3587. var lb = new Point();
  3588. var rt = new Point();
  3589. var minTv = new Point();
  3590. var maxTv = new Point();
  3591. var BoundingRect = (function () {
  3592. function BoundingRect(x, y, width, height) {
  3593. if (width < 0 && isFinite(width)) {
  3594. x = x + width;
  3595. width = -width;
  3596. }
  3597. if (height < 0 && isFinite(height)) {
  3598. y = y + height;
  3599. height = -height;
  3600. }
  3601. this.x = x;
  3602. this.y = y;
  3603. this.width = width;
  3604. this.height = height;
  3605. }
  3606. BoundingRect.prototype.union = function (other) {
  3607. var x = mathMin(other.x, this.x);
  3608. var y = mathMin(other.y, this.y);
  3609. if (isFinite(this.x) && isFinite(this.width)) {
  3610. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  3611. }
  3612. else {
  3613. this.width = other.width;
  3614. }
  3615. if (isFinite(this.y) && isFinite(this.height)) {
  3616. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  3617. }
  3618. else {
  3619. this.height = other.height;
  3620. }
  3621. this.x = x;
  3622. this.y = y;
  3623. };
  3624. BoundingRect.prototype.applyTransform = function (m) {
  3625. BoundingRect.applyTransform(this, this, m);
  3626. };
  3627. BoundingRect.prototype.calculateTransform = function (b) {
  3628. var a = this;
  3629. var sx = b.width / a.width;
  3630. var sy = b.height / a.height;
  3631. var m = create$1();
  3632. translate(m, m, [-a.x, -a.y]);
  3633. scale$1(m, m, [sx, sy]);
  3634. translate(m, m, [b.x, b.y]);
  3635. return m;
  3636. };
  3637. BoundingRect.prototype.intersect = function (b, mtv) {
  3638. if (!b) {
  3639. return false;
  3640. }
  3641. if (!(b instanceof BoundingRect)) {
  3642. b = BoundingRect.create(b);
  3643. }
  3644. var a = this;
  3645. var ax0 = a.x;
  3646. var ax1 = a.x + a.width;
  3647. var ay0 = a.y;
  3648. var ay1 = a.y + a.height;
  3649. var bx0 = b.x;
  3650. var bx1 = b.x + b.width;
  3651. var by0 = b.y;
  3652. var by1 = b.y + b.height;
  3653. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  3654. if (mtv) {
  3655. var dMin = Infinity;
  3656. var dMax = 0;
  3657. var d0 = Math.abs(ax1 - bx0);
  3658. var d1 = Math.abs(bx1 - ax0);
  3659. var d2 = Math.abs(ay1 - by0);
  3660. var d3 = Math.abs(by1 - ay0);
  3661. var dx = Math.min(d0, d1);
  3662. var dy = Math.min(d2, d3);
  3663. if (ax1 < bx0 || bx1 < ax0) {
  3664. if (dx > dMax) {
  3665. dMax = dx;
  3666. if (d0 < d1) {
  3667. Point.set(maxTv, -d0, 0);
  3668. }
  3669. else {
  3670. Point.set(maxTv, d1, 0);
  3671. }
  3672. }
  3673. }
  3674. else {
  3675. if (dx < dMin) {
  3676. dMin = dx;
  3677. if (d0 < d1) {
  3678. Point.set(minTv, d0, 0);
  3679. }
  3680. else {
  3681. Point.set(minTv, -d1, 0);
  3682. }
  3683. }
  3684. }
  3685. if (ay1 < by0 || by1 < ay0) {
  3686. if (dy > dMax) {
  3687. dMax = dy;
  3688. if (d2 < d3) {
  3689. Point.set(maxTv, 0, -d2);
  3690. }
  3691. else {
  3692. Point.set(maxTv, 0, d3);
  3693. }
  3694. }
  3695. }
  3696. else {
  3697. if (dx < dMin) {
  3698. dMin = dx;
  3699. if (d2 < d3) {
  3700. Point.set(minTv, 0, d2);
  3701. }
  3702. else {
  3703. Point.set(minTv, 0, -d3);
  3704. }
  3705. }
  3706. }
  3707. }
  3708. if (mtv) {
  3709. Point.copy(mtv, overlap ? minTv : maxTv);
  3710. }
  3711. return overlap;
  3712. };
  3713. BoundingRect.prototype.contain = function (x, y) {
  3714. var rect = this;
  3715. return x >= rect.x
  3716. && x <= (rect.x + rect.width)
  3717. && y >= rect.y
  3718. && y <= (rect.y + rect.height);
  3719. };
  3720. BoundingRect.prototype.clone = function () {
  3721. return new BoundingRect(this.x, this.y, this.width, this.height);
  3722. };
  3723. BoundingRect.prototype.copy = function (other) {
  3724. BoundingRect.copy(this, other);
  3725. };
  3726. BoundingRect.prototype.plain = function () {
  3727. return {
  3728. x: this.x,
  3729. y: this.y,
  3730. width: this.width,
  3731. height: this.height
  3732. };
  3733. };
  3734. BoundingRect.prototype.isFinite = function () {
  3735. return isFinite(this.x)
  3736. && isFinite(this.y)
  3737. && isFinite(this.width)
  3738. && isFinite(this.height);
  3739. };
  3740. BoundingRect.prototype.isZero = function () {
  3741. return this.width === 0 || this.height === 0;
  3742. };
  3743. BoundingRect.create = function (rect) {
  3744. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  3745. };
  3746. BoundingRect.copy = function (target, source) {
  3747. target.x = source.x;
  3748. target.y = source.y;
  3749. target.width = source.width;
  3750. target.height = source.height;
  3751. };
  3752. BoundingRect.applyTransform = function (target, source, m) {
  3753. if (!m) {
  3754. if (target !== source) {
  3755. BoundingRect.copy(target, source);
  3756. }
  3757. return;
  3758. }
  3759. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  3760. var sx = m[0];
  3761. var sy = m[3];
  3762. var tx = m[4];
  3763. var ty = m[5];
  3764. target.x = source.x * sx + tx;
  3765. target.y = source.y * sy + ty;
  3766. target.width = source.width * sx;
  3767. target.height = source.height * sy;
  3768. if (target.width < 0) {
  3769. target.x += target.width;
  3770. target.width = -target.width;
  3771. }
  3772. if (target.height < 0) {
  3773. target.y += target.height;
  3774. target.height = -target.height;
  3775. }
  3776. return;
  3777. }
  3778. lt.x = lb.x = source.x;
  3779. lt.y = rt.y = source.y;
  3780. rb.x = rt.x = source.x + source.width;
  3781. rb.y = lb.y = source.y + source.height;
  3782. lt.transform(m);
  3783. rt.transform(m);
  3784. rb.transform(m);
  3785. lb.transform(m);
  3786. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  3787. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  3788. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  3789. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  3790. target.width = maxX - target.x;
  3791. target.height = maxY - target.y;
  3792. };
  3793. return BoundingRect;
  3794. }());
  3795. var textWidthCache = {};
  3796. var DEFAULT_FONT = '12px sans-serif';
  3797. var _ctx;
  3798. var _cachedFont;
  3799. function defaultMeasureText(text, font) {
  3800. if (!_ctx) {
  3801. _ctx = createCanvas().getContext('2d');
  3802. }
  3803. if (_cachedFont !== font) {
  3804. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  3805. }
  3806. return _ctx.measureText(text);
  3807. }
  3808. var methods$1 = {
  3809. measureText: defaultMeasureText
  3810. };
  3811. function getWidth(text, font) {
  3812. font = font || DEFAULT_FONT;
  3813. var cacheOfFont = textWidthCache[font];
  3814. if (!cacheOfFont) {
  3815. cacheOfFont = textWidthCache[font] = new LRU(500);
  3816. }
  3817. var width = cacheOfFont.get(text);
  3818. if (width == null) {
  3819. width = methods$1.measureText(text, font).width;
  3820. cacheOfFont.put(text, width);
  3821. }
  3822. return width;
  3823. }
  3824. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  3825. var width = getWidth(text, font);
  3826. var height = getLineHeight(font);
  3827. var x = adjustTextX(0, width, textAlign);
  3828. var y = adjustTextY(0, height, textBaseline);
  3829. var rect = new BoundingRect(x, y, width, height);
  3830. return rect;
  3831. }
  3832. function getBoundingRect(text, font, textAlign, textBaseline) {
  3833. var textLines = ((text || '') + '').split('\n');
  3834. var len = textLines.length;
  3835. if (len === 1) {
  3836. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  3837. }
  3838. else {
  3839. var uniondRect = new BoundingRect(0, 0, 0, 0);
  3840. for (var i = 0; i < textLines.length; i++) {
  3841. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  3842. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  3843. }
  3844. return uniondRect;
  3845. }
  3846. }
  3847. function adjustTextX(x, width, textAlign) {
  3848. if (textAlign === 'right') {
  3849. x -= width;
  3850. }
  3851. else if (textAlign === 'center') {
  3852. x -= width / 2;
  3853. }
  3854. return x;
  3855. }
  3856. function adjustTextY(y, height, verticalAlign) {
  3857. if (verticalAlign === 'middle') {
  3858. y -= height / 2;
  3859. }
  3860. else if (verticalAlign === 'bottom') {
  3861. y -= height;
  3862. }
  3863. return y;
  3864. }
  3865. function getLineHeight(font) {
  3866. return getWidth('国', font);
  3867. }
  3868. function parsePercent(value, maxValue) {
  3869. if (typeof value === 'string') {
  3870. if (value.lastIndexOf('%') >= 0) {
  3871. return parseFloat(value) / 100 * maxValue;
  3872. }
  3873. return parseFloat(value);
  3874. }
  3875. return value;
  3876. }
  3877. function calculateTextPosition(out, opts, rect) {
  3878. var textPosition = opts.position || 'inside';
  3879. var distance = opts.distance != null ? opts.distance : 5;
  3880. var height = rect.height;
  3881. var width = rect.width;
  3882. var halfHeight = height / 2;
  3883. var x = rect.x;
  3884. var y = rect.y;
  3885. var textAlign = 'left';
  3886. var textVerticalAlign = 'top';
  3887. if (textPosition instanceof Array) {
  3888. x += parsePercent(textPosition[0], rect.width);
  3889. y += parsePercent(textPosition[1], rect.height);
  3890. textAlign = null;
  3891. textVerticalAlign = null;
  3892. }
  3893. else {
  3894. switch (textPosition) {
  3895. case 'left':
  3896. x -= distance;
  3897. y += halfHeight;
  3898. textAlign = 'right';
  3899. textVerticalAlign = 'middle';
  3900. break;
  3901. case 'right':
  3902. x += distance + width;
  3903. y += halfHeight;
  3904. textVerticalAlign = 'middle';
  3905. break;
  3906. case 'top':
  3907. x += width / 2;
  3908. y -= distance;
  3909. textAlign = 'center';
  3910. textVerticalAlign = 'bottom';
  3911. break;
  3912. case 'bottom':
  3913. x += width / 2;
  3914. y += height + distance;
  3915. textAlign = 'center';
  3916. break;
  3917. case 'inside':
  3918. x += width / 2;
  3919. y += halfHeight;
  3920. textAlign = 'center';
  3921. textVerticalAlign = 'middle';
  3922. break;
  3923. case 'insideLeft':
  3924. x += distance;
  3925. y += halfHeight;
  3926. textVerticalAlign = 'middle';
  3927. break;
  3928. case 'insideRight':
  3929. x += width - distance;
  3930. y += halfHeight;
  3931. textAlign = 'right';
  3932. textVerticalAlign = 'middle';
  3933. break;
  3934. case 'insideTop':
  3935. x += width / 2;
  3936. y += distance;
  3937. textAlign = 'center';
  3938. break;
  3939. case 'insideBottom':
  3940. x += width / 2;
  3941. y += height - distance;
  3942. textAlign = 'center';
  3943. textVerticalAlign = 'bottom';
  3944. break;
  3945. case 'insideTopLeft':
  3946. x += distance;
  3947. y += distance;
  3948. break;
  3949. case 'insideTopRight':
  3950. x += width - distance;
  3951. y += distance;
  3952. textAlign = 'right';
  3953. break;
  3954. case 'insideBottomLeft':
  3955. x += distance;
  3956. y += height - distance;
  3957. textVerticalAlign = 'bottom';
  3958. break;
  3959. case 'insideBottomRight':
  3960. x += width - distance;
  3961. y += height - distance;
  3962. textAlign = 'right';
  3963. textVerticalAlign = 'bottom';
  3964. break;
  3965. }
  3966. }
  3967. out = out || {};
  3968. out.x = x;
  3969. out.y = y;
  3970. out.align = textAlign;
  3971. out.verticalAlign = textVerticalAlign;
  3972. return out;
  3973. }
  3974. var dpr = 1;
  3975. if (typeof window !== 'undefined') {
  3976. dpr = Math.max(window.devicePixelRatio
  3977. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  3978. || 1, 1);
  3979. }
  3980. var devicePixelRatio = dpr;
  3981. var DARK_MODE_THRESHOLD = 0.4;
  3982. var DARK_LABEL_COLOR = '#333';
  3983. var LIGHT_LABEL_COLOR = '#ccc';
  3984. var LIGHTER_LABEL_COLOR = '#eee';
  3985. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  3986. var PRIMARY_STATES_KEYS = ['x', 'y', 'scaleX', 'scaleY', 'originX', 'originY', 'rotation', 'ignore'];
  3987. var DEFAULT_ANIMATABLE_MAP = {
  3988. x: true,
  3989. y: true,
  3990. scaleX: true,
  3991. scaleY: true,
  3992. originX: true,
  3993. originY: true,
  3994. rotation: true,
  3995. ignore: false
  3996. };
  3997. var tmpTextPosCalcRes = {};
  3998. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  3999. var Element = (function () {
  4000. function Element(props) {
  4001. this.id = guid();
  4002. this.animators = [];
  4003. this.currentStates = [];
  4004. this.states = {};
  4005. this._init(props);
  4006. }
  4007. Element.prototype._init = function (props) {
  4008. this.attr(props);
  4009. };
  4010. Element.prototype.drift = function (dx, dy, e) {
  4011. switch (this.draggable) {
  4012. case 'horizontal':
  4013. dy = 0;
  4014. break;
  4015. case 'vertical':
  4016. dx = 0;
  4017. break;
  4018. }
  4019. var m = this.transform;
  4020. if (!m) {
  4021. m = this.transform = [1, 0, 0, 1, 0, 0];
  4022. }
  4023. m[4] += dx;
  4024. m[5] += dy;
  4025. this.decomposeTransform();
  4026. this.markRedraw();
  4027. };
  4028. Element.prototype.beforeUpdate = function () { };
  4029. Element.prototype.afterUpdate = function () { };
  4030. Element.prototype.update = function () {
  4031. this.updateTransform();
  4032. if (this.__dirty) {
  4033. this.updateInnerText();
  4034. }
  4035. };
  4036. Element.prototype.updateInnerText = function (forceUpdate) {
  4037. var textEl = this._textContent;
  4038. if (textEl && (!textEl.ignore || forceUpdate)) {
  4039. if (!this.textConfig) {
  4040. this.textConfig = {};
  4041. }
  4042. var textConfig = this.textConfig;
  4043. var isLocal = textConfig.local;
  4044. var attachedTransform = textEl.attachedTransform;
  4045. var textAlign = void 0;
  4046. var textVerticalAlign = void 0;
  4047. var textStyleChanged = false;
  4048. if (isLocal) {
  4049. attachedTransform.parent = this;
  4050. }
  4051. else {
  4052. attachedTransform.parent = null;
  4053. }
  4054. var innerOrigin = false;
  4055. attachedTransform.x = textEl.x;
  4056. attachedTransform.y = textEl.y;
  4057. attachedTransform.originX = textEl.originX;
  4058. attachedTransform.originY = textEl.originY;
  4059. attachedTransform.rotation = textEl.rotation;
  4060. attachedTransform.scaleX = textEl.scaleX;
  4061. attachedTransform.scaleY = textEl.scaleY;
  4062. if (textConfig.position != null) {
  4063. var layoutRect = tmpBoundingRect;
  4064. if (textConfig.layoutRect) {
  4065. layoutRect.copy(textConfig.layoutRect);
  4066. }
  4067. else {
  4068. layoutRect.copy(this.getBoundingRect());
  4069. }
  4070. if (!isLocal) {
  4071. layoutRect.applyTransform(this.transform);
  4072. }
  4073. if (this.calculateTextPosition) {
  4074. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  4075. }
  4076. else {
  4077. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  4078. }
  4079. attachedTransform.x = tmpTextPosCalcRes.x;
  4080. attachedTransform.y = tmpTextPosCalcRes.y;
  4081. textAlign = tmpTextPosCalcRes.align;
  4082. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  4083. var textOrigin = textConfig.origin;
  4084. if (textOrigin && textConfig.rotation != null) {
  4085. var relOriginX = void 0;
  4086. var relOriginY = void 0;
  4087. if (textOrigin === 'center') {
  4088. relOriginX = layoutRect.width * 0.5;
  4089. relOriginY = layoutRect.height * 0.5;
  4090. }
  4091. else {
  4092. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  4093. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  4094. }
  4095. innerOrigin = true;
  4096. attachedTransform.originX = -attachedTransform.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  4097. attachedTransform.originY = -attachedTransform.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  4098. }
  4099. }
  4100. if (textConfig.rotation != null) {
  4101. attachedTransform.rotation = textConfig.rotation;
  4102. }
  4103. var textOffset = textConfig.offset;
  4104. if (textOffset) {
  4105. attachedTransform.x += textOffset[0];
  4106. attachedTransform.y += textOffset[1];
  4107. if (!innerOrigin) {
  4108. attachedTransform.originX = -textOffset[0];
  4109. attachedTransform.originY = -textOffset[1];
  4110. }
  4111. }
  4112. var isInside = textConfig.inside == null
  4113. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  4114. : textConfig.inside;
  4115. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  4116. var textFill = void 0;
  4117. var textStroke = void 0;
  4118. var autoStroke = void 0;
  4119. if (isInside && this.canBeInsideText()) {
  4120. textFill = textConfig.insideFill;
  4121. textStroke = textConfig.insideStroke;
  4122. if (textFill == null || textFill === 'auto') {
  4123. textFill = this.getInsideTextFill();
  4124. }
  4125. if (textStroke == null || textStroke === 'auto') {
  4126. textStroke = this.getInsideTextStroke(textFill);
  4127. autoStroke = true;
  4128. }
  4129. }
  4130. else {
  4131. textFill = textConfig.outsideFill;
  4132. textStroke = textConfig.outsideStroke;
  4133. if (textFill == null || textFill === 'auto') {
  4134. textFill = this.getOutsideFill();
  4135. }
  4136. if (textStroke == null || textStroke === 'auto') {
  4137. textStroke = this.getOutsideStroke(textFill);
  4138. autoStroke = true;
  4139. }
  4140. }
  4141. textFill = textFill || '#000';
  4142. if (textFill !== innerTextDefaultStyle.fill
  4143. || textStroke !== innerTextDefaultStyle.stroke
  4144. || autoStroke !== innerTextDefaultStyle.autoStroke
  4145. || textAlign !== innerTextDefaultStyle.align
  4146. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  4147. textStyleChanged = true;
  4148. innerTextDefaultStyle.fill = textFill;
  4149. innerTextDefaultStyle.stroke = textStroke;
  4150. innerTextDefaultStyle.autoStroke = autoStroke;
  4151. innerTextDefaultStyle.align = textAlign;
  4152. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  4153. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  4154. }
  4155. if (textStyleChanged) {
  4156. textEl.dirtyStyle();
  4157. }
  4158. textEl.markRedraw();
  4159. }
  4160. };
  4161. Element.prototype.canBeInsideText = function () {
  4162. return true;
  4163. };
  4164. Element.prototype.getInsideTextFill = function () {
  4165. return '#fff';
  4166. };
  4167. Element.prototype.getInsideTextStroke = function (textFill) {
  4168. return '#000';
  4169. };
  4170. Element.prototype.getOutsideFill = function () {
  4171. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  4172. };
  4173. Element.prototype.getOutsideStroke = function (textFill) {
  4174. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  4175. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  4176. if (!colorArr) {
  4177. colorArr = [255, 255, 255, 1];
  4178. }
  4179. var alpha = colorArr[3];
  4180. var isDark = this.__zr.isDarkMode();
  4181. for (var i = 0; i < 3; i++) {
  4182. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  4183. }
  4184. colorArr[3] = 1;
  4185. return stringify(colorArr, 'rgba');
  4186. };
  4187. Element.prototype.traverse = function (cb, context) { };
  4188. Element.prototype.attrKV = function (key, value) {
  4189. if (key === 'textConfig') {
  4190. this.setTextConfig(value);
  4191. }
  4192. else if (key === 'textContent') {
  4193. this.setTextContent(value);
  4194. }
  4195. else if (key === 'clipPath') {
  4196. this.setClipPath(value);
  4197. }
  4198. else if (key === 'extra') {
  4199. this.extra = this.extra || {};
  4200. extend(this.extra, value);
  4201. }
  4202. else {
  4203. this[key] = value;
  4204. }
  4205. };
  4206. Element.prototype.hide = function () {
  4207. this.ignore = true;
  4208. this.markRedraw();
  4209. };
  4210. Element.prototype.show = function () {
  4211. this.ignore = false;
  4212. this.markRedraw();
  4213. };
  4214. Element.prototype.attr = function (keyOrObj, value) {
  4215. if (typeof keyOrObj === 'string') {
  4216. this.attrKV(keyOrObj, value);
  4217. }
  4218. else if (isObject(keyOrObj)) {
  4219. var obj = keyOrObj;
  4220. var keysArr = keys(obj);
  4221. for (var i = 0; i < keysArr.length; i++) {
  4222. var key = keysArr[i];
  4223. this.attrKV(key, keyOrObj[key]);
  4224. }
  4225. }
  4226. this.markRedraw();
  4227. return this;
  4228. };
  4229. Element.prototype.saveCurrentToNormalState = function (toState) {
  4230. this._innerSaveToNormal(toState);
  4231. var normalState = this._normalState;
  4232. for (var i = 0; i < this.animators.length; i++) {
  4233. var animator = this.animators[i];
  4234. var fromStateTransition = animator.__fromStateTransition;
  4235. if (fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  4236. continue;
  4237. }
  4238. var targetName = animator.targetName;
  4239. var target = targetName
  4240. ? normalState[targetName] : normalState;
  4241. animator.saveFinalToTarget(target);
  4242. }
  4243. };
  4244. Element.prototype._innerSaveToNormal = function (toState) {
  4245. var normalState = this._normalState;
  4246. if (!normalState) {
  4247. normalState = this._normalState = {};
  4248. }
  4249. if (toState.textConfig && !normalState.textConfig) {
  4250. normalState.textConfig = this.textConfig;
  4251. }
  4252. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  4253. };
  4254. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  4255. for (var i = 0; i < primaryKeys.length; i++) {
  4256. var key = primaryKeys[i];
  4257. if (toState[key] != null && !(key in normalState)) {
  4258. normalState[key] = this[key];
  4259. }
  4260. }
  4261. };
  4262. Element.prototype.hasState = function () {
  4263. return this.currentStates.length > 0;
  4264. };
  4265. Element.prototype.getState = function (name) {
  4266. return this.states[name];
  4267. };
  4268. Element.prototype.ensureState = function (name) {
  4269. var states = this.states;
  4270. if (!states[name]) {
  4271. states[name] = {};
  4272. }
  4273. return states[name];
  4274. };
  4275. Element.prototype.clearStates = function (noAnimation) {
  4276. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  4277. };
  4278. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation) {
  4279. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  4280. var hasStates = this.hasState();
  4281. if (!hasStates && toNormalState) {
  4282. return;
  4283. }
  4284. var currentStates = this.currentStates;
  4285. var animationCfg = this.stateTransition;
  4286. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  4287. return;
  4288. }
  4289. var state;
  4290. if (this.stateProxy && !toNormalState) {
  4291. state = this.stateProxy(stateName);
  4292. }
  4293. if (!state) {
  4294. state = (this.states && this.states[stateName]);
  4295. }
  4296. if (!state && !toNormalState) {
  4297. logError("State " + stateName + " not exists.");
  4298. return;
  4299. }
  4300. if (!toNormalState) {
  4301. this.saveCurrentToNormalState(state);
  4302. }
  4303. var useHoverLayer = !!(state && state.hoverLayer);
  4304. if (useHoverLayer) {
  4305. this._toggleHoverLayerFlag(true);
  4306. }
  4307. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  4308. if (this._textContent) {
  4309. this._textContent.useState(stateName, keepCurrentStates);
  4310. }
  4311. if (this._textGuide) {
  4312. this._textGuide.useState(stateName, keepCurrentStates);
  4313. }
  4314. if (toNormalState) {
  4315. this.currentStates = [];
  4316. this._normalState = {};
  4317. }
  4318. else {
  4319. if (!keepCurrentStates) {
  4320. this.currentStates = [stateName];
  4321. }
  4322. else {
  4323. this.currentStates.push(stateName);
  4324. }
  4325. }
  4326. this._updateAnimationTargets();
  4327. this.markRedraw();
  4328. if (!useHoverLayer && this.__inHover) {
  4329. this._toggleHoverLayerFlag(false);
  4330. this.__dirty &= ~Element.REDARAW_BIT;
  4331. }
  4332. return state;
  4333. };
  4334. Element.prototype.useStates = function (states, noAnimation) {
  4335. if (!states.length) {
  4336. this.clearStates();
  4337. }
  4338. else {
  4339. var stateObjects = [];
  4340. var currentStates = this.currentStates;
  4341. var len = states.length;
  4342. var notChange = len === currentStates.length;
  4343. if (notChange) {
  4344. for (var i = 0; i < len; i++) {
  4345. if (states[i] !== currentStates[i]) {
  4346. notChange = false;
  4347. break;
  4348. }
  4349. }
  4350. }
  4351. if (notChange) {
  4352. return;
  4353. }
  4354. for (var i = 0; i < len; i++) {
  4355. var stateName = states[i];
  4356. var stateObj = void 0;
  4357. if (this.stateProxy) {
  4358. stateObj = this.stateProxy(stateName, states);
  4359. }
  4360. if (!stateObj) {
  4361. stateObj = this.states[stateName];
  4362. }
  4363. if (stateObj) {
  4364. stateObjects.push(stateObj);
  4365. }
  4366. }
  4367. var useHoverLayer = !!(stateObjects[len - 1] && stateObjects[len - 1].hoverLayer);
  4368. if (useHoverLayer) {
  4369. this._toggleHoverLayerFlag(true);
  4370. }
  4371. var mergedState = this._mergeStates(stateObjects);
  4372. var animationCfg = this.stateTransition;
  4373. this.saveCurrentToNormalState(mergedState);
  4374. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  4375. if (this._textContent) {
  4376. this._textContent.useStates(states);
  4377. }
  4378. if (this._textGuide) {
  4379. this._textGuide.useStates(states);
  4380. }
  4381. this._updateAnimationTargets();
  4382. this.currentStates = states.slice();
  4383. this.markRedraw();
  4384. if (!useHoverLayer && this.__inHover) {
  4385. this._toggleHoverLayerFlag(false);
  4386. this.__dirty &= ~Element.REDARAW_BIT;
  4387. }
  4388. }
  4389. };
  4390. Element.prototype._updateAnimationTargets = function () {
  4391. for (var i = 0; i < this.animators.length; i++) {
  4392. var animator = this.animators[i];
  4393. if (animator.targetName) {
  4394. animator.changeTarget(this[animator.targetName]);
  4395. }
  4396. }
  4397. };
  4398. Element.prototype.removeState = function (state) {
  4399. var idx = indexOf(this.currentStates, state);
  4400. if (idx >= 0) {
  4401. var currentStates = this.currentStates.slice();
  4402. currentStates.splice(idx, 1);
  4403. this.useStates(currentStates);
  4404. }
  4405. };
  4406. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  4407. var currentStates = this.currentStates.slice();
  4408. var idx = indexOf(currentStates, oldState);
  4409. var newStateExists = indexOf(currentStates, newState) >= 0;
  4410. if (idx >= 0) {
  4411. if (!newStateExists) {
  4412. currentStates[idx] = newState;
  4413. }
  4414. else {
  4415. currentStates.splice(idx, 1);
  4416. }
  4417. }
  4418. else if (forceAdd && !newStateExists) {
  4419. currentStates.push(newState);
  4420. }
  4421. this.useStates(currentStates);
  4422. };
  4423. Element.prototype.toggleState = function (state, enable) {
  4424. if (enable) {
  4425. this.useState(state, true);
  4426. }
  4427. else {
  4428. this.removeState(state);
  4429. }
  4430. };
  4431. Element.prototype._mergeStates = function (states) {
  4432. var mergedState = {};
  4433. var mergedTextConfig;
  4434. for (var i = 0; i < states.length; i++) {
  4435. var state = states[i];
  4436. extend(mergedState, state);
  4437. if (state.textConfig) {
  4438. mergedTextConfig = mergedTextConfig || {};
  4439. extend(mergedTextConfig, state.textConfig);
  4440. }
  4441. }
  4442. if (mergedTextConfig) {
  4443. mergedState.textConfig = mergedTextConfig;
  4444. }
  4445. return mergedState;
  4446. };
  4447. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  4448. var needsRestoreToNormal = !(state && keepCurrentStates);
  4449. if (state && state.textConfig) {
  4450. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  4451. extend(this.textConfig, state.textConfig);
  4452. }
  4453. else if (needsRestoreToNormal) {
  4454. if (normalState.textConfig) {
  4455. this.textConfig = normalState.textConfig;
  4456. }
  4457. }
  4458. var transitionTarget = {};
  4459. var hasTransition = false;
  4460. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  4461. var key = PRIMARY_STATES_KEYS[i];
  4462. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  4463. if (state && state[key] != null) {
  4464. if (propNeedsTransition) {
  4465. hasTransition = true;
  4466. transitionTarget[key] = state[key];
  4467. }
  4468. else {
  4469. this[key] = state[key];
  4470. }
  4471. }
  4472. else if (needsRestoreToNormal) {
  4473. if (normalState[key] != null) {
  4474. if (propNeedsTransition) {
  4475. hasTransition = true;
  4476. transitionTarget[key] = normalState[key];
  4477. }
  4478. else {
  4479. this[key] = normalState[key];
  4480. }
  4481. }
  4482. }
  4483. }
  4484. if (!transition) {
  4485. for (var i = 0; i < this.animators.length; i++) {
  4486. var animator = this.animators[i];
  4487. var targetName = animator.targetName;
  4488. animator.__changeFinalValue(targetName
  4489. ? (state || normalState)[targetName]
  4490. : (state || normalState));
  4491. }
  4492. }
  4493. if (hasTransition) {
  4494. this._transitionState(stateName, transitionTarget, animationCfg);
  4495. }
  4496. };
  4497. Element.prototype._attachComponent = function (componentEl) {
  4498. if (componentEl.__zr && !componentEl.__hostTarget) {
  4499. throw new Error('Text element has been added to zrender.');
  4500. }
  4501. if (componentEl === this) {
  4502. throw new Error('Recursive component attachment.');
  4503. }
  4504. var zr = this.__zr;
  4505. if (zr) {
  4506. componentEl.addSelfToZr(zr);
  4507. }
  4508. componentEl.__zr = zr;
  4509. componentEl.__hostTarget = this;
  4510. };
  4511. Element.prototype._detachComponent = function (componentEl) {
  4512. if (componentEl.__zr) {
  4513. componentEl.removeSelfFromZr(componentEl.__zr);
  4514. }
  4515. componentEl.__zr = null;
  4516. componentEl.__hostTarget = null;
  4517. };
  4518. Element.prototype.getClipPath = function () {
  4519. return this._clipPath;
  4520. };
  4521. Element.prototype.setClipPath = function (clipPath) {
  4522. if (this._clipPath && this._clipPath !== clipPath) {
  4523. this.removeClipPath();
  4524. }
  4525. this._attachComponent(clipPath);
  4526. this._clipPath = clipPath;
  4527. this.markRedraw();
  4528. };
  4529. Element.prototype.removeClipPath = function () {
  4530. var clipPath = this._clipPath;
  4531. if (clipPath) {
  4532. this._detachComponent(clipPath);
  4533. this._clipPath = null;
  4534. this.markRedraw();
  4535. }
  4536. };
  4537. Element.prototype.getTextContent = function () {
  4538. return this._textContent;
  4539. };
  4540. Element.prototype.setTextContent = function (textEl) {
  4541. var previousTextContent = this._textContent;
  4542. if (previousTextContent === textEl) {
  4543. return;
  4544. }
  4545. if (previousTextContent && previousTextContent !== textEl) {
  4546. this.removeTextContent();
  4547. }
  4548. if (textEl.__zr && !textEl.__hostTarget) {
  4549. throw new Error('Text element has been added to zrender.');
  4550. }
  4551. textEl.attachedTransform = new Transformable();
  4552. this._attachComponent(textEl);
  4553. this._textContent = textEl;
  4554. this.markRedraw();
  4555. };
  4556. Element.prototype.setTextConfig = function (cfg) {
  4557. if (!this.textConfig) {
  4558. this.textConfig = {};
  4559. }
  4560. extend(this.textConfig, cfg);
  4561. this.markRedraw();
  4562. };
  4563. Element.prototype.removeTextContent = function () {
  4564. var textEl = this._textContent;
  4565. if (textEl) {
  4566. textEl.attachedTransform = null;
  4567. this._detachComponent(textEl);
  4568. this._textContent = null;
  4569. this._innerTextDefaultStyle = null;
  4570. this.markRedraw();
  4571. }
  4572. };
  4573. Element.prototype.getTextGuideLine = function () {
  4574. return this._textGuide;
  4575. };
  4576. Element.prototype.setTextGuideLine = function (guideLine) {
  4577. if (this._textGuide && this._textGuide !== guideLine) {
  4578. this.removeTextGuideLine();
  4579. }
  4580. this._attachComponent(guideLine);
  4581. this._textGuide = guideLine;
  4582. this.markRedraw();
  4583. };
  4584. Element.prototype.removeTextGuideLine = function () {
  4585. var textGuide = this._textGuide;
  4586. if (textGuide) {
  4587. this._detachComponent(textGuide);
  4588. this._textGuide = null;
  4589. this.markRedraw();
  4590. }
  4591. };
  4592. Element.prototype.markRedraw = function () {
  4593. this.__dirty |= Element.REDARAW_BIT;
  4594. var zr = this.__zr;
  4595. if (zr) {
  4596. if (this.__inHover) {
  4597. zr.refreshHover();
  4598. }
  4599. else {
  4600. zr.refresh();
  4601. }
  4602. }
  4603. if (this.__hostTarget) {
  4604. this.__hostTarget.markRedraw();
  4605. }
  4606. };
  4607. Element.prototype.dirty = function () {
  4608. this.markRedraw();
  4609. };
  4610. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  4611. this.__inHover = inHover;
  4612. var textContent = this._textContent;
  4613. var textGuide = this._textGuide;
  4614. if (textContent) {
  4615. textContent.__inHover = inHover;
  4616. }
  4617. if (textGuide) {
  4618. textGuide.__inHover = inHover;
  4619. }
  4620. };
  4621. Element.prototype.addSelfToZr = function (zr) {
  4622. this.__zr = zr;
  4623. var animators = this.animators;
  4624. if (animators) {
  4625. for (var i = 0; i < animators.length; i++) {
  4626. zr.animation.addAnimator(animators[i]);
  4627. }
  4628. }
  4629. if (this._clipPath) {
  4630. this._clipPath.addSelfToZr(zr);
  4631. }
  4632. if (this._textContent) {
  4633. this._textContent.addSelfToZr(zr);
  4634. }
  4635. if (this._textGuide) {
  4636. this._textGuide.addSelfToZr(zr);
  4637. }
  4638. };
  4639. Element.prototype.removeSelfFromZr = function (zr) {
  4640. this.__zr = null;
  4641. var animators = this.animators;
  4642. if (animators) {
  4643. for (var i = 0; i < animators.length; i++) {
  4644. zr.animation.removeAnimator(animators[i]);
  4645. }
  4646. }
  4647. if (this._clipPath) {
  4648. this._clipPath.removeSelfFromZr(zr);
  4649. }
  4650. if (this._textContent) {
  4651. this._textContent.removeSelfFromZr(zr);
  4652. }
  4653. if (this._textGuide) {
  4654. this._textGuide.removeSelfFromZr(zr);
  4655. }
  4656. };
  4657. Element.prototype.animate = function (key, loop) {
  4658. var target = key ? this[key] : this;
  4659. if (!target) {
  4660. logError('Property "'
  4661. + key
  4662. + '" is not existed in element '
  4663. + this.id);
  4664. return;
  4665. }
  4666. var animator = new Animator(target, loop);
  4667. this.addAnimator(animator, key);
  4668. return animator;
  4669. };
  4670. Element.prototype.addAnimator = function (animator, key) {
  4671. var zr = this.__zr;
  4672. var el = this;
  4673. animator.during(function () {
  4674. el.updateDuringAnimation(key);
  4675. }).done(function () {
  4676. var animators = el.animators;
  4677. var idx = indexOf(animators, animator);
  4678. if (idx >= 0) {
  4679. animators.splice(idx, 1);
  4680. }
  4681. });
  4682. this.animators.push(animator);
  4683. if (zr) {
  4684. zr.animation.addAnimator(animator);
  4685. }
  4686. zr && zr.wakeUp();
  4687. };
  4688. Element.prototype.updateDuringAnimation = function (key) {
  4689. this.markRedraw();
  4690. };
  4691. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  4692. var animators = this.animators;
  4693. var len = animators.length;
  4694. var leftAnimators = [];
  4695. for (var i = 0; i < len; i++) {
  4696. var animator = animators[i];
  4697. if (!scope || scope === animator.scope) {
  4698. animator.stop(forwardToLast);
  4699. }
  4700. else {
  4701. leftAnimators.push(animator);
  4702. }
  4703. }
  4704. this.animators = leftAnimators;
  4705. return this;
  4706. };
  4707. Element.prototype.animateTo = function (target, cfg, animationProps) {
  4708. animateTo(this, target, cfg, animationProps);
  4709. };
  4710. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  4711. animateTo(this, target, cfg, animationProps, true);
  4712. };
  4713. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  4714. var animators = animateTo(this, target, cfg, animationProps);
  4715. for (var i = 0; i < animators.length; i++) {
  4716. animators[i].__fromStateTransition = stateName;
  4717. }
  4718. };
  4719. Element.prototype.getBoundingRect = function () {
  4720. return null;
  4721. };
  4722. Element.prototype.getPaintRect = function () {
  4723. return null;
  4724. };
  4725. Element.REDARAW_BIT = 1;
  4726. Element.initDefaultProps = (function () {
  4727. var elProto = Element.prototype;
  4728. elProto.type = 'element';
  4729. elProto.name = '';
  4730. elProto.ignore = false;
  4731. elProto.silent = false;
  4732. elProto.isGroup = false;
  4733. elProto.draggable = false;
  4734. elProto.dragging = false;
  4735. elProto.ignoreClip = false;
  4736. elProto.__inHover = false;
  4737. elProto.__dirty = Element.REDARAW_BIT;
  4738. var logs = {};
  4739. function logDeprecatedError(key, xKey, yKey) {
  4740. if (!logs[key + xKey + yKey]) {
  4741. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  4742. logs[key + xKey + yKey] = true;
  4743. }
  4744. }
  4745. function createLegacyProperty(key, privateKey, xKey, yKey) {
  4746. Object.defineProperty(elProto, key, {
  4747. get: function () {
  4748. logDeprecatedError(key, xKey, yKey);
  4749. if (!this[privateKey]) {
  4750. var pos = this[privateKey] = [];
  4751. enhanceArray(this, pos);
  4752. }
  4753. return this[privateKey];
  4754. },
  4755. set: function (pos) {
  4756. logDeprecatedError(key, xKey, yKey);
  4757. this[xKey] = pos[0];
  4758. this[yKey] = pos[1];
  4759. this[privateKey] = pos;
  4760. enhanceArray(this, pos);
  4761. }
  4762. });
  4763. function enhanceArray(self, pos) {
  4764. Object.defineProperty(pos, 0, {
  4765. get: function () {
  4766. return self[xKey];
  4767. },
  4768. set: function (val) {
  4769. self[xKey] = val;
  4770. }
  4771. });
  4772. Object.defineProperty(pos, 1, {
  4773. get: function () {
  4774. return self[yKey];
  4775. },
  4776. set: function (val) {
  4777. self[yKey] = val;
  4778. }
  4779. });
  4780. }
  4781. }
  4782. if (Object.defineProperty && (!env.browser.ie || env.browser.version > 8)) {
  4783. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  4784. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  4785. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  4786. }
  4787. })();
  4788. return Element;
  4789. }());
  4790. mixin(Element, Eventful);
  4791. mixin(Element, Transformable);
  4792. function animateTo(animatable, target, cfg, animationProps, reverse) {
  4793. cfg = cfg || {};
  4794. var animators = [];
  4795. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  4796. var finishCount = animators.length;
  4797. var doneHappened = false;
  4798. var cfgDone = cfg.done;
  4799. var cfgAborted = cfg.aborted;
  4800. var doneCb = function () {
  4801. doneHappened = true;
  4802. finishCount--;
  4803. if (finishCount <= 0) {
  4804. doneHappened
  4805. ? (cfgDone && cfgDone())
  4806. : (cfgAborted && cfgAborted());
  4807. }
  4808. };
  4809. var abortedCb = function () {
  4810. finishCount--;
  4811. if (finishCount <= 0) {
  4812. doneHappened
  4813. ? (cfgDone && cfgDone())
  4814. : (cfgAborted && cfgAborted());
  4815. }
  4816. };
  4817. if (!finishCount) {
  4818. cfgDone && cfgDone();
  4819. }
  4820. if (animators.length > 0 && cfg.during) {
  4821. animators[0].during(function (target, percent) {
  4822. cfg.during(percent);
  4823. });
  4824. }
  4825. for (var i = 0; i < animators.length; i++) {
  4826. var animator = animators[i];
  4827. if (doneCb) {
  4828. animator.done(doneCb);
  4829. }
  4830. if (abortedCb) {
  4831. animator.aborted(abortedCb);
  4832. }
  4833. animator.start(cfg.easing, cfg.force);
  4834. }
  4835. return animators;
  4836. }
  4837. function copyArrShallow(source, target, len) {
  4838. for (var i = 0; i < len; i++) {
  4839. source[i] = target[i];
  4840. }
  4841. }
  4842. function is2DArray(value) {
  4843. return isArrayLike(value[0]);
  4844. }
  4845. function copyValue(target, source, key) {
  4846. if (isArrayLike(source[key])) {
  4847. if (!isArrayLike(target[key])) {
  4848. target[key] = [];
  4849. }
  4850. if (isTypedArray(source[key])) {
  4851. var len = source[key].length;
  4852. if (target[key].length !== len) {
  4853. target[key] = new (source[key].constructor)(len);
  4854. copyArrShallow(target[key], source[key], len);
  4855. }
  4856. }
  4857. else {
  4858. var sourceArr = source[key];
  4859. var targetArr = target[key];
  4860. var len0 = sourceArr.length;
  4861. if (is2DArray(sourceArr)) {
  4862. var len1 = sourceArr[0].length;
  4863. for (var i = 0; i < len0; i++) {
  4864. if (!targetArr[i]) {
  4865. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  4866. }
  4867. else {
  4868. copyArrShallow(targetArr[i], sourceArr[i], len1);
  4869. }
  4870. }
  4871. }
  4872. else {
  4873. copyArrShallow(targetArr, sourceArr, len0);
  4874. }
  4875. targetArr.length = sourceArr.length;
  4876. }
  4877. }
  4878. else {
  4879. target[key] = source[key];
  4880. }
  4881. }
  4882. function animateToShallow(animatable, topKey, source, target, cfg, animationProps, animators, reverse) {
  4883. var animatableKeys = [];
  4884. var changedKeys = [];
  4885. var targetKeys = keys(target);
  4886. var duration = cfg.duration;
  4887. var delay = cfg.delay;
  4888. var additive = cfg.additive;
  4889. var setToFinal = cfg.setToFinal;
  4890. var animateAll = !isObject(animationProps);
  4891. for (var k = 0; k < targetKeys.length; k++) {
  4892. var innerKey = targetKeys[k];
  4893. if (source[innerKey] != null
  4894. && target[innerKey] != null
  4895. && (animateAll || animationProps[innerKey])) {
  4896. if (isObject(target[innerKey]) && !isArrayLike(target[innerKey])) {
  4897. if (topKey) {
  4898. if (!reverse) {
  4899. source[innerKey] = target[innerKey];
  4900. animatable.updateDuringAnimation(topKey);
  4901. }
  4902. continue;
  4903. }
  4904. animateToShallow(animatable, innerKey, source[innerKey], target[innerKey], cfg, animationProps && animationProps[innerKey], animators, reverse);
  4905. }
  4906. else {
  4907. animatableKeys.push(innerKey);
  4908. changedKeys.push(innerKey);
  4909. }
  4910. }
  4911. else if (!reverse) {
  4912. source[innerKey] = target[innerKey];
  4913. animatable.updateDuringAnimation(topKey);
  4914. changedKeys.push(innerKey);
  4915. }
  4916. }
  4917. var keyLen = animatableKeys.length;
  4918. if (keyLen > 0
  4919. || (cfg.force && !animators.length)) {
  4920. var existsAnimators = animatable.animators;
  4921. var existsAnimatorsOnSameTarget = [];
  4922. for (var i = 0; i < existsAnimators.length; i++) {
  4923. if (existsAnimators[i].targetName === topKey) {
  4924. existsAnimatorsOnSameTarget.push(existsAnimators[i]);
  4925. }
  4926. }
  4927. if (!additive && existsAnimatorsOnSameTarget.length) {
  4928. for (var i = 0; i < existsAnimatorsOnSameTarget.length; i++) {
  4929. var allAborted = existsAnimatorsOnSameTarget[i].stopTracks(changedKeys);
  4930. if (allAborted) {
  4931. var idx = indexOf(existsAnimators, existsAnimatorsOnSameTarget[i]);
  4932. existsAnimators.splice(idx, 1);
  4933. }
  4934. }
  4935. }
  4936. var revertedSource = void 0;
  4937. var reversedTarget = void 0;
  4938. var sourceClone = void 0;
  4939. if (reverse) {
  4940. reversedTarget = {};
  4941. if (setToFinal) {
  4942. revertedSource = {};
  4943. }
  4944. for (var i = 0; i < keyLen; i++) {
  4945. var innerKey = animatableKeys[i];
  4946. reversedTarget[innerKey] = source[innerKey];
  4947. if (setToFinal) {
  4948. revertedSource[innerKey] = target[innerKey];
  4949. }
  4950. else {
  4951. source[innerKey] = target[innerKey];
  4952. }
  4953. }
  4954. }
  4955. else if (setToFinal) {
  4956. sourceClone = {};
  4957. for (var i = 0; i < keyLen; i++) {
  4958. var innerKey = animatableKeys[i];
  4959. sourceClone[innerKey] = cloneValue(source[innerKey]);
  4960. copyValue(source, target, innerKey);
  4961. }
  4962. }
  4963. var animator = new Animator(source, false, additive ? existsAnimatorsOnSameTarget : null);
  4964. animator.targetName = topKey;
  4965. if (cfg.scope) {
  4966. animator.scope = cfg.scope;
  4967. }
  4968. if (setToFinal && revertedSource) {
  4969. animator.whenWithKeys(0, revertedSource, animatableKeys);
  4970. }
  4971. if (sourceClone) {
  4972. animator.whenWithKeys(0, sourceClone, animatableKeys);
  4973. }
  4974. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animatableKeys).delay(delay || 0);
  4975. animatable.addAnimator(animator, topKey);
  4976. animators.push(animator);
  4977. }
  4978. }
  4979. var DEFAULT_MIN_MERGE = 32;
  4980. var DEFAULT_MIN_GALLOPING = 7;
  4981. function minRunLength(n) {
  4982. var r = 0;
  4983. while (n >= DEFAULT_MIN_MERGE) {
  4984. r |= n & 1;
  4985. n >>= 1;
  4986. }
  4987. return n + r;
  4988. }
  4989. function makeAscendingRun(array, lo, hi, compare) {
  4990. var runHi = lo + 1;
  4991. if (runHi === hi) {
  4992. return 1;
  4993. }
  4994. if (compare(array[runHi++], array[lo]) < 0) {
  4995. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4996. runHi++;
  4997. }
  4998. reverseRun(array, lo, runHi);
  4999. }
  5000. else {
  5001. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5002. runHi++;
  5003. }
  5004. }
  5005. return runHi - lo;
  5006. }
  5007. function reverseRun(array, lo, hi) {
  5008. hi--;
  5009. while (lo < hi) {
  5010. var t = array[lo];
  5011. array[lo++] = array[hi];
  5012. array[hi--] = t;
  5013. }
  5014. }
  5015. function binaryInsertionSort(array, lo, hi, start, compare) {
  5016. if (start === lo) {
  5017. start++;
  5018. }
  5019. for (; start < hi; start++) {
  5020. var pivot = array[start];
  5021. var left = lo;
  5022. var right = start;
  5023. var mid;
  5024. while (left < right) {
  5025. mid = left + right >>> 1;
  5026. if (compare(pivot, array[mid]) < 0) {
  5027. right = mid;
  5028. }
  5029. else {
  5030. left = mid + 1;
  5031. }
  5032. }
  5033. var n = start - left;
  5034. switch (n) {
  5035. case 3:
  5036. array[left + 3] = array[left + 2];
  5037. case 2:
  5038. array[left + 2] = array[left + 1];
  5039. case 1:
  5040. array[left + 1] = array[left];
  5041. break;
  5042. default:
  5043. while (n > 0) {
  5044. array[left + n] = array[left + n - 1];
  5045. n--;
  5046. }
  5047. }
  5048. array[left] = pivot;
  5049. }
  5050. }
  5051. function gallopLeft(value, array, start, length, hint, compare) {
  5052. var lastOffset = 0;
  5053. var maxOffset = 0;
  5054. var offset = 1;
  5055. if (compare(value, array[start + hint]) > 0) {
  5056. maxOffset = length - hint;
  5057. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5058. lastOffset = offset;
  5059. offset = (offset << 1) + 1;
  5060. if (offset <= 0) {
  5061. offset = maxOffset;
  5062. }
  5063. }
  5064. if (offset > maxOffset) {
  5065. offset = maxOffset;
  5066. }
  5067. lastOffset += hint;
  5068. offset += hint;
  5069. }
  5070. else {
  5071. maxOffset = hint + 1;
  5072. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5073. lastOffset = offset;
  5074. offset = (offset << 1) + 1;
  5075. if (offset <= 0) {
  5076. offset = maxOffset;
  5077. }
  5078. }
  5079. if (offset > maxOffset) {
  5080. offset = maxOffset;
  5081. }
  5082. var tmp = lastOffset;
  5083. lastOffset = hint - offset;
  5084. offset = hint - tmp;
  5085. }
  5086. lastOffset++;
  5087. while (lastOffset < offset) {
  5088. var m = lastOffset + (offset - lastOffset >>> 1);
  5089. if (compare(value, array[start + m]) > 0) {
  5090. lastOffset = m + 1;
  5091. }
  5092. else {
  5093. offset = m;
  5094. }
  5095. }
  5096. return offset;
  5097. }
  5098. function gallopRight(value, array, start, length, hint, compare) {
  5099. var lastOffset = 0;
  5100. var maxOffset = 0;
  5101. var offset = 1;
  5102. if (compare(value, array[start + hint]) < 0) {
  5103. maxOffset = hint + 1;
  5104. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5105. lastOffset = offset;
  5106. offset = (offset << 1) + 1;
  5107. if (offset <= 0) {
  5108. offset = maxOffset;
  5109. }
  5110. }
  5111. if (offset > maxOffset) {
  5112. offset = maxOffset;
  5113. }
  5114. var tmp = lastOffset;
  5115. lastOffset = hint - offset;
  5116. offset = hint - tmp;
  5117. }
  5118. else {
  5119. maxOffset = length - hint;
  5120. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5121. lastOffset = offset;
  5122. offset = (offset << 1) + 1;
  5123. if (offset <= 0) {
  5124. offset = maxOffset;
  5125. }
  5126. }
  5127. if (offset > maxOffset) {
  5128. offset = maxOffset;
  5129. }
  5130. lastOffset += hint;
  5131. offset += hint;
  5132. }
  5133. lastOffset++;
  5134. while (lastOffset < offset) {
  5135. var m = lastOffset + (offset - lastOffset >>> 1);
  5136. if (compare(value, array[start + m]) < 0) {
  5137. offset = m;
  5138. }
  5139. else {
  5140. lastOffset = m + 1;
  5141. }
  5142. }
  5143. return offset;
  5144. }
  5145. function TimSort(array, compare) {
  5146. var minGallop = DEFAULT_MIN_GALLOPING;
  5147. var length = 0;
  5148. var runStart;
  5149. var runLength;
  5150. var stackSize = 0;
  5151. length = array.length;
  5152. var tmp = [];
  5153. runStart = [];
  5154. runLength = [];
  5155. function pushRun(_runStart, _runLength) {
  5156. runStart[stackSize] = _runStart;
  5157. runLength[stackSize] = _runLength;
  5158. stackSize += 1;
  5159. }
  5160. function mergeRuns() {
  5161. while (stackSize > 1) {
  5162. var n = stackSize - 2;
  5163. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5164. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  5165. if (runLength[n - 1] < runLength[n + 1]) {
  5166. n--;
  5167. }
  5168. }
  5169. else if (runLength[n] > runLength[n + 1]) {
  5170. break;
  5171. }
  5172. mergeAt(n);
  5173. }
  5174. }
  5175. function forceMergeRuns() {
  5176. while (stackSize > 1) {
  5177. var n = stackSize - 2;
  5178. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5179. n--;
  5180. }
  5181. mergeAt(n);
  5182. }
  5183. }
  5184. function mergeAt(i) {
  5185. var start1 = runStart[i];
  5186. var length1 = runLength[i];
  5187. var start2 = runStart[i + 1];
  5188. var length2 = runLength[i + 1];
  5189. runLength[i] = length1 + length2;
  5190. if (i === stackSize - 3) {
  5191. runStart[i + 1] = runStart[i + 2];
  5192. runLength[i + 1] = runLength[i + 2];
  5193. }
  5194. stackSize--;
  5195. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5196. start1 += k;
  5197. length1 -= k;
  5198. if (length1 === 0) {
  5199. return;
  5200. }
  5201. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5202. if (length2 === 0) {
  5203. return;
  5204. }
  5205. if (length1 <= length2) {
  5206. mergeLow(start1, length1, start2, length2);
  5207. }
  5208. else {
  5209. mergeHigh(start1, length1, start2, length2);
  5210. }
  5211. }
  5212. function mergeLow(start1, length1, start2, length2) {
  5213. var i = 0;
  5214. for (i = 0; i < length1; i++) {
  5215. tmp[i] = array[start1 + i];
  5216. }
  5217. var cursor1 = 0;
  5218. var cursor2 = start2;
  5219. var dest = start1;
  5220. array[dest++] = array[cursor2++];
  5221. if (--length2 === 0) {
  5222. for (i = 0; i < length1; i++) {
  5223. array[dest + i] = tmp[cursor1 + i];
  5224. }
  5225. return;
  5226. }
  5227. if (length1 === 1) {
  5228. for (i = 0; i < length2; i++) {
  5229. array[dest + i] = array[cursor2 + i];
  5230. }
  5231. array[dest + length2] = tmp[cursor1];
  5232. return;
  5233. }
  5234. var _minGallop = minGallop;
  5235. var count1;
  5236. var count2;
  5237. var exit;
  5238. while (1) {
  5239. count1 = 0;
  5240. count2 = 0;
  5241. exit = false;
  5242. do {
  5243. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5244. array[dest++] = array[cursor2++];
  5245. count2++;
  5246. count1 = 0;
  5247. if (--length2 === 0) {
  5248. exit = true;
  5249. break;
  5250. }
  5251. }
  5252. else {
  5253. array[dest++] = tmp[cursor1++];
  5254. count1++;
  5255. count2 = 0;
  5256. if (--length1 === 1) {
  5257. exit = true;
  5258. break;
  5259. }
  5260. }
  5261. } while ((count1 | count2) < _minGallop);
  5262. if (exit) {
  5263. break;
  5264. }
  5265. do {
  5266. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5267. if (count1 !== 0) {
  5268. for (i = 0; i < count1; i++) {
  5269. array[dest + i] = tmp[cursor1 + i];
  5270. }
  5271. dest += count1;
  5272. cursor1 += count1;
  5273. length1 -= count1;
  5274. if (length1 <= 1) {
  5275. exit = true;
  5276. break;
  5277. }
  5278. }
  5279. array[dest++] = array[cursor2++];
  5280. if (--length2 === 0) {
  5281. exit = true;
  5282. break;
  5283. }
  5284. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5285. if (count2 !== 0) {
  5286. for (i = 0; i < count2; i++) {
  5287. array[dest + i] = array[cursor2 + i];
  5288. }
  5289. dest += count2;
  5290. cursor2 += count2;
  5291. length2 -= count2;
  5292. if (length2 === 0) {
  5293. exit = true;
  5294. break;
  5295. }
  5296. }
  5297. array[dest++] = tmp[cursor1++];
  5298. if (--length1 === 1) {
  5299. exit = true;
  5300. break;
  5301. }
  5302. _minGallop--;
  5303. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5304. if (exit) {
  5305. break;
  5306. }
  5307. if (_minGallop < 0) {
  5308. _minGallop = 0;
  5309. }
  5310. _minGallop += 2;
  5311. }
  5312. minGallop = _minGallop;
  5313. minGallop < 1 && (minGallop = 1);
  5314. if (length1 === 1) {
  5315. for (i = 0; i < length2; i++) {
  5316. array[dest + i] = array[cursor2 + i];
  5317. }
  5318. array[dest + length2] = tmp[cursor1];
  5319. }
  5320. else if (length1 === 0) {
  5321. throw new Error();
  5322. }
  5323. else {
  5324. for (i = 0; i < length1; i++) {
  5325. array[dest + i] = tmp[cursor1 + i];
  5326. }
  5327. }
  5328. }
  5329. function mergeHigh(start1, length1, start2, length2) {
  5330. var i = 0;
  5331. for (i = 0; i < length2; i++) {
  5332. tmp[i] = array[start2 + i];
  5333. }
  5334. var cursor1 = start1 + length1 - 1;
  5335. var cursor2 = length2 - 1;
  5336. var dest = start2 + length2 - 1;
  5337. var customCursor = 0;
  5338. var customDest = 0;
  5339. array[dest--] = array[cursor1--];
  5340. if (--length1 === 0) {
  5341. customCursor = dest - (length2 - 1);
  5342. for (i = 0; i < length2; i++) {
  5343. array[customCursor + i] = tmp[i];
  5344. }
  5345. return;
  5346. }
  5347. if (length2 === 1) {
  5348. dest -= length1;
  5349. cursor1 -= length1;
  5350. customDest = dest + 1;
  5351. customCursor = cursor1 + 1;
  5352. for (i = length1 - 1; i >= 0; i--) {
  5353. array[customDest + i] = array[customCursor + i];
  5354. }
  5355. array[dest] = tmp[cursor2];
  5356. return;
  5357. }
  5358. var _minGallop = minGallop;
  5359. while (true) {
  5360. var count1 = 0;
  5361. var count2 = 0;
  5362. var exit = false;
  5363. do {
  5364. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5365. array[dest--] = array[cursor1--];
  5366. count1++;
  5367. count2 = 0;
  5368. if (--length1 === 0) {
  5369. exit = true;
  5370. break;
  5371. }
  5372. }
  5373. else {
  5374. array[dest--] = tmp[cursor2--];
  5375. count2++;
  5376. count1 = 0;
  5377. if (--length2 === 1) {
  5378. exit = true;
  5379. break;
  5380. }
  5381. }
  5382. } while ((count1 | count2) < _minGallop);
  5383. if (exit) {
  5384. break;
  5385. }
  5386. do {
  5387. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5388. if (count1 !== 0) {
  5389. dest -= count1;
  5390. cursor1 -= count1;
  5391. length1 -= count1;
  5392. customDest = dest + 1;
  5393. customCursor = cursor1 + 1;
  5394. for (i = count1 - 1; i >= 0; i--) {
  5395. array[customDest + i] = array[customCursor + i];
  5396. }
  5397. if (length1 === 0) {
  5398. exit = true;
  5399. break;
  5400. }
  5401. }
  5402. array[dest--] = tmp[cursor2--];
  5403. if (--length2 === 1) {
  5404. exit = true;
  5405. break;
  5406. }
  5407. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5408. if (count2 !== 0) {
  5409. dest -= count2;
  5410. cursor2 -= count2;
  5411. length2 -= count2;
  5412. customDest = dest + 1;
  5413. customCursor = cursor2 + 1;
  5414. for (i = 0; i < count2; i++) {
  5415. array[customDest + i] = tmp[customCursor + i];
  5416. }
  5417. if (length2 <= 1) {
  5418. exit = true;
  5419. break;
  5420. }
  5421. }
  5422. array[dest--] = array[cursor1--];
  5423. if (--length1 === 0) {
  5424. exit = true;
  5425. break;
  5426. }
  5427. _minGallop--;
  5428. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5429. if (exit) {
  5430. break;
  5431. }
  5432. if (_minGallop < 0) {
  5433. _minGallop = 0;
  5434. }
  5435. _minGallop += 2;
  5436. }
  5437. minGallop = _minGallop;
  5438. if (minGallop < 1) {
  5439. minGallop = 1;
  5440. }
  5441. if (length2 === 1) {
  5442. dest -= length1;
  5443. cursor1 -= length1;
  5444. customDest = dest + 1;
  5445. customCursor = cursor1 + 1;
  5446. for (i = length1 - 1; i >= 0; i--) {
  5447. array[customDest + i] = array[customCursor + i];
  5448. }
  5449. array[dest] = tmp[cursor2];
  5450. }
  5451. else if (length2 === 0) {
  5452. throw new Error();
  5453. }
  5454. else {
  5455. customCursor = dest - (length2 - 1);
  5456. for (i = 0; i < length2; i++) {
  5457. array[customCursor + i] = tmp[i];
  5458. }
  5459. }
  5460. }
  5461. return {
  5462. mergeRuns: mergeRuns,
  5463. forceMergeRuns: forceMergeRuns,
  5464. pushRun: pushRun
  5465. };
  5466. }
  5467. function sort(array, compare, lo, hi) {
  5468. if (!lo) {
  5469. lo = 0;
  5470. }
  5471. if (!hi) {
  5472. hi = array.length;
  5473. }
  5474. var remaining = hi - lo;
  5475. if (remaining < 2) {
  5476. return;
  5477. }
  5478. var runLength = 0;
  5479. if (remaining < DEFAULT_MIN_MERGE) {
  5480. runLength = makeAscendingRun(array, lo, hi, compare);
  5481. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5482. return;
  5483. }
  5484. var ts = TimSort(array, compare);
  5485. var minRun = minRunLength(remaining);
  5486. do {
  5487. runLength = makeAscendingRun(array, lo, hi, compare);
  5488. if (runLength < minRun) {
  5489. var force = remaining;
  5490. if (force > minRun) {
  5491. force = minRun;
  5492. }
  5493. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5494. runLength = force;
  5495. }
  5496. ts.pushRun(lo, runLength);
  5497. ts.mergeRuns();
  5498. remaining -= runLength;
  5499. lo += runLength;
  5500. } while (remaining !== 0);
  5501. ts.forceMergeRuns();
  5502. }
  5503. var invalidZErrorLogged = false;
  5504. function logInvalidZError() {
  5505. if (invalidZErrorLogged) {
  5506. return;
  5507. }
  5508. invalidZErrorLogged = true;
  5509. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  5510. }
  5511. function shapeCompareFunc(a, b) {
  5512. if (a.zlevel === b.zlevel) {
  5513. if (a.z === b.z) {
  5514. return a.z2 - b.z2;
  5515. }
  5516. return a.z - b.z;
  5517. }
  5518. return a.zlevel - b.zlevel;
  5519. }
  5520. var Storage = (function () {
  5521. function Storage() {
  5522. this._roots = [];
  5523. this._displayList = [];
  5524. this._displayListLen = 0;
  5525. this.displayableSortFunc = shapeCompareFunc;
  5526. }
  5527. Storage.prototype.traverse = function (cb, context) {
  5528. for (var i = 0; i < this._roots.length; i++) {
  5529. this._roots[i].traverse(cb, context);
  5530. }
  5531. };
  5532. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  5533. includeIgnore = includeIgnore || false;
  5534. var displayList = this._displayList;
  5535. if (update || !displayList.length) {
  5536. this.updateDisplayList(includeIgnore);
  5537. }
  5538. return displayList;
  5539. };
  5540. Storage.prototype.updateDisplayList = function (includeIgnore) {
  5541. this._displayListLen = 0;
  5542. var roots = this._roots;
  5543. var displayList = this._displayList;
  5544. for (var i = 0, len = roots.length; i < len; i++) {
  5545. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5546. }
  5547. displayList.length = this._displayListLen;
  5548. env.canvasSupported && sort(displayList, shapeCompareFunc);
  5549. };
  5550. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  5551. if (el.ignore && !includeIgnore) {
  5552. return;
  5553. }
  5554. el.beforeUpdate();
  5555. el.update();
  5556. el.afterUpdate();
  5557. var userSetClipPath = el.getClipPath();
  5558. if (el.ignoreClip) {
  5559. clipPaths = null;
  5560. }
  5561. else if (userSetClipPath) {
  5562. if (clipPaths) {
  5563. clipPaths = clipPaths.slice();
  5564. }
  5565. else {
  5566. clipPaths = [];
  5567. }
  5568. var currentClipPath = userSetClipPath;
  5569. var parentClipPath = el;
  5570. while (currentClipPath) {
  5571. currentClipPath.parent = parentClipPath;
  5572. currentClipPath.updateTransform();
  5573. clipPaths.push(currentClipPath);
  5574. parentClipPath = currentClipPath;
  5575. currentClipPath = currentClipPath.getClipPath();
  5576. }
  5577. }
  5578. if (el.childrenRef) {
  5579. var children = el.childrenRef();
  5580. for (var i = 0; i < children.length; i++) {
  5581. var child = children[i];
  5582. if (el.__dirty) {
  5583. child.__dirty |= Element.REDARAW_BIT;
  5584. }
  5585. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5586. }
  5587. el.__dirty = 0;
  5588. }
  5589. else {
  5590. var disp = el;
  5591. if (clipPaths && clipPaths.length) {
  5592. disp.__clipPaths = clipPaths;
  5593. }
  5594. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  5595. disp.__clipPaths = [];
  5596. }
  5597. if (isNaN(disp.z)) {
  5598. logInvalidZError();
  5599. disp.z = 0;
  5600. }
  5601. if (isNaN(disp.z2)) {
  5602. logInvalidZError();
  5603. disp.z2 = 0;
  5604. }
  5605. if (isNaN(disp.zlevel)) {
  5606. logInvalidZError();
  5607. disp.zlevel = 0;
  5608. }
  5609. this._displayList[this._displayListLen++] = disp;
  5610. }
  5611. var decalEl = el.getDecalElement && el.getDecalElement();
  5612. if (decalEl) {
  5613. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  5614. }
  5615. var textGuide = el.getTextGuideLine();
  5616. if (textGuide) {
  5617. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  5618. }
  5619. var textEl = el.getTextContent();
  5620. if (textEl) {
  5621. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  5622. }
  5623. };
  5624. Storage.prototype.addRoot = function (el) {
  5625. if (el.__zr && el.__zr.storage === this) {
  5626. return;
  5627. }
  5628. this._roots.push(el);
  5629. };
  5630. Storage.prototype.delRoot = function (el) {
  5631. if (el instanceof Array) {
  5632. for (var i = 0, l = el.length; i < l; i++) {
  5633. this.delRoot(el[i]);
  5634. }
  5635. return;
  5636. }
  5637. var idx = indexOf(this._roots, el);
  5638. if (idx >= 0) {
  5639. this._roots.splice(idx, 1);
  5640. }
  5641. };
  5642. Storage.prototype.delAllRoots = function () {
  5643. this._roots = [];
  5644. this._displayList = [];
  5645. this._displayListLen = 0;
  5646. return;
  5647. };
  5648. Storage.prototype.getRoots = function () {
  5649. return this._roots;
  5650. };
  5651. Storage.prototype.dispose = function () {
  5652. this._displayList = null;
  5653. this._roots = null;
  5654. };
  5655. return Storage;
  5656. }());
  5657. var requestAnimationFrame;
  5658. requestAnimationFrame = (typeof window !== 'undefined'
  5659. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5660. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5661. || window.mozRequestAnimationFrame
  5662. || window.webkitRequestAnimationFrame)) || function (func) {
  5663. return setTimeout(func, 16);
  5664. };
  5665. var requestAnimationFrame$1 = requestAnimationFrame;
  5666. var Animation = (function (_super) {
  5667. __extends(Animation, _super);
  5668. function Animation(opts) {
  5669. var _this = _super.call(this) || this;
  5670. _this._running = false;
  5671. _this._time = 0;
  5672. _this._pausedTime = 0;
  5673. _this._pauseStart = 0;
  5674. _this._paused = false;
  5675. opts = opts || {};
  5676. _this.stage = opts.stage || {};
  5677. _this.onframe = opts.onframe || function () { };
  5678. return _this;
  5679. }
  5680. Animation.prototype.addClip = function (clip) {
  5681. if (clip.animation) {
  5682. this.removeClip(clip);
  5683. }
  5684. if (!this._clipsHead) {
  5685. this._clipsHead = this._clipsTail = clip;
  5686. }
  5687. else {
  5688. this._clipsTail.next = clip;
  5689. clip.prev = this._clipsTail;
  5690. clip.next = null;
  5691. this._clipsTail = clip;
  5692. }
  5693. clip.animation = this;
  5694. };
  5695. Animation.prototype.addAnimator = function (animator) {
  5696. animator.animation = this;
  5697. var clip = animator.getClip();
  5698. if (clip) {
  5699. this.addClip(clip);
  5700. }
  5701. };
  5702. Animation.prototype.removeClip = function (clip) {
  5703. if (!clip.animation) {
  5704. return;
  5705. }
  5706. var prev = clip.prev;
  5707. var next = clip.next;
  5708. if (prev) {
  5709. prev.next = next;
  5710. }
  5711. else {
  5712. this._clipsHead = next;
  5713. }
  5714. if (next) {
  5715. next.prev = prev;
  5716. }
  5717. else {
  5718. this._clipsTail = prev;
  5719. }
  5720. clip.next = clip.prev = clip.animation = null;
  5721. };
  5722. Animation.prototype.removeAnimator = function (animator) {
  5723. var clip = animator.getClip();
  5724. if (clip) {
  5725. this.removeClip(clip);
  5726. }
  5727. animator.animation = null;
  5728. };
  5729. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  5730. var time = new Date().getTime() - this._pausedTime;
  5731. var delta = time - this._time;
  5732. var clip = this._clipsHead;
  5733. while (clip) {
  5734. var nextClip = clip.next;
  5735. var finished = clip.step(time, delta);
  5736. if (finished) {
  5737. clip.ondestroy && clip.ondestroy();
  5738. this.removeClip(clip);
  5739. clip = nextClip;
  5740. }
  5741. else {
  5742. clip = nextClip;
  5743. }
  5744. }
  5745. this._time = time;
  5746. if (!notTriggerFrameAndStageUpdate) {
  5747. this.onframe(delta);
  5748. this.trigger('frame', delta);
  5749. this.stage.update && this.stage.update();
  5750. }
  5751. };
  5752. Animation.prototype._startLoop = function () {
  5753. var self = this;
  5754. this._running = true;
  5755. function step() {
  5756. if (self._running) {
  5757. requestAnimationFrame$1(step);
  5758. !self._paused && self.update();
  5759. }
  5760. }
  5761. requestAnimationFrame$1(step);
  5762. };
  5763. Animation.prototype.start = function () {
  5764. if (this._running) {
  5765. return;
  5766. }
  5767. this._time = new Date().getTime();
  5768. this._pausedTime = 0;
  5769. this._startLoop();
  5770. };
  5771. Animation.prototype.stop = function () {
  5772. this._running = false;
  5773. };
  5774. Animation.prototype.pause = function () {
  5775. if (!this._paused) {
  5776. this._pauseStart = new Date().getTime();
  5777. this._paused = true;
  5778. }
  5779. };
  5780. Animation.prototype.resume = function () {
  5781. if (this._paused) {
  5782. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  5783. this._paused = false;
  5784. }
  5785. };
  5786. Animation.prototype.clear = function () {
  5787. var clip = this._clipsHead;
  5788. while (clip) {
  5789. var nextClip = clip.next;
  5790. clip.prev = clip.next = clip.animation = null;
  5791. clip = nextClip;
  5792. }
  5793. this._clipsHead = this._clipsTail = null;
  5794. };
  5795. Animation.prototype.isFinished = function () {
  5796. return this._clipsHead == null;
  5797. };
  5798. Animation.prototype.animate = function (target, options) {
  5799. options = options || {};
  5800. this.start();
  5801. var animator = new Animator(target, options.loop);
  5802. this.addAnimator(animator);
  5803. return animator;
  5804. };
  5805. return Animation;
  5806. }(Eventful));
  5807. var TOUCH_CLICK_DELAY = 300;
  5808. var globalEventSupported = env.domSupported;
  5809. var localNativeListenerNames = (function () {
  5810. var mouseHandlerNames = [
  5811. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5812. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5813. ];
  5814. var touchHandlerNames = [
  5815. 'touchstart', 'touchend', 'touchmove'
  5816. ];
  5817. var pointerEventNameMap = {
  5818. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5819. };
  5820. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5821. var nm = name.replace('mouse', 'pointer');
  5822. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5823. });
  5824. return {
  5825. mouse: mouseHandlerNames,
  5826. touch: touchHandlerNames,
  5827. pointer: pointerHandlerNames
  5828. };
  5829. })();
  5830. var globalNativeListenerNames = {
  5831. mouse: ['mousemove', 'mouseup'],
  5832. pointer: ['pointermove', 'pointerup']
  5833. };
  5834. var wheelEventSupported = false;
  5835. function isPointerFromTouch(event) {
  5836. var pointerType = event.pointerType;
  5837. return pointerType === 'pen' || pointerType === 'touch';
  5838. }
  5839. function setTouchTimer(scope) {
  5840. scope.touching = true;
  5841. if (scope.touchTimer != null) {
  5842. clearTimeout(scope.touchTimer);
  5843. scope.touchTimer = null;
  5844. }
  5845. scope.touchTimer = setTimeout(function () {
  5846. scope.touching = false;
  5847. scope.touchTimer = null;
  5848. }, 700);
  5849. }
  5850. function markTouch(event) {
  5851. event && (event.zrByTouch = true);
  5852. }
  5853. function normalizeGlobalEvent(instance, event) {
  5854. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5855. }
  5856. function isLocalEl(instance, el) {
  5857. var elTmp = el;
  5858. var isLocal = false;
  5859. while (elTmp && elTmp.nodeType !== 9
  5860. && !(isLocal = elTmp.domBelongToZr
  5861. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5862. elTmp = elTmp.parentNode;
  5863. }
  5864. return isLocal;
  5865. }
  5866. var FakeGlobalEvent = (function () {
  5867. function FakeGlobalEvent(instance, event) {
  5868. this.stopPropagation = noop;
  5869. this.stopImmediatePropagation = noop;
  5870. this.preventDefault = noop;
  5871. this.type = event.type;
  5872. this.target = this.currentTarget = instance.dom;
  5873. this.pointerType = event.pointerType;
  5874. this.clientX = event.clientX;
  5875. this.clientY = event.clientY;
  5876. }
  5877. return FakeGlobalEvent;
  5878. }());
  5879. var localDOMHandlers = {
  5880. mousedown: function (event) {
  5881. event = normalizeEvent(this.dom, event);
  5882. this.__mayPointerCapture = [event.zrX, event.zrY];
  5883. this.trigger('mousedown', event);
  5884. },
  5885. mousemove: function (event) {
  5886. event = normalizeEvent(this.dom, event);
  5887. var downPoint = this.__mayPointerCapture;
  5888. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5889. this.__togglePointerCapture(true);
  5890. }
  5891. this.trigger('mousemove', event);
  5892. },
  5893. mouseup: function (event) {
  5894. event = normalizeEvent(this.dom, event);
  5895. this.__togglePointerCapture(false);
  5896. this.trigger('mouseup', event);
  5897. },
  5898. mouseout: function (event) {
  5899. event = normalizeEvent(this.dom, event);
  5900. var element = event.toElement || event.relatedTarget;
  5901. if (!isLocalEl(this, element)) {
  5902. if (this.__pointerCapturing) {
  5903. event.zrEventControl = 'no_globalout';
  5904. }
  5905. this.trigger('mouseout', event);
  5906. }
  5907. },
  5908. wheel: function (event) {
  5909. wheelEventSupported = true;
  5910. event = normalizeEvent(this.dom, event);
  5911. this.trigger('mousewheel', event);
  5912. },
  5913. mousewheel: function (event) {
  5914. if (wheelEventSupported) {
  5915. return;
  5916. }
  5917. event = normalizeEvent(this.dom, event);
  5918. this.trigger('mousewheel', event);
  5919. },
  5920. touchstart: function (event) {
  5921. event = normalizeEvent(this.dom, event);
  5922. markTouch(event);
  5923. this.__lastTouchMoment = new Date();
  5924. this.handler.processGesture(event, 'start');
  5925. localDOMHandlers.mousemove.call(this, event);
  5926. localDOMHandlers.mousedown.call(this, event);
  5927. },
  5928. touchmove: function (event) {
  5929. event = normalizeEvent(this.dom, event);
  5930. markTouch(event);
  5931. this.handler.processGesture(event, 'change');
  5932. localDOMHandlers.mousemove.call(this, event);
  5933. },
  5934. touchend: function (event) {
  5935. event = normalizeEvent(this.dom, event);
  5936. markTouch(event);
  5937. this.handler.processGesture(event, 'end');
  5938. localDOMHandlers.mouseup.call(this, event);
  5939. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5940. localDOMHandlers.click.call(this, event);
  5941. }
  5942. },
  5943. pointerdown: function (event) {
  5944. localDOMHandlers.mousedown.call(this, event);
  5945. },
  5946. pointermove: function (event) {
  5947. if (!isPointerFromTouch(event)) {
  5948. localDOMHandlers.mousemove.call(this, event);
  5949. }
  5950. },
  5951. pointerup: function (event) {
  5952. localDOMHandlers.mouseup.call(this, event);
  5953. },
  5954. pointerout: function (event) {
  5955. if (!isPointerFromTouch(event)) {
  5956. localDOMHandlers.mouseout.call(this, event);
  5957. }
  5958. }
  5959. };
  5960. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5961. localDOMHandlers[name] = function (event) {
  5962. event = normalizeEvent(this.dom, event);
  5963. this.trigger(name, event);
  5964. };
  5965. });
  5966. var globalDOMHandlers = {
  5967. pointermove: function (event) {
  5968. if (!isPointerFromTouch(event)) {
  5969. globalDOMHandlers.mousemove.call(this, event);
  5970. }
  5971. },
  5972. pointerup: function (event) {
  5973. globalDOMHandlers.mouseup.call(this, event);
  5974. },
  5975. mousemove: function (event) {
  5976. this.trigger('mousemove', event);
  5977. },
  5978. mouseup: function (event) {
  5979. var pointerCaptureReleasing = this.__pointerCapturing;
  5980. this.__togglePointerCapture(false);
  5981. this.trigger('mouseup', event);
  5982. if (pointerCaptureReleasing) {
  5983. event.zrEventControl = 'only_globalout';
  5984. this.trigger('mouseout', event);
  5985. }
  5986. }
  5987. };
  5988. function mountLocalDOMEventListeners(instance, scope) {
  5989. var domHandlers = scope.domHandlers;
  5990. if (env.pointerEventsSupported) {
  5991. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5992. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5993. domHandlers[nativeEventName].call(instance, event);
  5994. });
  5995. });
  5996. }
  5997. else {
  5998. if (env.touchEventsSupported) {
  5999. each(localNativeListenerNames.touch, function (nativeEventName) {
  6000. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  6001. domHandlers[nativeEventName].call(instance, event);
  6002. setTouchTimer(scope);
  6003. });
  6004. });
  6005. }
  6006. each(localNativeListenerNames.mouse, function (nativeEventName) {
  6007. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  6008. event = getNativeEvent(event);
  6009. if (!scope.touching) {
  6010. domHandlers[nativeEventName].call(instance, event);
  6011. }
  6012. });
  6013. });
  6014. }
  6015. }
  6016. function mountGlobalDOMEventListeners(instance, scope) {
  6017. if (env.pointerEventsSupported) {
  6018. each(globalNativeListenerNames.pointer, mount);
  6019. }
  6020. else if (!env.touchEventsSupported) {
  6021. each(globalNativeListenerNames.mouse, mount);
  6022. }
  6023. function mount(nativeEventName) {
  6024. function nativeEventListener(event) {
  6025. event = getNativeEvent(event);
  6026. if (!isLocalEl(instance, event.target)) {
  6027. event = normalizeGlobalEvent(instance, event);
  6028. scope.domHandlers[nativeEventName].call(instance, event);
  6029. }
  6030. }
  6031. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  6032. }
  6033. }
  6034. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  6035. scope.mounted[nativeEventName] = listener;
  6036. scope.listenerOpts[nativeEventName] = opt;
  6037. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  6038. }
  6039. function unmountDOMEventListeners(scope) {
  6040. var mounted = scope.mounted;
  6041. for (var nativeEventName in mounted) {
  6042. if (mounted.hasOwnProperty(nativeEventName)) {
  6043. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  6044. }
  6045. }
  6046. scope.mounted = {};
  6047. }
  6048. var DOMHandlerScope = (function () {
  6049. function DOMHandlerScope(domTarget, domHandlers) {
  6050. this.mounted = {};
  6051. this.listenerOpts = {};
  6052. this.touching = false;
  6053. this.domTarget = domTarget;
  6054. this.domHandlers = domHandlers;
  6055. }
  6056. return DOMHandlerScope;
  6057. }());
  6058. var HandlerDomProxy = (function (_super) {
  6059. __extends(HandlerDomProxy, _super);
  6060. function HandlerDomProxy(dom, painterRoot) {
  6061. var _this = _super.call(this) || this;
  6062. _this.__pointerCapturing = false;
  6063. _this.dom = dom;
  6064. _this.painterRoot = painterRoot;
  6065. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  6066. if (globalEventSupported) {
  6067. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  6068. }
  6069. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  6070. return _this;
  6071. }
  6072. HandlerDomProxy.prototype.dispose = function () {
  6073. unmountDOMEventListeners(this._localHandlerScope);
  6074. if (globalEventSupported) {
  6075. unmountDOMEventListeners(this._globalHandlerScope);
  6076. }
  6077. };
  6078. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  6079. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  6080. };
  6081. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  6082. this.__mayPointerCapture = null;
  6083. if (globalEventSupported
  6084. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  6085. this.__pointerCapturing = isPointerCapturing;
  6086. var globalHandlerScope = this._globalHandlerScope;
  6087. isPointerCapturing
  6088. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  6089. : unmountDOMEventListeners(globalHandlerScope);
  6090. }
  6091. };
  6092. return HandlerDomProxy;
  6093. }(Eventful));
  6094. var Group = (function (_super) {
  6095. __extends(Group, _super);
  6096. function Group(opts) {
  6097. var _this = _super.call(this) || this;
  6098. _this.isGroup = true;
  6099. _this._children = [];
  6100. _this.attr(opts);
  6101. return _this;
  6102. }
  6103. Group.prototype.childrenRef = function () {
  6104. return this._children;
  6105. };
  6106. Group.prototype.children = function () {
  6107. return this._children.slice();
  6108. };
  6109. Group.prototype.childAt = function (idx) {
  6110. return this._children[idx];
  6111. };
  6112. Group.prototype.childOfName = function (name) {
  6113. var children = this._children;
  6114. for (var i = 0; i < children.length; i++) {
  6115. if (children[i].name === name) {
  6116. return children[i];
  6117. }
  6118. }
  6119. };
  6120. Group.prototype.childCount = function () {
  6121. return this._children.length;
  6122. };
  6123. Group.prototype.add = function (child) {
  6124. if (child) {
  6125. if (child !== this && child.parent !== this) {
  6126. this._children.push(child);
  6127. this._doAdd(child);
  6128. }
  6129. if (child.__hostTarget) {
  6130. throw 'This elemenet has been used as an attachment';
  6131. }
  6132. }
  6133. return this;
  6134. };
  6135. Group.prototype.addBefore = function (child, nextSibling) {
  6136. if (child && child !== this && child.parent !== this
  6137. && nextSibling && nextSibling.parent === this) {
  6138. var children = this._children;
  6139. var idx = children.indexOf(nextSibling);
  6140. if (idx >= 0) {
  6141. children.splice(idx, 0, child);
  6142. this._doAdd(child);
  6143. }
  6144. }
  6145. return this;
  6146. };
  6147. Group.prototype.replaceAt = function (child, index) {
  6148. var children = this._children;
  6149. var old = children[index];
  6150. if (child && child !== this && child.parent !== this && child !== old) {
  6151. children[index] = child;
  6152. old.parent = null;
  6153. var zr = this.__zr;
  6154. if (zr) {
  6155. old.removeSelfFromZr(zr);
  6156. }
  6157. this._doAdd(child);
  6158. }
  6159. return this;
  6160. };
  6161. Group.prototype._doAdd = function (child) {
  6162. if (child.parent) {
  6163. child.parent.remove(child);
  6164. }
  6165. child.parent = this;
  6166. var zr = this.__zr;
  6167. if (zr && zr !== child.__zr) {
  6168. child.addSelfToZr(zr);
  6169. }
  6170. zr && zr.refresh();
  6171. };
  6172. Group.prototype.remove = function (child) {
  6173. var zr = this.__zr;
  6174. var children = this._children;
  6175. var idx = indexOf(children, child);
  6176. if (idx < 0) {
  6177. return this;
  6178. }
  6179. children.splice(idx, 1);
  6180. child.parent = null;
  6181. if (zr) {
  6182. child.removeSelfFromZr(zr);
  6183. }
  6184. zr && zr.refresh();
  6185. return this;
  6186. };
  6187. Group.prototype.removeAll = function () {
  6188. var children = this._children;
  6189. var zr = this.__zr;
  6190. for (var i = 0; i < children.length; i++) {
  6191. var child = children[i];
  6192. if (zr) {
  6193. child.removeSelfFromZr(zr);
  6194. }
  6195. child.parent = null;
  6196. }
  6197. children.length = 0;
  6198. return this;
  6199. };
  6200. Group.prototype.eachChild = function (cb, context) {
  6201. var children = this._children;
  6202. for (var i = 0; i < children.length; i++) {
  6203. var child = children[i];
  6204. cb.call(context, child, i);
  6205. }
  6206. return this;
  6207. };
  6208. Group.prototype.traverse = function (cb, context) {
  6209. for (var i = 0; i < this._children.length; i++) {
  6210. var child = this._children[i];
  6211. var stopped = cb.call(context, child);
  6212. if (child.isGroup && !stopped) {
  6213. child.traverse(cb, context);
  6214. }
  6215. }
  6216. return this;
  6217. };
  6218. Group.prototype.addSelfToZr = function (zr) {
  6219. _super.prototype.addSelfToZr.call(this, zr);
  6220. for (var i = 0; i < this._children.length; i++) {
  6221. var child = this._children[i];
  6222. child.addSelfToZr(zr);
  6223. }
  6224. };
  6225. Group.prototype.removeSelfFromZr = function (zr) {
  6226. _super.prototype.removeSelfFromZr.call(this, zr);
  6227. for (var i = 0; i < this._children.length; i++) {
  6228. var child = this._children[i];
  6229. child.removeSelfFromZr(zr);
  6230. }
  6231. };
  6232. Group.prototype.getBoundingRect = function (includeChildren) {
  6233. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6234. var children = includeChildren || this._children;
  6235. var tmpMat = [];
  6236. var rect = null;
  6237. for (var i = 0; i < children.length; i++) {
  6238. var child = children[i];
  6239. if (child.ignore || child.invisible) {
  6240. continue;
  6241. }
  6242. var childRect = child.getBoundingRect();
  6243. var transform = child.getLocalTransform(tmpMat);
  6244. if (transform) {
  6245. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6246. rect = rect || tmpRect.clone();
  6247. rect.union(tmpRect);
  6248. }
  6249. else {
  6250. rect = rect || childRect.clone();
  6251. rect.union(childRect);
  6252. }
  6253. }
  6254. return rect || tmpRect;
  6255. };
  6256. return Group;
  6257. }(Element));
  6258. Group.prototype.type = 'group';
  6259. /*!
  6260. * ZRender, a high performance 2d drawing library.
  6261. *
  6262. * Copyright (c) 2013, Baidu Inc.
  6263. * All rights reserved.
  6264. *
  6265. * LICENSE
  6266. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6267. */
  6268. var useVML = !env.canvasSupported;
  6269. var painterCtors = {};
  6270. var instances = {};
  6271. function delInstance(id) {
  6272. delete instances[id];
  6273. }
  6274. function isDarkMode(backgroundColor) {
  6275. if (!backgroundColor) {
  6276. return false;
  6277. }
  6278. if (typeof backgroundColor === 'string') {
  6279. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6280. }
  6281. else if (backgroundColor.colorStops) {
  6282. var colorStops = backgroundColor.colorStops;
  6283. var totalLum = 0;
  6284. var len = colorStops.length;
  6285. for (var i = 0; i < len; i++) {
  6286. totalLum += lum(colorStops[i].color, 1);
  6287. }
  6288. totalLum /= len;
  6289. return totalLum < DARK_MODE_THRESHOLD;
  6290. }
  6291. return false;
  6292. }
  6293. var ZRender = (function () {
  6294. function ZRender(id, dom, opts) {
  6295. var _this = this;
  6296. this._sleepAfterStill = 10;
  6297. this._stillFrameAccum = 0;
  6298. this._needsRefresh = true;
  6299. this._needsRefreshHover = true;
  6300. this._darkMode = false;
  6301. opts = opts || {};
  6302. this.dom = dom;
  6303. this.id = id;
  6304. var storage = new Storage();
  6305. var rendererType = opts.renderer || 'canvas';
  6306. if (useVML) {
  6307. throw new Error('IE8 support has been dropped since 5.0');
  6308. }
  6309. if (!painterCtors[rendererType]) {
  6310. rendererType = keys(painterCtors)[0];
  6311. }
  6312. if (!painterCtors[rendererType]) {
  6313. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  6314. }
  6315. opts.useDirtyRect = opts.useDirtyRect == null
  6316. ? false
  6317. : opts.useDirtyRect;
  6318. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  6319. this.storage = storage;
  6320. this.painter = painter;
  6321. var handerProxy = (!env.node && !env.worker)
  6322. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  6323. : null;
  6324. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  6325. this.animation = new Animation({
  6326. stage: {
  6327. update: function () { return _this._flush(true); }
  6328. }
  6329. });
  6330. this.animation.start();
  6331. }
  6332. ZRender.prototype.add = function (el) {
  6333. if (!el) {
  6334. return;
  6335. }
  6336. this.storage.addRoot(el);
  6337. el.addSelfToZr(this);
  6338. this.refresh();
  6339. };
  6340. ZRender.prototype.remove = function (el) {
  6341. if (!el) {
  6342. return;
  6343. }
  6344. this.storage.delRoot(el);
  6345. el.removeSelfFromZr(this);
  6346. this.refresh();
  6347. };
  6348. ZRender.prototype.configLayer = function (zLevel, config) {
  6349. if (this.painter.configLayer) {
  6350. this.painter.configLayer(zLevel, config);
  6351. }
  6352. this.refresh();
  6353. };
  6354. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  6355. if (this.painter.setBackgroundColor) {
  6356. this.painter.setBackgroundColor(backgroundColor);
  6357. }
  6358. this.refresh();
  6359. this._backgroundColor = backgroundColor;
  6360. this._darkMode = isDarkMode(backgroundColor);
  6361. };
  6362. ZRender.prototype.getBackgroundColor = function () {
  6363. return this._backgroundColor;
  6364. };
  6365. ZRender.prototype.setDarkMode = function (darkMode) {
  6366. this._darkMode = darkMode;
  6367. };
  6368. ZRender.prototype.isDarkMode = function () {
  6369. return this._darkMode;
  6370. };
  6371. ZRender.prototype.refreshImmediately = function (fromInside) {
  6372. if (!fromInside) {
  6373. this.animation.update(true);
  6374. }
  6375. this._needsRefresh = false;
  6376. this.painter.refresh();
  6377. this._needsRefresh = false;
  6378. };
  6379. ZRender.prototype.refresh = function () {
  6380. this._needsRefresh = true;
  6381. this.animation.start();
  6382. };
  6383. ZRender.prototype.flush = function () {
  6384. this._flush(false);
  6385. };
  6386. ZRender.prototype._flush = function (fromInside) {
  6387. var triggerRendered;
  6388. var start = new Date().getTime();
  6389. if (this._needsRefresh) {
  6390. triggerRendered = true;
  6391. this.refreshImmediately(fromInside);
  6392. }
  6393. if (this._needsRefreshHover) {
  6394. triggerRendered = true;
  6395. this.refreshHoverImmediately();
  6396. }
  6397. var end = new Date().getTime();
  6398. if (triggerRendered) {
  6399. this._stillFrameAccum = 0;
  6400. this.trigger('rendered', {
  6401. elapsedTime: end - start
  6402. });
  6403. }
  6404. else if (this._sleepAfterStill > 0) {
  6405. this._stillFrameAccum++;
  6406. if (this._stillFrameAccum > this._sleepAfterStill) {
  6407. this.animation.stop();
  6408. }
  6409. }
  6410. };
  6411. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  6412. this._sleepAfterStill = stillFramesCount;
  6413. };
  6414. ZRender.prototype.wakeUp = function () {
  6415. this.animation.start();
  6416. this._stillFrameAccum = 0;
  6417. };
  6418. ZRender.prototype.addHover = function (el) {
  6419. };
  6420. ZRender.prototype.removeHover = function (el) {
  6421. };
  6422. ZRender.prototype.clearHover = function () {
  6423. };
  6424. ZRender.prototype.refreshHover = function () {
  6425. this._needsRefreshHover = true;
  6426. };
  6427. ZRender.prototype.refreshHoverImmediately = function () {
  6428. this._needsRefreshHover = false;
  6429. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  6430. this.painter.refreshHover();
  6431. }
  6432. };
  6433. ZRender.prototype.resize = function (opts) {
  6434. opts = opts || {};
  6435. this.painter.resize(opts.width, opts.height);
  6436. this.handler.resize();
  6437. };
  6438. ZRender.prototype.clearAnimation = function () {
  6439. this.animation.clear();
  6440. };
  6441. ZRender.prototype.getWidth = function () {
  6442. return this.painter.getWidth();
  6443. };
  6444. ZRender.prototype.getHeight = function () {
  6445. return this.painter.getHeight();
  6446. };
  6447. ZRender.prototype.pathToImage = function (e, dpr) {
  6448. if (this.painter.pathToImage) {
  6449. return this.painter.pathToImage(e, dpr);
  6450. }
  6451. };
  6452. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  6453. this.handler.setCursorStyle(cursorStyle);
  6454. };
  6455. ZRender.prototype.findHover = function (x, y) {
  6456. return this.handler.findHover(x, y);
  6457. };
  6458. ZRender.prototype.on = function (eventName, eventHandler, context) {
  6459. this.handler.on(eventName, eventHandler, context);
  6460. return this;
  6461. };
  6462. ZRender.prototype.off = function (eventName, eventHandler) {
  6463. this.handler.off(eventName, eventHandler);
  6464. };
  6465. ZRender.prototype.trigger = function (eventName, event) {
  6466. this.handler.trigger(eventName, event);
  6467. };
  6468. ZRender.prototype.clear = function () {
  6469. var roots = this.storage.getRoots();
  6470. for (var i = 0; i < roots.length; i++) {
  6471. if (roots[i] instanceof Group) {
  6472. roots[i].removeSelfFromZr(this);
  6473. }
  6474. }
  6475. this.storage.delAllRoots();
  6476. this.painter.clear();
  6477. };
  6478. ZRender.prototype.dispose = function () {
  6479. this.animation.stop();
  6480. this.clear();
  6481. this.storage.dispose();
  6482. this.painter.dispose();
  6483. this.handler.dispose();
  6484. this.animation =
  6485. this.storage =
  6486. this.painter =
  6487. this.handler = null;
  6488. delInstance(this.id);
  6489. };
  6490. return ZRender;
  6491. }());
  6492. function init(dom, opts) {
  6493. var zr = new ZRender(guid(), dom, opts);
  6494. instances[zr.id] = zr;
  6495. return zr;
  6496. }
  6497. function dispose(zr) {
  6498. zr.dispose();
  6499. }
  6500. function disposeAll() {
  6501. for (var key in instances) {
  6502. if (instances.hasOwnProperty(key)) {
  6503. instances[key].dispose();
  6504. }
  6505. }
  6506. instances = {};
  6507. }
  6508. function getInstance(id) {
  6509. return instances[id];
  6510. }
  6511. function registerPainter(name, Ctor) {
  6512. painterCtors[name] = Ctor;
  6513. }
  6514. var version = '5.0.4';
  6515. var zrender = /*#__PURE__*/Object.freeze({
  6516. __proto__: null,
  6517. init: init,
  6518. dispose: dispose,
  6519. disposeAll: disposeAll,
  6520. getInstance: getInstance,
  6521. registerPainter: registerPainter,
  6522. version: version
  6523. });
  6524. var RADIAN_EPSILON = 1e-4;
  6525. function _trim(str) {
  6526. return str.replace(/^\s+|\s+$/g, '');
  6527. }
  6528. /**
  6529. * Linear mapping a value from domain to range
  6530. * @param val
  6531. * @param domain Domain extent domain[0] can be bigger than domain[1]
  6532. * @param range Range extent range[0] can be bigger than range[1]
  6533. * @param clamp Default to be false
  6534. */
  6535. function linearMap(val, domain, range, clamp) {
  6536. var subDomain = domain[1] - domain[0];
  6537. var subRange = range[1] - range[0];
  6538. if (subDomain === 0) {
  6539. return subRange === 0 ? range[0] : (range[0] + range[1]) / 2;
  6540. } // Avoid accuracy problem in edge, such as
  6541. // 146.39 - 62.83 === 83.55999999999999.
  6542. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  6543. // It is a little verbose for efficiency considering this method
  6544. // is a hotspot.
  6545. if (clamp) {
  6546. if (subDomain > 0) {
  6547. if (val <= domain[0]) {
  6548. return range[0];
  6549. } else if (val >= domain[1]) {
  6550. return range[1];
  6551. }
  6552. } else {
  6553. if (val >= domain[0]) {
  6554. return range[0];
  6555. } else if (val <= domain[1]) {
  6556. return range[1];
  6557. }
  6558. }
  6559. } else {
  6560. if (val === domain[0]) {
  6561. return range[0];
  6562. }
  6563. if (val === domain[1]) {
  6564. return range[1];
  6565. }
  6566. }
  6567. return (val - domain[0]) / subDomain * subRange + range[0];
  6568. }
  6569. /**
  6570. * Convert a percent string to absolute number.
  6571. * Returns NaN if percent is not a valid string or number
  6572. */
  6573. function parsePercent$1(percent, all) {
  6574. switch (percent) {
  6575. case 'center':
  6576. case 'middle':
  6577. percent = '50%';
  6578. break;
  6579. case 'left':
  6580. case 'top':
  6581. percent = '0%';
  6582. break;
  6583. case 'right':
  6584. case 'bottom':
  6585. percent = '100%';
  6586. break;
  6587. }
  6588. if (typeof percent === 'string') {
  6589. if (_trim(percent).match(/%$/)) {
  6590. return parseFloat(percent) / 100 * all;
  6591. }
  6592. return parseFloat(percent);
  6593. }
  6594. return percent == null ? NaN : +percent;
  6595. }
  6596. function round(x, precision, returnStr) {
  6597. if (precision == null) {
  6598. precision = 10;
  6599. } // Avoid range error
  6600. precision = Math.min(Math.max(0, precision), 20);
  6601. x = (+x).toFixed(precision);
  6602. return returnStr ? x : +x;
  6603. }
  6604. /**
  6605. * Inplacd asc sort arr.
  6606. * The input arr will be modified.
  6607. */
  6608. function asc(arr) {
  6609. arr.sort(function (a, b) {
  6610. return a - b;
  6611. });
  6612. return arr;
  6613. }
  6614. /**
  6615. * Get precision
  6616. */
  6617. function getPrecision(val) {
  6618. val = +val;
  6619. if (isNaN(val)) {
  6620. return 0;
  6621. } // It is much faster than methods converting number to string as follows
  6622. // let tmp = val.toString();
  6623. // return tmp.length - 1 - tmp.indexOf('.');
  6624. // especially when precision is low
  6625. var e = 1;
  6626. var count = 0;
  6627. while (Math.round(val * e) / e !== val) {
  6628. e *= 10;
  6629. count++;
  6630. }
  6631. return count;
  6632. }
  6633. /**
  6634. * Get precision with slow but safe method
  6635. */
  6636. function getPrecisionSafe(val) {
  6637. var str = val.toString(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  6638. var eIndex = str.indexOf('e');
  6639. if (eIndex > 0) {
  6640. var precision = +str.slice(eIndex + 1);
  6641. return precision < 0 ? -precision : 0;
  6642. } else {
  6643. var dotIndex = str.indexOf('.');
  6644. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  6645. }
  6646. }
  6647. /**
  6648. * Minimal dicernible data precisioin according to a single pixel.
  6649. */
  6650. function getPixelPrecision(dataExtent, pixelExtent) {
  6651. var log = Math.log;
  6652. var LN10 = Math.LN10;
  6653. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  6654. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  6655. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  6656. return !isFinite(precision) ? 20 : precision;
  6657. }
  6658. /**
  6659. * Get a data of given precision, assuring the sum of percentages
  6660. * in valueList is 1.
  6661. * The largest remainer method is used.
  6662. * https://en.wikipedia.org/wiki/Largest_remainder_method
  6663. *
  6664. * @param valueList a list of all data
  6665. * @param idx index of the data to be processed in valueList
  6666. * @param precision integer number showing digits of precision
  6667. * @return percent ranging from 0 to 100
  6668. */
  6669. function getPercentWithPrecision(valueList, idx, precision) {
  6670. if (!valueList[idx]) {
  6671. return 0;
  6672. }
  6673. var sum = reduce(valueList, function (acc, val) {
  6674. return acc + (isNaN(val) ? 0 : val);
  6675. }, 0);
  6676. if (sum === 0) {
  6677. return 0;
  6678. }
  6679. var digits = Math.pow(10, precision);
  6680. var votesPerQuota = map(valueList, function (val) {
  6681. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  6682. });
  6683. var targetSeats = digits * 100;
  6684. var seats = map(votesPerQuota, function (votes) {
  6685. // Assign automatic seats.
  6686. return Math.floor(votes);
  6687. });
  6688. var currentSum = reduce(seats, function (acc, val) {
  6689. return acc + val;
  6690. }, 0);
  6691. var remainder = map(votesPerQuota, function (votes, idx) {
  6692. return votes - seats[idx];
  6693. }); // Has remainding votes.
  6694. while (currentSum < targetSeats) {
  6695. // Find next largest remainder.
  6696. var max = Number.NEGATIVE_INFINITY;
  6697. var maxId = null;
  6698. for (var i = 0, len = remainder.length; i < len; ++i) {
  6699. if (remainder[i] > max) {
  6700. max = remainder[i];
  6701. maxId = i;
  6702. }
  6703. } // Add a vote to max remainder.
  6704. ++seats[maxId];
  6705. remainder[maxId] = 0;
  6706. ++currentSum;
  6707. }
  6708. return seats[idx] / digits;
  6709. } // Number.MAX_SAFE_INTEGER, ie do not support.
  6710. var MAX_SAFE_INTEGER = 9007199254740991;
  6711. /**
  6712. * To 0 - 2 * PI, considering negative radian.
  6713. */
  6714. function remRadian(radian) {
  6715. var pi2 = Math.PI * 2;
  6716. return (radian % pi2 + pi2) % pi2;
  6717. }
  6718. /**
  6719. * @param {type} radian
  6720. * @return {boolean}
  6721. */
  6722. function isRadianAroundZero(val) {
  6723. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  6724. } // eslint-disable-next-line
  6725. 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
  6726. /**
  6727. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  6728. * These values can be accepted:
  6729. * + An instance of Date, represent a time in its own time zone.
  6730. * + Or string in a subset of ISO 8601, only including:
  6731. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  6732. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  6733. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  6734. * all of which will be treated as local time if time zone is not specified
  6735. * (see <https://momentjs.com/>).
  6736. * + Or other string format, including (all of which will be treated as loacal time):
  6737. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  6738. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  6739. * + a timestamp, which represent a time in UTC.
  6740. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  6741. */
  6742. function parseDate(value) {
  6743. if (value instanceof Date) {
  6744. return value;
  6745. } else if (typeof value === 'string') {
  6746. // Different browsers parse date in different way, so we parse it manually.
  6747. // Some other issues:
  6748. // new Date('1970-01-01') is UTC,
  6749. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  6750. // See issue #3623
  6751. var match = TIME_REG.exec(value);
  6752. if (!match) {
  6753. // return Invalid Date.
  6754. return new Date(NaN);
  6755. } // Use local time when no timezone offset specifed.
  6756. if (!match[8]) {
  6757. // match[n] can only be string or undefined.
  6758. // But take care of '12' + 1 => '121'.
  6759. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
  6760. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  6761. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  6762. // For example, system timezone is set as "Time Zone: America/Toronto",
  6763. // then these code will get different result:
  6764. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  6765. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  6766. // So we should not use `new Date`, but use `Date.UTC`.
  6767. else {
  6768. var hour = +match[4] || 0;
  6769. if (match[8].toUpperCase() !== 'Z') {
  6770. hour -= +match[8].slice(0, 3);
  6771. }
  6772. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
  6773. }
  6774. } else if (value == null) {
  6775. return new Date(NaN);
  6776. }
  6777. return new Date(Math.round(value));
  6778. }
  6779. /**
  6780. * Quantity of a number. e.g. 0.1, 1, 10, 100
  6781. *
  6782. * @param val
  6783. * @return
  6784. */
  6785. function quantity(val) {
  6786. return Math.pow(10, quantityExponent(val));
  6787. }
  6788. /**
  6789. * Exponent of the quantity of a number
  6790. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  6791. *
  6792. * @param val non-negative value
  6793. * @return
  6794. */
  6795. function quantityExponent(val) {
  6796. if (val === 0) {
  6797. return 0;
  6798. }
  6799. var exp = Math.floor(Math.log(val) / Math.LN10);
  6800. /**
  6801. * exp is expected to be the rounded-down result of the base-10 log of val.
  6802. * But due to the precision loss with Math.log(val), we need to restore it
  6803. * using 10^exp to make sure we can get val back from exp. #11249
  6804. */
  6805. if (val / Math.pow(10, exp) >= 10) {
  6806. exp++;
  6807. }
  6808. return exp;
  6809. }
  6810. /**
  6811. * find a “nice” number approximately equal to x. Round the number if round = true,
  6812. * take ceiling if round = false. The primary observation is that the “nicest”
  6813. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  6814. *
  6815. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  6816. *
  6817. * @param val Non-negative value.
  6818. * @param round
  6819. * @return Niced number
  6820. */
  6821. function nice(val, round) {
  6822. var exponent = quantityExponent(val);
  6823. var exp10 = Math.pow(10, exponent);
  6824. var f = val / exp10; // 1 <= f < 10
  6825. var nf;
  6826. if (round) {
  6827. if (f < 1.5) {
  6828. nf = 1;
  6829. } else if (f < 2.5) {
  6830. nf = 2;
  6831. } else if (f < 4) {
  6832. nf = 3;
  6833. } else if (f < 7) {
  6834. nf = 5;
  6835. } else {
  6836. nf = 10;
  6837. }
  6838. } else {
  6839. if (f < 1) {
  6840. nf = 1;
  6841. } else if (f < 2) {
  6842. nf = 2;
  6843. } else if (f < 3) {
  6844. nf = 3;
  6845. } else if (f < 5) {
  6846. nf = 5;
  6847. } else {
  6848. nf = 10;
  6849. }
  6850. }
  6851. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  6852. // 20 is the uppper bound of toFixed.
  6853. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  6854. }
  6855. /**
  6856. * This code was copied from "d3.js"
  6857. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  6858. * See the license statement at the head of this file.
  6859. * @param ascArr
  6860. */
  6861. function quantile(ascArr, p) {
  6862. var H = (ascArr.length - 1) * p + 1;
  6863. var h = Math.floor(H);
  6864. var v = +ascArr[h - 1];
  6865. var e = H - h;
  6866. return e ? v + e * (ascArr[h] - v) : v;
  6867. }
  6868. /**
  6869. * Order intervals asc, and split them when overlap.
  6870. * expect(numberUtil.reformIntervals([
  6871. * {interval: [18, 62], close: [1, 1]},
  6872. * {interval: [-Infinity, -70], close: [0, 0]},
  6873. * {interval: [-70, -26], close: [1, 1]},
  6874. * {interval: [-26, 18], close: [1, 1]},
  6875. * {interval: [62, 150], close: [1, 1]},
  6876. * {interval: [106, 150], close: [1, 1]},
  6877. * {interval: [150, Infinity], close: [0, 0]}
  6878. * ])).toEqual([
  6879. * {interval: [-Infinity, -70], close: [0, 0]},
  6880. * {interval: [-70, -26], close: [1, 1]},
  6881. * {interval: [-26, 18], close: [0, 1]},
  6882. * {interval: [18, 62], close: [0, 1]},
  6883. * {interval: [62, 150], close: [0, 1]},
  6884. * {interval: [150, Infinity], close: [0, 0]}
  6885. * ]);
  6886. * @param list, where `close` mean open or close
  6887. * of the interval, and Infinity can be used.
  6888. * @return The origin list, which has been reformed.
  6889. */
  6890. function reformIntervals(list) {
  6891. list.sort(function (a, b) {
  6892. return littleThan(a, b, 0) ? -1 : 1;
  6893. });
  6894. var curr = -Infinity;
  6895. var currClose = 1;
  6896. for (var i = 0; i < list.length;) {
  6897. var interval = list[i].interval;
  6898. var close_1 = list[i].close;
  6899. for (var lg = 0; lg < 2; lg++) {
  6900. if (interval[lg] <= curr) {
  6901. interval[lg] = curr;
  6902. close_1[lg] = !lg ? 1 - currClose : 1;
  6903. }
  6904. curr = interval[lg];
  6905. currClose = close_1[lg];
  6906. }
  6907. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  6908. list.splice(i, 1);
  6909. } else {
  6910. i++;
  6911. }
  6912. }
  6913. return list;
  6914. function littleThan(a, b, lg) {
  6915. 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));
  6916. }
  6917. }
  6918. /**
  6919. * [Numberic is defined as]:
  6920. * `parseFloat(val) == val`
  6921. * For example:
  6922. * numeric:
  6923. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  6924. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  6925. * not-numeric:
  6926. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  6927. * empty string, string with only white-spaces or line-terminal (see es spec),
  6928. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  6929. * non-string, ...
  6930. *
  6931. * @test See full test cases in `test/ut/spec/util/number.js`.
  6932. * @return Must be a typeof number. If not numeric, return NaN.
  6933. */
  6934. function numericToNumber(val) {
  6935. var valFloat = parseFloat(val);
  6936. return valFloat == val // eslint-disable-line eqeqeq
  6937. && (valFloat !== 0 || typeof val !== 'string' || val.indexOf('x') <= 0) // For case ' 0x0 '.
  6938. ? valFloat : NaN;
  6939. }
  6940. /**
  6941. * Definition of "numeric": see `numericToNumber`.
  6942. */
  6943. function isNumeric(val) {
  6944. return !isNaN(numericToNumber(val));
  6945. }
  6946. /**
  6947. * Use random base to prevent users hard code depending on
  6948. * this auto generated marker id.
  6949. * @return An positive integer.
  6950. */
  6951. function getRandomIdBase() {
  6952. return Math.round(Math.random() * 9);
  6953. }
  6954. /**
  6955. * Get the greatest common dividor
  6956. *
  6957. * @param {number} a one number
  6958. * @param {number} b the other number
  6959. */
  6960. function getGreatestCommonDividor(a, b) {
  6961. if (b === 0) {
  6962. return a;
  6963. }
  6964. return getGreatestCommonDividor(b, a % b);
  6965. }
  6966. /**
  6967. * Get the least common multiple
  6968. *
  6969. * @param {number} a one number
  6970. * @param {number} b the other number
  6971. */
  6972. function getLeastCommonMultiple(a, b) {
  6973. if (a == null) {
  6974. return b;
  6975. }
  6976. if (b == null) {
  6977. return a;
  6978. }
  6979. return a * b / getGreatestCommonDividor(a, b);
  6980. }
  6981. var ECHARTS_PREFIX = '[ECharts] ';
  6982. var storedLogs = {};
  6983. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  6984. && console.warn && console.log;
  6985. function warn(str) {
  6986. if (hasConsole) {
  6987. console.warn(ECHARTS_PREFIX + str);
  6988. }
  6989. }
  6990. function error(str) {
  6991. if (hasConsole) {
  6992. console.error(ECHARTS_PREFIX + str);
  6993. }
  6994. }
  6995. function deprecateLog(str) {
  6996. if ("development" !== 'production') {
  6997. if (storedLogs[str]) {
  6998. // Not display duplicate message.
  6999. return;
  7000. }
  7001. if (hasConsole) {
  7002. storedLogs[str] = true;
  7003. console.warn(ECHARTS_PREFIX + 'DEPRECATED: ' + str);
  7004. }
  7005. }
  7006. }
  7007. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7008. if ("development" !== 'production') {
  7009. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7010. }
  7011. }
  7012. function consoleLog() {
  7013. var args = [];
  7014. for (var _i = 0; _i < arguments.length; _i++) {
  7015. args[_i] = arguments[_i];
  7016. }
  7017. if ("development" !== 'production') {
  7018. /* eslint-disable no-console */
  7019. if (typeof console !== 'undefined' && console.log) {
  7020. console.log.apply(console, args);
  7021. }
  7022. /* eslint-enable no-console */
  7023. }
  7024. }
  7025. /**
  7026. * If in __DEV__ environment, get console printable message for users hint.
  7027. * Parameters are separated by ' '.
  7028. * @usuage
  7029. * makePrintable('This is an error on', someVar, someObj);
  7030. *
  7031. * @param hintInfo anything about the current execution context to hint users.
  7032. * @throws Error
  7033. */
  7034. function makePrintable() {
  7035. var hintInfo = [];
  7036. for (var _i = 0; _i < arguments.length; _i++) {
  7037. hintInfo[_i] = arguments[_i];
  7038. }
  7039. var msg = '';
  7040. if ("development" !== 'production') {
  7041. // Fuzzy stringify for print.
  7042. // This code only exist in dev environment.
  7043. var makePrintableStringIfPossible_1 = function (val) {
  7044. 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;
  7045. };
  7046. msg = map(hintInfo, function (arg) {
  7047. if (isString(arg)) {
  7048. // Print without quotation mark for some statement.
  7049. return arg;
  7050. } else {
  7051. var printableStr = makePrintableStringIfPossible_1(arg);
  7052. if (printableStr != null) {
  7053. return printableStr;
  7054. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7055. try {
  7056. return JSON.stringify(arg, function (n, val) {
  7057. var printableStr = makePrintableStringIfPossible_1(val);
  7058. return printableStr == null ? val : printableStr;
  7059. }); // In most cases the info object is small, so do not line break.
  7060. } catch (err) {
  7061. return '?';
  7062. }
  7063. } else {
  7064. return '?';
  7065. }
  7066. }
  7067. }).join(' ');
  7068. }
  7069. return msg;
  7070. }
  7071. /**
  7072. * @throws Error
  7073. */
  7074. function throwError(msg) {
  7075. throw new Error(msg);
  7076. }
  7077. /**
  7078. * Make the name displayable. But we should
  7079. * make sure it is not duplicated with user
  7080. * specified name, so use '\0';
  7081. */
  7082. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7083. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7084. /**
  7085. * If value is not array, then translate it to array.
  7086. * @param {*} value
  7087. * @return {Array} [value] or value
  7088. */
  7089. function normalizeToArray(value) {
  7090. return value instanceof Array ? value : value == null ? [] : [value];
  7091. }
  7092. /**
  7093. * Sync default option between normal and emphasis like `position` and `show`
  7094. * In case some one will write code like
  7095. * label: {
  7096. * show: false,
  7097. * position: 'outside',
  7098. * fontSize: 18
  7099. * },
  7100. * emphasis: {
  7101. * label: { show: true }
  7102. * }
  7103. */
  7104. function defaultEmphasis(opt, key, subOpts) {
  7105. // Caution: performance sensitive.
  7106. if (opt) {
  7107. opt[key] = opt[key] || {};
  7108. opt.emphasis = opt.emphasis || {};
  7109. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7110. for (var i = 0, len = subOpts.length; i < len; i++) {
  7111. var subOptName = subOpts[i];
  7112. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7113. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7114. }
  7115. }
  7116. }
  7117. }
  7118. 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([
  7119. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7120. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7121. // // FIXME: deprecated, check and remove it.
  7122. // 'textStyle'
  7123. // ]);
  7124. /**
  7125. * The method do not ensure performance.
  7126. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7127. * This helper method retieves value from data.
  7128. */
  7129. function getDataItemValue(dataItem) {
  7130. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7131. }
  7132. /**
  7133. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7134. * This helper method determine if dataItem has extra option besides value
  7135. */
  7136. function isDataItemOption(dataItem) {
  7137. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7138. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7139. }
  7140. /**
  7141. * Mapping to existings for merge.
  7142. *
  7143. * Mode "normalMege":
  7144. * The mapping result (merge result) will keep the order of the existing
  7145. * component, rather than the order of new option. Because we should ensure
  7146. * some specified index reference (like xAxisIndex) keep work.
  7147. * And in most cases, "merge option" is used to update partial option but not
  7148. * be expected to change the order.
  7149. *
  7150. * Mode "replaceMege":
  7151. * (1) Only the id mapped components will be merged.
  7152. * (2) Other existing components (except internal compoonets) will be removed.
  7153. * (3) Other new options will be used to create new component.
  7154. * (4) The index of the existing compoents will not be modified.
  7155. * That means their might be "hole" after the removal.
  7156. * The new components are created first at those available index.
  7157. *
  7158. * Mode "replaceAll":
  7159. * This mode try to support that reproduce an echarts instance from another
  7160. * echarts instance (via `getOption`) in some simple cases.
  7161. * In this senario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7162. * which ensures the compoennt index referring (like `xAxisIndex: ?`) corrent. That is,
  7163. * the "hole" in `newCmptOptions` will also be kept.
  7164. * On the contrary, other modes try best to eliminate holes.
  7165. * PENDING: This is an experimental mode yet.
  7166. *
  7167. * @return See the comment of <MappingResult>.
  7168. */
  7169. function mappingToExists(existings, newCmptOptions, mode) {
  7170. var isNormalMergeMode = mode === 'normalMerge';
  7171. var isReplaceMergeMode = mode === 'replaceMerge';
  7172. var isReplaceAllMode = mode === 'replaceAll';
  7173. existings = existings || [];
  7174. newCmptOptions = (newCmptOptions || []).slice();
  7175. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7176. each(newCmptOptions, function (cmptOption, index) {
  7177. if (!isObject(cmptOption)) {
  7178. newCmptOptions[index] = null;
  7179. return;
  7180. }
  7181. if ("development" !== 'production') {
  7182. // There is some legacy case that name is set as `false`.
  7183. // But should work normally rather than throw error.
  7184. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7185. warnInvalidateIdOrName(cmptOption.id);
  7186. }
  7187. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7188. warnInvalidateIdOrName(cmptOption.name);
  7189. }
  7190. }
  7191. });
  7192. var result = prepareResult(existings, existingIdIdxMap, mode);
  7193. if (isNormalMergeMode || isReplaceMergeMode) {
  7194. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7195. }
  7196. if (isNormalMergeMode) {
  7197. mappingByName(result, newCmptOptions);
  7198. }
  7199. if (isNormalMergeMode || isReplaceMergeMode) {
  7200. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7201. } else if (isReplaceAllMode) {
  7202. mappingInReplaceAllMode(result, newCmptOptions);
  7203. }
  7204. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7205. // forEach will ommit those items and result in incorrect result.
  7206. return result;
  7207. }
  7208. function prepareResult(existings, existingIdIdxMap, mode) {
  7209. var result = [];
  7210. if (mode === 'replaceAll') {
  7211. return result;
  7212. } // Do not use native `map` to in case that the array `existings`
  7213. // contains elided items, which will be ommited.
  7214. for (var index = 0; index < existings.length; index++) {
  7215. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7216. if (existing && existing.id != null) {
  7217. existingIdIdxMap.set(existing.id, index);
  7218. } // For non-internal-componnets:
  7219. // Mode "normalMerge": all existings kept.
  7220. // Mode "replaceMerge": all existing removed unless mapped by id.
  7221. // For internal-components:
  7222. // go with "replaceMerge" approach in both mode.
  7223. result.push({
  7224. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7225. newOption: null,
  7226. keyInfo: null,
  7227. brandNew: null
  7228. });
  7229. }
  7230. return result;
  7231. }
  7232. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7233. // Mapping by id if specified.
  7234. each(newCmptOptions, function (cmptOption, index) {
  7235. if (!cmptOption || cmptOption.id == null) {
  7236. return;
  7237. }
  7238. var optionId = makeComparableKey(cmptOption.id);
  7239. var existingIdx = existingIdIdxMap.get(optionId);
  7240. if (existingIdx != null) {
  7241. var resultItem = result[existingIdx];
  7242. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7243. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7244. // the existings rather than creating new component model.
  7245. resultItem.existing = existings[existingIdx];
  7246. newCmptOptions[index] = null;
  7247. }
  7248. });
  7249. }
  7250. function mappingByName(result, newCmptOptions) {
  7251. // Mapping by name if specified.
  7252. each(newCmptOptions, function (cmptOption, index) {
  7253. if (!cmptOption || cmptOption.name == null) {
  7254. return;
  7255. }
  7256. for (var i = 0; i < result.length; i++) {
  7257. var existing = result[i].existing;
  7258. if (!result[i].newOption // Consider name: two map to one.
  7259. // Can not match when both ids existing but different.
  7260. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  7261. result[i].newOption = cmptOption;
  7262. newCmptOptions[index] = null;
  7263. return;
  7264. }
  7265. }
  7266. });
  7267. }
  7268. function mappingByIndex(result, newCmptOptions, brandNew) {
  7269. each(newCmptOptions, function (cmptOption) {
  7270. if (!cmptOption) {
  7271. return;
  7272. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  7273. var resultItem;
  7274. var nextIdx = 0;
  7275. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  7276. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  7277. // after mapping performed, model will always be assigned with an id if user not given.
  7278. // After that all models have id.
  7279. // (2) If new option has id, it can only set to a hole or append to the last. It should
  7280. // not be merged to the existings with different id. Because id should not be overwritten.
  7281. // (3) Name can be overwritten, because axis use name as 'show label text'.
  7282. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  7283. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  7284. nextIdx++;
  7285. }
  7286. if (resultItem) {
  7287. resultItem.newOption = cmptOption;
  7288. resultItem.brandNew = brandNew;
  7289. } else {
  7290. result.push({
  7291. newOption: cmptOption,
  7292. brandNew: brandNew,
  7293. existing: null,
  7294. keyInfo: null
  7295. });
  7296. }
  7297. nextIdx++;
  7298. });
  7299. }
  7300. function mappingInReplaceAllMode(result, newCmptOptions) {
  7301. each(newCmptOptions, function (cmptOption) {
  7302. // The feature "reproduce" requires "hole" will also reproduced
  7303. // in case that compoennt index referring are broken.
  7304. result.push({
  7305. newOption: cmptOption,
  7306. brandNew: true,
  7307. existing: null,
  7308. keyInfo: null
  7309. });
  7310. });
  7311. }
  7312. /**
  7313. * Make id and name for mapping result (result of mappingToExists)
  7314. * into `keyInfo` field.
  7315. */
  7316. function makeIdAndName(mapResult) {
  7317. // We use this id to hash component models and view instances
  7318. // in echarts. id can be specified by user, or auto generated.
  7319. // The id generation rule ensures new view instance are able
  7320. // to mapped to old instance when setOption are called in
  7321. // no-merge mode. So we generate model id by name and plus
  7322. // type in view id.
  7323. // name can be duplicated among components, which is convenient
  7324. // to specify multi components (like series) by one name.
  7325. // Ensure that each id is distinct.
  7326. var idMap = createHashMap();
  7327. each(mapResult, function (item) {
  7328. var existing = item.existing;
  7329. existing && idMap.set(existing.id, item);
  7330. });
  7331. each(mapResult, function (item) {
  7332. var opt = item.newOption; // Force ensure id not duplicated.
  7333. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  7334. opt && opt.id != null && idMap.set(opt.id, item);
  7335. !item.keyInfo && (item.keyInfo = {});
  7336. }); // Make name and id.
  7337. each(mapResult, function (item, index) {
  7338. var existing = item.existing;
  7339. var opt = item.newOption;
  7340. var keyInfo = item.keyInfo;
  7341. if (!isObject(opt)) {
  7342. return;
  7343. } // name can be overwitten. Consider case: axis.name = '20km'.
  7344. // But id generated by name will not be changed, which affect
  7345. // only in that case: setOption with 'not merge mode' and view
  7346. // instance will be recreated, which can be accepted.
  7347. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid diffferent series has the same name,
  7348. // because name may be used like in color pallet.
  7349. : DUMMY_COMPONENT_NAME_PREFIX + index;
  7350. if (existing) {
  7351. keyInfo.id = makeComparableKey(existing.id);
  7352. } else if (opt.id != null) {
  7353. keyInfo.id = makeComparableKey(opt.id);
  7354. } else {
  7355. // Consider this situatoin:
  7356. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  7357. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  7358. // Series with the same name between optionA and optionB
  7359. // should be mapped.
  7360. var idNum = 0;
  7361. do {
  7362. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  7363. } while (idMap.get(keyInfo.id));
  7364. }
  7365. idMap.set(keyInfo.id, item);
  7366. });
  7367. }
  7368. function keyExistAndEqual(attr, obj1, obj2) {
  7369. var key1 = convertOptionIdName(obj1[attr], null);
  7370. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  7371. return key1 != null && key2 != null && key1 === key2;
  7372. }
  7373. /**
  7374. * @return return null if not exist.
  7375. */
  7376. function makeComparableKey(val) {
  7377. if ("development" !== 'production') {
  7378. if (val == null) {
  7379. throw new Error();
  7380. }
  7381. }
  7382. return convertOptionIdName(val, '');
  7383. }
  7384. function convertOptionIdName(idOrName, defaultValue) {
  7385. if (idOrName == null) {
  7386. return defaultValue;
  7387. }
  7388. var type = typeof idOrName;
  7389. return type === 'string' ? idOrName : type === 'number' || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  7390. }
  7391. function warnInvalidateIdOrName(idOrName) {
  7392. if ("development" !== 'production') {
  7393. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  7394. }
  7395. }
  7396. function isValidIdOrName(idOrName) {
  7397. return isStringSafe(idOrName) || isNumeric(idOrName);
  7398. }
  7399. function isNameSpecified(componentModel) {
  7400. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  7401. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  7402. }
  7403. /**
  7404. * @public
  7405. * @param {Object} cmptOption
  7406. * @return {boolean}
  7407. */
  7408. function isComponentIdInternal(cmptOption) {
  7409. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  7410. }
  7411. function makeInternalComponentId(idSuffix) {
  7412. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  7413. }
  7414. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  7415. // Set mainType and complete subType.
  7416. each(mappingResult, function (item) {
  7417. var newOption = item.newOption;
  7418. if (isObject(newOption)) {
  7419. item.keyInfo.mainType = mainType;
  7420. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  7421. }
  7422. });
  7423. }
  7424. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  7425. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  7426. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  7427. return subType;
  7428. }
  7429. /**
  7430. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  7431. * each of which can be Array or primary type.
  7432. * @return dataIndex If not found, return undefined/null.
  7433. */
  7434. function queryDataIndex(data, payload) {
  7435. if (payload.dataIndexInside != null) {
  7436. return payload.dataIndexInside;
  7437. } else if (payload.dataIndex != null) {
  7438. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  7439. return data.indexOfRawIndex(value);
  7440. }) : data.indexOfRawIndex(payload.dataIndex);
  7441. } else if (payload.name != null) {
  7442. return isArray(payload.name) ? map(payload.name, function (value) {
  7443. return data.indexOfName(value);
  7444. }) : data.indexOfName(payload.name);
  7445. }
  7446. }
  7447. /**
  7448. * Enable property storage to any host object.
  7449. * Notice: Serialization is not supported.
  7450. *
  7451. * For example:
  7452. * let inner = zrUitl.makeInner();
  7453. *
  7454. * function some1(hostObj) {
  7455. * inner(hostObj).someProperty = 1212;
  7456. * ...
  7457. * }
  7458. * function some2() {
  7459. * let fields = inner(this);
  7460. * fields.someProperty1 = 1212;
  7461. * fields.someProperty2 = 'xx';
  7462. * ...
  7463. * }
  7464. *
  7465. * @return {Function}
  7466. */
  7467. function makeInner() {
  7468. var key = '__ec_inner_' + innerUniqueIndex++;
  7469. return function (hostObj) {
  7470. return hostObj[key] || (hostObj[key] = {});
  7471. };
  7472. }
  7473. var innerUniqueIndex = getRandomIdBase();
  7474. /**
  7475. * The same behavior as `component.getReferringComponents`.
  7476. */
  7477. function parseFinder(ecModel, finderInput, opt) {
  7478. var finder;
  7479. if (isString(finderInput)) {
  7480. var obj = {};
  7481. obj[finderInput + 'Index'] = 0;
  7482. finder = obj;
  7483. } else {
  7484. finder = finderInput;
  7485. }
  7486. var queryOptionMap = createHashMap();
  7487. var result = {};
  7488. var mainTypeSpecified = false;
  7489. each(finder, function (value, key) {
  7490. // Exclude 'dataIndex' and other illgal keys.
  7491. if (key === 'dataIndex' || key === 'dataIndexInside') {
  7492. result[key] = value;
  7493. return;
  7494. }
  7495. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  7496. var mainType = parsedKey[1];
  7497. var queryType = (parsedKey[2] || '').toLowerCase();
  7498. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  7499. return;
  7500. }
  7501. mainTypeSpecified = mainTypeSpecified || !!mainType;
  7502. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  7503. queryOption[queryType] = value;
  7504. });
  7505. var defaultMainType = opt ? opt.defaultMainType : null;
  7506. if (!mainTypeSpecified && defaultMainType) {
  7507. queryOptionMap.set(defaultMainType, {});
  7508. }
  7509. queryOptionMap.each(function (queryOption, mainType) {
  7510. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  7511. useDefault: defaultMainType === mainType,
  7512. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  7513. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  7514. });
  7515. result[mainType + 'Models'] = queryResult.models;
  7516. result[mainType + 'Model'] = queryResult.models[0];
  7517. });
  7518. return result;
  7519. }
  7520. var SINGLE_REFERRING = {
  7521. useDefault: true,
  7522. enableAll: false,
  7523. enableNone: false
  7524. };
  7525. var MULTIPLE_REFERRING = {
  7526. useDefault: false,
  7527. enableAll: true,
  7528. enableNone: true
  7529. };
  7530. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  7531. opt = opt || SINGLE_REFERRING;
  7532. var indexOption = userOption.index;
  7533. var idOption = userOption.id;
  7534. var nameOption = userOption.name;
  7535. var result = {
  7536. models: null,
  7537. specified: indexOption != null || idOption != null || nameOption != null
  7538. };
  7539. if (!result.specified) {
  7540. // Use the first as default if `useDefault`.
  7541. var firstCmpt = void 0;
  7542. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  7543. return result;
  7544. }
  7545. if (indexOption === 'none' || indexOption === false) {
  7546. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  7547. result.models = [];
  7548. return result;
  7549. } // `queryComponents` will return all components if
  7550. // both all of index/id/name are null/undefined.
  7551. if (indexOption === 'all') {
  7552. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  7553. indexOption = idOption = nameOption = null;
  7554. }
  7555. result.models = ecModel.queryComponents({
  7556. mainType: mainType,
  7557. index: indexOption,
  7558. id: idOption,
  7559. name: nameOption
  7560. });
  7561. return result;
  7562. }
  7563. function setAttribute(dom, key, value) {
  7564. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  7565. }
  7566. function getAttribute(dom, key) {
  7567. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  7568. }
  7569. function getTooltipRenderMode(renderModeOption) {
  7570. if (renderModeOption === 'auto') {
  7571. // Using html when `document` exists, use richText otherwise
  7572. return env.domSupported ? 'html' : 'richText';
  7573. } else {
  7574. return renderModeOption || 'html';
  7575. }
  7576. }
  7577. /**
  7578. * Interpolate raw values of a series with percent
  7579. *
  7580. * @param data data
  7581. * @param labelModel label model of the text element
  7582. * @param sourceValue start value. May be null/undefined when init.
  7583. * @param targetValue end value
  7584. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  7585. * @return interpolated values
  7586. * If `sourceValue` and `targetValue` are `number`, return `number`.
  7587. * If `sourceValue` and `targetValue` are `string`, return `string`.
  7588. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  7589. * Other cases do not supported.
  7590. */
  7591. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  7592. var isAutoPrecision = precision == null || precision === 'auto';
  7593. if (targetValue == null) {
  7594. return targetValue;
  7595. }
  7596. if (typeof targetValue === 'number') {
  7597. var value = interpolateNumber(sourceValue || 0, targetValue, percent);
  7598. return round(value, isAutoPrecision ? Math.max(getPrecisionSafe(sourceValue || 0), getPrecisionSafe(targetValue)) : precision);
  7599. } else if (typeof targetValue === 'string') {
  7600. return percent < 1 ? sourceValue : targetValue;
  7601. } else {
  7602. var interpolated = [];
  7603. var leftArr = sourceValue;
  7604. var rightArr = targetValue;
  7605. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  7606. for (var i = 0; i < length_1; ++i) {
  7607. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  7608. if (info.type === 'ordinal') {
  7609. // In init, there is no `sourceValue`, but should better not to get undefined result.
  7610. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  7611. } else {
  7612. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  7613. var rightVal = rightArr[i];
  7614. var value = interpolateNumber(leftVal, rightVal, percent);
  7615. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecisionSafe(leftVal), getPrecisionSafe(rightVal)) : precision);
  7616. }
  7617. }
  7618. return interpolated;
  7619. }
  7620. }
  7621. var TYPE_DELIMITER = '.';
  7622. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  7623. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  7624. /**
  7625. * Notice, parseClassType('') should returns {main: '', sub: ''}
  7626. * @public
  7627. */
  7628. function parseClassType(componentType) {
  7629. var ret = {
  7630. main: '',
  7631. sub: ''
  7632. };
  7633. if (componentType) {
  7634. var typeArr = componentType.split(TYPE_DELIMITER);
  7635. ret.main = typeArr[0] || '';
  7636. ret.sub = typeArr[1] || '';
  7637. }
  7638. return ret;
  7639. }
  7640. /**
  7641. * @public
  7642. */
  7643. function checkClassType(componentType) {
  7644. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  7645. }
  7646. function isExtendedClass(clz) {
  7647. return !!(clz && clz[IS_EXTENDED_CLASS]);
  7648. }
  7649. /**
  7650. * Implements `ExtendableConstructor` for `rootClz`.
  7651. *
  7652. * @usage
  7653. * ```ts
  7654. * class Xxx {}
  7655. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  7656. * enableClassExtend(Xxx as XxxConstructor);
  7657. * ```
  7658. */
  7659. function enableClassExtend(rootClz, mandatoryMethods) {
  7660. rootClz.$constructor = rootClz; // FIXME: not necessary?
  7661. rootClz.extend = function (proto) {
  7662. if ("development" !== 'production') {
  7663. each(mandatoryMethods, function (method) {
  7664. if (!proto[method]) {
  7665. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  7666. }
  7667. });
  7668. }
  7669. var superClass = this; // For backward compat, we both support ts class inheritance and this
  7670. // "extend" approach.
  7671. // The constructor should keep the same behavior as ts class inheritance:
  7672. // If this constructor/$constructor is not declared, auto invoke the super
  7673. // constructor.
  7674. // If this constructor/$constructor is declared, it is responsible for
  7675. // calling the super constructor.
  7676. function ExtendedClass() {
  7677. var args = [];
  7678. for (var _i = 0; _i < arguments.length; _i++) {
  7679. args[_i] = arguments[_i];
  7680. }
  7681. if (!proto.$constructor) {
  7682. if (!isESClass(superClass)) {
  7683. // Will throw error if superClass is an es6 native class.
  7684. superClass.apply(this, arguments);
  7685. } else {
  7686. var ins = createObject( // @ts-ignore
  7687. ExtendedClass.prototype, new (superClass.bind.apply(superClass, __spreadArrays([void 0], args)))());
  7688. return ins;
  7689. }
  7690. } else {
  7691. proto.$constructor.apply(this, arguments);
  7692. }
  7693. }
  7694. ExtendedClass[IS_EXTENDED_CLASS] = true;
  7695. extend(ExtendedClass.prototype, proto);
  7696. ExtendedClass.extend = this.extend;
  7697. ExtendedClass.superCall = superCall;
  7698. ExtendedClass.superApply = superApply;
  7699. inherits(ExtendedClass, this);
  7700. ExtendedClass.superClass = superClass;
  7701. return ExtendedClass;
  7702. };
  7703. }
  7704. function isESClass(fn) {
  7705. return typeof fn === 'function' && /^class\s/.test(Function.prototype.toString.call(fn));
  7706. }
  7707. /**
  7708. * A work around to both support ts extend and this extend mechanism.
  7709. * on sub-class.
  7710. * @usage
  7711. * ```ts
  7712. * class Component { ... }
  7713. * classUtil.enableClassExtend(Component);
  7714. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  7715. *
  7716. * class Series extends Component { ... }
  7717. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  7718. * Component.markExtend(Series);
  7719. * ```
  7720. */
  7721. function mountExtend(SubClz, SupperClz) {
  7722. SubClz.extend = SupperClz.extend;
  7723. } // A random offset.
  7724. var classBase = Math.round(Math.random() * 10);
  7725. /**
  7726. * Implements `CheckableConstructor` for `target`.
  7727. * Can not use instanceof, consider different scope by
  7728. * cross domain or es module import in ec extensions.
  7729. * Mount a method "isInstance()" to Clz.
  7730. *
  7731. * @usage
  7732. * ```ts
  7733. * class Xxx {}
  7734. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  7735. * enableClassCheck(Xxx as XxxConstructor)
  7736. * ```
  7737. */
  7738. function enableClassCheck(target) {
  7739. var classAttr = ['__\0is_clz', classBase++].join('_');
  7740. target.prototype[classAttr] = true;
  7741. if ("development" !== 'production') {
  7742. assert(!target.isInstance, 'The method "is" can not be defined.');
  7743. }
  7744. target.isInstance = function (obj) {
  7745. return !!(obj && obj[classAttr]);
  7746. };
  7747. } // superCall should have class info, which can not be fetch from 'this'.
  7748. // Consider this case:
  7749. // class A has method f,
  7750. // class B inherits class A, overrides method f, f call superApply('f'),
  7751. // class C inherits class B, do not overrides method f,
  7752. // then when method of class C is called, dead loop occured.
  7753. function superCall(context, methodName) {
  7754. var args = [];
  7755. for (var _i = 2; _i < arguments.length; _i++) {
  7756. args[_i - 2] = arguments[_i];
  7757. }
  7758. return this.superClass.prototype[methodName].apply(context, args);
  7759. }
  7760. function superApply(context, methodName, args) {
  7761. return this.superClass.prototype[methodName].apply(context, args);
  7762. }
  7763. /**
  7764. * Implements `ClassManager` for `target`
  7765. *
  7766. * @usage
  7767. * ```ts
  7768. * class Xxx {}
  7769. * type XxxConstructor = typeof Xxx & ClassManager
  7770. * enableClassManagement(Xxx as XxxConstructor);
  7771. * ```
  7772. */
  7773. function enableClassManagement(target) {
  7774. /**
  7775. * Component model classes
  7776. * key: componentType,
  7777. * value:
  7778. * componentClass, when componentType is 'xxx'
  7779. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  7780. */
  7781. var storage = {};
  7782. target.registerClass = function (clz) {
  7783. // `type` should not be a "instance memeber".
  7784. // If using TS class, should better declared as `static type = 'series.pie'`.
  7785. // otherwise users have to mount `type` on prototype manually.
  7786. // For backward compat and enable instance visit type via `this.type`,
  7787. // we stil support fetch `type` from prototype.
  7788. var componentFullType = clz.type || clz.prototype.type;
  7789. if (componentFullType) {
  7790. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  7791. clz.prototype.type = componentFullType;
  7792. var componentTypeInfo = parseClassType(componentFullType);
  7793. if (!componentTypeInfo.sub) {
  7794. if ("development" !== 'production') {
  7795. if (storage[componentTypeInfo.main]) {
  7796. console.warn(componentTypeInfo.main + ' exists.');
  7797. }
  7798. }
  7799. storage[componentTypeInfo.main] = clz;
  7800. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  7801. var container = makeContainer(componentTypeInfo);
  7802. container[componentTypeInfo.sub] = clz;
  7803. }
  7804. }
  7805. return clz;
  7806. };
  7807. target.getClass = function (mainType, subType, throwWhenNotFound) {
  7808. var clz = storage[mainType];
  7809. if (clz && clz[IS_CONTAINER]) {
  7810. clz = subType ? clz[subType] : null;
  7811. }
  7812. if (throwWhenNotFound && !clz) {
  7813. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' not exists. Load it first.');
  7814. }
  7815. return clz;
  7816. };
  7817. target.getClassesByMainType = function (componentType) {
  7818. var componentTypeInfo = parseClassType(componentType);
  7819. var result = [];
  7820. var obj = storage[componentTypeInfo.main];
  7821. if (obj && obj[IS_CONTAINER]) {
  7822. each(obj, function (o, type) {
  7823. type !== IS_CONTAINER && result.push(o);
  7824. });
  7825. } else {
  7826. result.push(obj);
  7827. }
  7828. return result;
  7829. };
  7830. target.hasClass = function (componentType) {
  7831. // Just consider componentType.main.
  7832. var componentTypeInfo = parseClassType(componentType);
  7833. return !!storage[componentTypeInfo.main];
  7834. };
  7835. /**
  7836. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  7837. */
  7838. target.getAllClassMainTypes = function () {
  7839. var types = [];
  7840. each(storage, function (obj, type) {
  7841. types.push(type);
  7842. });
  7843. return types;
  7844. };
  7845. /**
  7846. * If a main type is container and has sub types
  7847. */
  7848. target.hasSubTypes = function (componentType) {
  7849. var componentTypeInfo = parseClassType(componentType);
  7850. var obj = storage[componentTypeInfo.main];
  7851. return obj && obj[IS_CONTAINER];
  7852. };
  7853. function makeContainer(componentTypeInfo) {
  7854. var container = storage[componentTypeInfo.main];
  7855. if (!container || !container[IS_CONTAINER]) {
  7856. container = storage[componentTypeInfo.main] = {};
  7857. container[IS_CONTAINER] = true;
  7858. }
  7859. return container;
  7860. }
  7861. } // /**
  7862. // * @param {string|Array.<string>} properties
  7863. // */
  7864. // export function setReadOnly(obj, properties) {
  7865. // FIXME It seems broken in IE8 simulation of IE11
  7866. // if (!zrUtil.isArray(properties)) {
  7867. // properties = properties != null ? [properties] : [];
  7868. // }
  7869. // zrUtil.each(properties, function (prop) {
  7870. // let value = obj[prop];
  7871. // Object.defineProperty
  7872. // && Object.defineProperty(obj, prop, {
  7873. // value: value, writable: false
  7874. // });
  7875. // zrUtil.isArray(obj[prop])
  7876. // && Object.freeze
  7877. // && Object.freeze(obj[prop]);
  7878. // });
  7879. // }
  7880. function makeStyleMapper(properties, ignoreParent) {
  7881. // Normalize
  7882. for (var i = 0; i < properties.length; i++) {
  7883. if (!properties[i][1]) {
  7884. properties[i][1] = properties[i][0];
  7885. }
  7886. }
  7887. ignoreParent = ignoreParent || false;
  7888. return function (model, excludes, includes) {
  7889. var style = {};
  7890. for (var i = 0; i < properties.length; i++) {
  7891. var propName = properties[i][1];
  7892. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  7893. continue;
  7894. }
  7895. var val = model.getShallow(propName, ignoreParent);
  7896. if (val != null) {
  7897. style[properties[i][0]] = val;
  7898. }
  7899. } // TODO Text or image?
  7900. return style;
  7901. };
  7902. }
  7903. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  7904. // So do not transfer decal directly.
  7905. ];
  7906. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  7907. var AreaStyleMixin =
  7908. /** @class */
  7909. function () {
  7910. function AreaStyleMixin() {}
  7911. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  7912. return getAreaStyle(this, excludes, includes);
  7913. };
  7914. return AreaStyleMixin;
  7915. }();
  7916. var globalImageCache = new LRU(50);
  7917. function findExistImage(newImageOrSrc) {
  7918. if (typeof newImageOrSrc === 'string') {
  7919. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  7920. return cachedImgObj && cachedImgObj.image;
  7921. }
  7922. else {
  7923. return newImageOrSrc;
  7924. }
  7925. }
  7926. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  7927. if (!newImageOrSrc) {
  7928. return image;
  7929. }
  7930. else if (typeof newImageOrSrc === 'string') {
  7931. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  7932. return image;
  7933. }
  7934. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  7935. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  7936. if (cachedImgObj) {
  7937. image = cachedImgObj.image;
  7938. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  7939. }
  7940. else {
  7941. image = new Image();
  7942. image.onload = image.onerror = imageOnLoad;
  7943. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  7944. image: image,
  7945. pending: [pendingWrap]
  7946. });
  7947. image.src = image.__zrImageSrc = newImageOrSrc;
  7948. }
  7949. return image;
  7950. }
  7951. else {
  7952. return newImageOrSrc;
  7953. }
  7954. }
  7955. function imageOnLoad() {
  7956. var cachedImgObj = this.__cachedImgObj;
  7957. this.onload = this.onerror = this.__cachedImgObj = null;
  7958. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  7959. var pendingWrap = cachedImgObj.pending[i];
  7960. var cb = pendingWrap.cb;
  7961. cb && cb(this, pendingWrap.cbPayload);
  7962. pendingWrap.hostEl.dirty();
  7963. }
  7964. cachedImgObj.pending.length = 0;
  7965. }
  7966. function isImageReady(image) {
  7967. return image && image.width && image.height;
  7968. }
  7969. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  7970. function truncateText(text, containerWidth, font, ellipsis, options) {
  7971. if (!containerWidth) {
  7972. return '';
  7973. }
  7974. var textLines = (text + '').split('\n');
  7975. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7976. for (var i = 0, len = textLines.length; i < len; i++) {
  7977. textLines[i] = truncateSingleLine(textLines[i], options);
  7978. }
  7979. return textLines.join('\n');
  7980. }
  7981. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7982. options = options || {};
  7983. var preparedOpts = extend({}, options);
  7984. preparedOpts.font = font;
  7985. ellipsis = retrieve2(ellipsis, '...');
  7986. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  7987. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  7988. preparedOpts.cnCharWidth = getWidth('国', font);
  7989. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  7990. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  7991. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  7992. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7993. contentWidth -= ascCharWidth;
  7994. }
  7995. var ellipsisWidth = getWidth(ellipsis, font);
  7996. if (ellipsisWidth > contentWidth) {
  7997. ellipsis = '';
  7998. ellipsisWidth = 0;
  7999. }
  8000. contentWidth = containerWidth - ellipsisWidth;
  8001. preparedOpts.ellipsis = ellipsis;
  8002. preparedOpts.ellipsisWidth = ellipsisWidth;
  8003. preparedOpts.contentWidth = contentWidth;
  8004. preparedOpts.containerWidth = containerWidth;
  8005. return preparedOpts;
  8006. }
  8007. function truncateSingleLine(textLine, options) {
  8008. var containerWidth = options.containerWidth;
  8009. var font = options.font;
  8010. var contentWidth = options.contentWidth;
  8011. if (!containerWidth) {
  8012. return '';
  8013. }
  8014. var lineWidth = getWidth(textLine, font);
  8015. if (lineWidth <= containerWidth) {
  8016. return textLine;
  8017. }
  8018. for (var j = 0;; j++) {
  8019. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8020. textLine += options.ellipsis;
  8021. break;
  8022. }
  8023. var subLength = j === 0
  8024. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8025. : lineWidth > 0
  8026. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8027. : 0;
  8028. textLine = textLine.substr(0, subLength);
  8029. lineWidth = getWidth(textLine, font);
  8030. }
  8031. if (textLine === '') {
  8032. textLine = options.placeholder;
  8033. }
  8034. return textLine;
  8035. }
  8036. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8037. var width = 0;
  8038. var i = 0;
  8039. for (var len = text.length; i < len && width < contentWidth; i++) {
  8040. var charCode = text.charCodeAt(i);
  8041. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8042. }
  8043. return i;
  8044. }
  8045. function parsePlainText(text, style) {
  8046. text != null && (text += '');
  8047. var overflow = style.overflow;
  8048. var padding = style.padding;
  8049. var font = style.font;
  8050. var truncate = overflow === 'truncate';
  8051. var calculatedLineHeight = getLineHeight(font);
  8052. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8053. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8054. var width = style.width;
  8055. var lines;
  8056. if (width != null && overflow === 'break' || overflow === 'breakAll') {
  8057. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8058. }
  8059. else {
  8060. lines = text ? text.split('\n') : [];
  8061. }
  8062. var contentHeight = lines.length * lineHeight;
  8063. var height = retrieve2(style.height, contentHeight);
  8064. if (contentHeight > height && truncateLineOverflow) {
  8065. var lineCount = Math.floor(height / lineHeight);
  8066. lines = lines.slice(0, lineCount);
  8067. }
  8068. var outerHeight = height;
  8069. var outerWidth = width;
  8070. if (padding) {
  8071. outerHeight += padding[0] + padding[2];
  8072. if (outerWidth != null) {
  8073. outerWidth += padding[1] + padding[3];
  8074. }
  8075. }
  8076. if (text && truncate && outerWidth != null) {
  8077. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8078. minChar: style.truncateMinChar,
  8079. placeholder: style.placeholder
  8080. });
  8081. for (var i = 0; i < lines.length; i++) {
  8082. lines[i] = truncateSingleLine(lines[i], options);
  8083. }
  8084. }
  8085. if (width == null) {
  8086. var maxWidth = 0;
  8087. for (var i = 0; i < lines.length; i++) {
  8088. maxWidth = Math.max(getWidth(lines[i], font), maxWidth);
  8089. }
  8090. width = maxWidth;
  8091. }
  8092. return {
  8093. lines: lines,
  8094. height: height,
  8095. outerHeight: outerHeight,
  8096. lineHeight: lineHeight,
  8097. calculatedLineHeight: calculatedLineHeight,
  8098. contentHeight: contentHeight,
  8099. width: width
  8100. };
  8101. }
  8102. var RichTextToken = (function () {
  8103. function RichTextToken() {
  8104. }
  8105. return RichTextToken;
  8106. }());
  8107. var RichTextLine = (function () {
  8108. function RichTextLine(tokens) {
  8109. this.tokens = [];
  8110. if (tokens) {
  8111. this.tokens = tokens;
  8112. }
  8113. }
  8114. return RichTextLine;
  8115. }());
  8116. var RichTextContentBlock = (function () {
  8117. function RichTextContentBlock() {
  8118. this.width = 0;
  8119. this.height = 0;
  8120. this.contentWidth = 0;
  8121. this.contentHeight = 0;
  8122. this.outerWidth = 0;
  8123. this.outerHeight = 0;
  8124. this.lines = [];
  8125. }
  8126. return RichTextContentBlock;
  8127. }());
  8128. function parseRichText(text, style) {
  8129. var contentBlock = new RichTextContentBlock();
  8130. text != null && (text += '');
  8131. if (!text) {
  8132. return contentBlock;
  8133. }
  8134. var topWidth = style.width;
  8135. var topHeight = style.height;
  8136. var overflow = style.overflow;
  8137. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8138. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8139. : null;
  8140. var lastIndex = STYLE_REG.lastIndex = 0;
  8141. var result;
  8142. while ((result = STYLE_REG.exec(text)) != null) {
  8143. var matchedIndex = result.index;
  8144. if (matchedIndex > lastIndex) {
  8145. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8146. }
  8147. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8148. lastIndex = STYLE_REG.lastIndex;
  8149. }
  8150. if (lastIndex < text.length) {
  8151. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8152. }
  8153. var pendingList = [];
  8154. var calculatedHeight = 0;
  8155. var calculatedWidth = 0;
  8156. var stlPadding = style.padding;
  8157. var truncate = overflow === 'truncate';
  8158. var truncateLine = style.lineOverflow === 'truncate';
  8159. function finishLine(line, lineWidth, lineHeight) {
  8160. line.width = lineWidth;
  8161. line.lineHeight = lineHeight;
  8162. calculatedHeight += lineHeight;
  8163. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8164. }
  8165. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8166. var line = contentBlock.lines[i];
  8167. var lineHeight = 0;
  8168. var lineWidth = 0;
  8169. for (var j = 0; j < line.tokens.length; j++) {
  8170. var token = line.tokens[j];
  8171. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8172. var textPadding = token.textPadding = tokenStyle.padding;
  8173. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8174. var font = token.font = tokenStyle.font || style.font;
  8175. token.contentHeight = getLineHeight(font);
  8176. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8177. token.innerHeight = tokenHeight;
  8178. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8179. token.height = tokenHeight;
  8180. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8181. token.align = tokenStyle && tokenStyle.align || style.align;
  8182. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8183. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8184. if (j > 0) {
  8185. line.tokens = line.tokens.slice(0, j);
  8186. finishLine(line, lineWidth, lineHeight);
  8187. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8188. }
  8189. else {
  8190. contentBlock.lines = contentBlock.lines.slice(0, i);
  8191. }
  8192. break outer;
  8193. }
  8194. var styleTokenWidth = tokenStyle.width;
  8195. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8196. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8197. token.percentWidth = styleTokenWidth;
  8198. pendingList.push(token);
  8199. token.contentWidth = getWidth(token.text, font);
  8200. }
  8201. else {
  8202. if (tokenWidthNotSpecified) {
  8203. var textBackgroundColor = tokenStyle.backgroundColor;
  8204. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8205. if (bgImg) {
  8206. bgImg = findExistImage(bgImg);
  8207. if (isImageReady(bgImg)) {
  8208. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8209. }
  8210. }
  8211. }
  8212. var remainTruncWidth = truncate && topWidth != null
  8213. ? topWidth - lineWidth : null;
  8214. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8215. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8216. token.text = '';
  8217. token.width = token.contentWidth = 0;
  8218. }
  8219. else {
  8220. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8221. token.width = token.contentWidth = getWidth(token.text, font);
  8222. }
  8223. }
  8224. else {
  8225. token.contentWidth = getWidth(token.text, font);
  8226. }
  8227. }
  8228. token.width += paddingH;
  8229. lineWidth += token.width;
  8230. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8231. }
  8232. finishLine(line, lineWidth, lineHeight);
  8233. }
  8234. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8235. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8236. contentBlock.contentHeight = calculatedHeight;
  8237. contentBlock.contentWidth = calculatedWidth;
  8238. if (stlPadding) {
  8239. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  8240. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  8241. }
  8242. for (var i = 0; i < pendingList.length; i++) {
  8243. var token = pendingList[i];
  8244. var percentWidth = token.percentWidth;
  8245. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  8246. }
  8247. return contentBlock;
  8248. }
  8249. function pushTokens(block, str, style, wrapInfo, styleName) {
  8250. var isEmptyStr = str === '';
  8251. var tokenStyle = styleName && style.rich[styleName] || {};
  8252. var lines = block.lines;
  8253. var font = tokenStyle.font || style.font;
  8254. var newLine = false;
  8255. var strLines;
  8256. var linesWidths;
  8257. if (wrapInfo) {
  8258. var tokenPadding = tokenStyle.padding;
  8259. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  8260. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  8261. var outerWidth_1 = parsePercent$2(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  8262. if (lines.length > 0) {
  8263. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  8264. strLines = str.split('\n');
  8265. newLine = true;
  8266. }
  8267. }
  8268. wrapInfo.accumWidth = outerWidth_1;
  8269. }
  8270. else {
  8271. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  8272. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  8273. linesWidths = res.linesWidths;
  8274. strLines = res.lines;
  8275. }
  8276. }
  8277. else {
  8278. strLines = str.split('\n');
  8279. }
  8280. for (var i = 0; i < strLines.length; i++) {
  8281. var text = strLines[i];
  8282. var token = new RichTextToken();
  8283. token.styleName = styleName;
  8284. token.text = text;
  8285. token.isLineHolder = !text && !isEmptyStr;
  8286. if (typeof tokenStyle.width === 'number') {
  8287. token.width = tokenStyle.width;
  8288. }
  8289. else {
  8290. token.width = linesWidths
  8291. ? linesWidths[i]
  8292. : getWidth(text, font);
  8293. }
  8294. if (!i && !newLine) {
  8295. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  8296. var tokensLen = tokens.length;
  8297. (tokensLen === 1 && tokens[0].isLineHolder)
  8298. ? (tokens[0] = token)
  8299. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  8300. }
  8301. else {
  8302. lines.push(new RichTextLine([token]));
  8303. }
  8304. }
  8305. }
  8306. function isLatin(ch) {
  8307. var code = ch.charCodeAt(0);
  8308. return code >= 0x21 && code <= 0xFF;
  8309. }
  8310. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  8311. obj[ch] = true;
  8312. return obj;
  8313. }, {});
  8314. function isWordBreakChar(ch) {
  8315. if (isLatin(ch)) {
  8316. if (breakCharMap[ch]) {
  8317. return true;
  8318. }
  8319. return false;
  8320. }
  8321. return true;
  8322. }
  8323. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  8324. var lines = [];
  8325. var linesWidths = [];
  8326. var line = '';
  8327. var currentWord = '';
  8328. var currentWordWidth = 0;
  8329. var accumWidth = 0;
  8330. for (var i = 0; i < text.length; i++) {
  8331. var ch = text.charAt(i);
  8332. if (ch === '\n') {
  8333. if (currentWord) {
  8334. line += currentWord;
  8335. accumWidth += currentWordWidth;
  8336. }
  8337. lines.push(line);
  8338. linesWidths.push(accumWidth);
  8339. line = '';
  8340. currentWord = '';
  8341. currentWordWidth = 0;
  8342. accumWidth = 0;
  8343. continue;
  8344. }
  8345. var chWidth = getWidth(ch, font);
  8346. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  8347. if (!lines.length
  8348. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  8349. : accumWidth + chWidth > lineWidth) {
  8350. if (!accumWidth) {
  8351. if (inWord) {
  8352. lines.push(currentWord);
  8353. linesWidths.push(currentWordWidth);
  8354. currentWord = ch;
  8355. currentWordWidth = chWidth;
  8356. }
  8357. else {
  8358. lines.push(ch);
  8359. linesWidths.push(chWidth);
  8360. }
  8361. }
  8362. else if (line || currentWord) {
  8363. if (inWord) {
  8364. if (!line) {
  8365. line = currentWord;
  8366. currentWord = '';
  8367. currentWordWidth = 0;
  8368. accumWidth = currentWordWidth;
  8369. }
  8370. lines.push(line);
  8371. linesWidths.push(accumWidth - currentWordWidth);
  8372. currentWord += ch;
  8373. currentWordWidth += chWidth;
  8374. line = '';
  8375. accumWidth = currentWordWidth;
  8376. }
  8377. else {
  8378. if (currentWord) {
  8379. line += currentWord;
  8380. accumWidth += currentWordWidth;
  8381. currentWord = '';
  8382. currentWordWidth = 0;
  8383. }
  8384. lines.push(line);
  8385. linesWidths.push(accumWidth);
  8386. line = ch;
  8387. accumWidth = chWidth;
  8388. }
  8389. }
  8390. continue;
  8391. }
  8392. accumWidth += chWidth;
  8393. if (inWord) {
  8394. currentWord += ch;
  8395. currentWordWidth += chWidth;
  8396. }
  8397. else {
  8398. if (currentWord) {
  8399. line += currentWord;
  8400. currentWord = '';
  8401. currentWordWidth = 0;
  8402. }
  8403. line += ch;
  8404. }
  8405. }
  8406. if (!lines.length && !line) {
  8407. line = text;
  8408. currentWord = '';
  8409. currentWordWidth = 0;
  8410. }
  8411. if (currentWord) {
  8412. line += currentWord;
  8413. }
  8414. if (line) {
  8415. lines.push(line);
  8416. linesWidths.push(accumWidth);
  8417. }
  8418. if (lines.length === 1) {
  8419. accumWidth += lastAccumWidth;
  8420. }
  8421. return {
  8422. accumWidth: accumWidth,
  8423. lines: lines,
  8424. linesWidths: linesWidths
  8425. };
  8426. }
  8427. function parsePercent$2(value, maxValue) {
  8428. if (typeof value === 'string') {
  8429. if (value.lastIndexOf('%') >= 0) {
  8430. return parseFloat(value) / 100 * maxValue;
  8431. }
  8432. return parseFloat(value);
  8433. }
  8434. return value;
  8435. }
  8436. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  8437. var DEFAULT_COMMON_STYLE = {
  8438. shadowBlur: 0,
  8439. shadowOffsetX: 0,
  8440. shadowOffsetY: 0,
  8441. shadowColor: '#000',
  8442. opacity: 1,
  8443. blend: 'source-over'
  8444. };
  8445. var DEFAULT_COMMON_ANIMATION_PROPS = {
  8446. style: {
  8447. shadowBlur: true,
  8448. shadowOffsetX: true,
  8449. shadowOffsetY: true,
  8450. shadowColor: true,
  8451. opacity: true
  8452. }
  8453. };
  8454. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  8455. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  8456. var Displayable = (function (_super) {
  8457. __extends(Displayable, _super);
  8458. function Displayable(props) {
  8459. return _super.call(this, props) || this;
  8460. }
  8461. Displayable.prototype._init = function (props) {
  8462. var keysArr = keys(props);
  8463. for (var i = 0; i < keysArr.length; i++) {
  8464. var key = keysArr[i];
  8465. if (key === 'style') {
  8466. this.useStyle(props[key]);
  8467. }
  8468. else {
  8469. _super.prototype.attrKV.call(this, key, props[key]);
  8470. }
  8471. }
  8472. if (!this.style) {
  8473. this.useStyle({});
  8474. }
  8475. };
  8476. Displayable.prototype.beforeBrush = function () { };
  8477. Displayable.prototype.afterBrush = function () { };
  8478. Displayable.prototype.innerBeforeBrush = function () { };
  8479. Displayable.prototype.innerAfterBrush = function () { };
  8480. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  8481. var m = this.transform;
  8482. if (this.ignore
  8483. || this.invisible
  8484. || this.style.opacity === 0
  8485. || (this.culling
  8486. && isDisplayableCulled(this, viewWidth, viewHeight))
  8487. || (m && !m[0] && !m[3])) {
  8488. return false;
  8489. }
  8490. if (considerClipPath && this.__clipPaths) {
  8491. for (var i = 0; i < this.__clipPaths.length; ++i) {
  8492. if (this.__clipPaths[i].isZeroArea()) {
  8493. return false;
  8494. }
  8495. }
  8496. }
  8497. if (considerAncestors && this.parent) {
  8498. var parent_1 = this.parent;
  8499. while (parent_1) {
  8500. if (parent_1.ignore) {
  8501. return false;
  8502. }
  8503. parent_1 = parent_1.parent;
  8504. }
  8505. }
  8506. return true;
  8507. };
  8508. Displayable.prototype.contain = function (x, y) {
  8509. return this.rectContain(x, y);
  8510. };
  8511. Displayable.prototype.traverse = function (cb, context) {
  8512. cb.call(context, this);
  8513. };
  8514. Displayable.prototype.rectContain = function (x, y) {
  8515. var coord = this.transformCoordToLocal(x, y);
  8516. var rect = this.getBoundingRect();
  8517. return rect.contain(coord[0], coord[1]);
  8518. };
  8519. Displayable.prototype.getPaintRect = function () {
  8520. var rect = this._paintRect;
  8521. if (!this._paintRect || this.__dirty) {
  8522. var transform = this.transform;
  8523. var elRect = this.getBoundingRect();
  8524. var style = this.style;
  8525. var shadowSize = style.shadowBlur || 0;
  8526. var shadowOffsetX = style.shadowOffsetX || 0;
  8527. var shadowOffsetY = style.shadowOffsetY || 0;
  8528. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  8529. if (transform) {
  8530. BoundingRect.applyTransform(rect, elRect, transform);
  8531. }
  8532. else {
  8533. rect.copy(elRect);
  8534. }
  8535. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  8536. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  8537. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  8538. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  8539. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  8540. }
  8541. var tolerance = this.dirtyRectTolerance;
  8542. if (!rect.isZero()) {
  8543. rect.x = Math.floor(rect.x - tolerance);
  8544. rect.y = Math.floor(rect.y - tolerance);
  8545. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  8546. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  8547. }
  8548. }
  8549. return rect;
  8550. };
  8551. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  8552. if (paintRect) {
  8553. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  8554. this._prevPaintRect.copy(paintRect);
  8555. }
  8556. else {
  8557. this._prevPaintRect = null;
  8558. }
  8559. };
  8560. Displayable.prototype.getPrevPaintRect = function () {
  8561. return this._prevPaintRect;
  8562. };
  8563. Displayable.prototype.animateStyle = function (loop) {
  8564. return this.animate('style', loop);
  8565. };
  8566. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  8567. if (targetKey === 'style') {
  8568. this.dirtyStyle();
  8569. }
  8570. else {
  8571. this.markRedraw();
  8572. }
  8573. };
  8574. Displayable.prototype.attrKV = function (key, value) {
  8575. if (key !== 'style') {
  8576. _super.prototype.attrKV.call(this, key, value);
  8577. }
  8578. else {
  8579. if (!this.style) {
  8580. this.useStyle(value);
  8581. }
  8582. else {
  8583. this.setStyle(value);
  8584. }
  8585. }
  8586. };
  8587. Displayable.prototype.setStyle = function (keyOrObj, value) {
  8588. if (typeof keyOrObj === 'string') {
  8589. this.style[keyOrObj] = value;
  8590. }
  8591. else {
  8592. extend(this.style, keyOrObj);
  8593. }
  8594. this.dirtyStyle();
  8595. return this;
  8596. };
  8597. Displayable.prototype.dirtyStyle = function () {
  8598. this.markRedraw();
  8599. this.__dirty |= Displayable.STYLE_CHANGED_BIT;
  8600. if (this._rect) {
  8601. this._rect = null;
  8602. }
  8603. };
  8604. Displayable.prototype.dirty = function () {
  8605. this.dirtyStyle();
  8606. };
  8607. Displayable.prototype.styleChanged = function () {
  8608. return !!(this.__dirty & Displayable.STYLE_CHANGED_BIT);
  8609. };
  8610. Displayable.prototype.styleUpdated = function () {
  8611. this.__dirty &= ~Displayable.STYLE_CHANGED_BIT;
  8612. };
  8613. Displayable.prototype.createStyle = function (obj) {
  8614. return createObject(DEFAULT_COMMON_STYLE, obj);
  8615. };
  8616. Displayable.prototype.useStyle = function (obj) {
  8617. if (!obj[STYLE_MAGIC_KEY]) {
  8618. obj = this.createStyle(obj);
  8619. }
  8620. if (this.__inHover) {
  8621. this.__hoverStyle = obj;
  8622. }
  8623. else {
  8624. this.style = obj;
  8625. }
  8626. this.dirtyStyle();
  8627. };
  8628. Displayable.prototype.isStyleObject = function (obj) {
  8629. return obj[STYLE_MAGIC_KEY];
  8630. };
  8631. Displayable.prototype._innerSaveToNormal = function (toState) {
  8632. _super.prototype._innerSaveToNormal.call(this, toState);
  8633. var normalState = this._normalState;
  8634. if (toState.style && !normalState.style) {
  8635. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  8636. }
  8637. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  8638. };
  8639. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  8640. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  8641. var needsRestoreToNormal = !(state && keepCurrentStates);
  8642. var targetStyle;
  8643. if (state && state.style) {
  8644. if (transition) {
  8645. if (keepCurrentStates) {
  8646. targetStyle = state.style;
  8647. }
  8648. else {
  8649. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  8650. this._mergeStyle(targetStyle, state.style);
  8651. }
  8652. }
  8653. else {
  8654. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  8655. this._mergeStyle(targetStyle, state.style);
  8656. }
  8657. }
  8658. else if (needsRestoreToNormal) {
  8659. targetStyle = normalState.style;
  8660. }
  8661. if (targetStyle) {
  8662. if (transition) {
  8663. var sourceStyle = this.style;
  8664. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  8665. if (needsRestoreToNormal) {
  8666. var changedKeys = keys(sourceStyle);
  8667. for (var i = 0; i < changedKeys.length; i++) {
  8668. var key = changedKeys[i];
  8669. if (key in targetStyle) {
  8670. targetStyle[key] = targetStyle[key];
  8671. this.style[key] = sourceStyle[key];
  8672. }
  8673. }
  8674. }
  8675. var targetKeys = keys(targetStyle);
  8676. for (var i = 0; i < targetKeys.length; i++) {
  8677. var key = targetKeys[i];
  8678. this.style[key] = this.style[key];
  8679. }
  8680. this._transitionState(stateName, {
  8681. style: targetStyle
  8682. }, animationCfg, this.getAnimationStyleProps());
  8683. }
  8684. else {
  8685. this.useStyle(targetStyle);
  8686. }
  8687. }
  8688. for (var i = 0; i < PRIMARY_STATES_KEYS$1.length; i++) {
  8689. var key = PRIMARY_STATES_KEYS$1[i];
  8690. if (state && state[key] != null) {
  8691. this[key] = state[key];
  8692. }
  8693. else if (needsRestoreToNormal) {
  8694. if (normalState[key] != null) {
  8695. this[key] = normalState[key];
  8696. }
  8697. }
  8698. }
  8699. };
  8700. Displayable.prototype._mergeStates = function (states) {
  8701. var mergedState = _super.prototype._mergeStates.call(this, states);
  8702. var mergedStyle;
  8703. for (var i = 0; i < states.length; i++) {
  8704. var state = states[i];
  8705. if (state.style) {
  8706. mergedStyle = mergedStyle || {};
  8707. this._mergeStyle(mergedStyle, state.style);
  8708. }
  8709. }
  8710. if (mergedStyle) {
  8711. mergedState.style = mergedStyle;
  8712. }
  8713. return mergedState;
  8714. };
  8715. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  8716. extend(targetStyle, sourceStyle);
  8717. return targetStyle;
  8718. };
  8719. Displayable.prototype.getAnimationStyleProps = function () {
  8720. return DEFAULT_COMMON_ANIMATION_PROPS;
  8721. };
  8722. Displayable.STYLE_CHANGED_BIT = 2;
  8723. Displayable.initDefaultProps = (function () {
  8724. var dispProto = Displayable.prototype;
  8725. dispProto.type = 'displayable';
  8726. dispProto.invisible = false;
  8727. dispProto.z = 0;
  8728. dispProto.z2 = 0;
  8729. dispProto.zlevel = 0;
  8730. dispProto.culling = false;
  8731. dispProto.cursor = 'pointer';
  8732. dispProto.rectHover = false;
  8733. dispProto.incremental = false;
  8734. dispProto._rect = null;
  8735. dispProto.dirtyRectTolerance = 0;
  8736. dispProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT;
  8737. })();
  8738. return Displayable;
  8739. }(Element));
  8740. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8741. var viewRect = new BoundingRect(0, 0, 0, 0);
  8742. function isDisplayableCulled(el, width, height) {
  8743. tmpRect.copy(el.getBoundingRect());
  8744. if (el.transform) {
  8745. tmpRect.applyTransform(el.transform);
  8746. }
  8747. viewRect.width = width;
  8748. viewRect.height = height;
  8749. return !tmpRect.intersect(viewRect);
  8750. }
  8751. var mathPow = Math.pow;
  8752. var mathSqrt = Math.sqrt;
  8753. var EPSILON$1 = 1e-8;
  8754. var EPSILON_NUMERIC = 1e-4;
  8755. var THREE_SQRT = mathSqrt(3);
  8756. var ONE_THIRD = 1 / 3;
  8757. var _v0 = create();
  8758. var _v1 = create();
  8759. var _v2 = create();
  8760. function isAroundZero(val) {
  8761. return val > -EPSILON$1 && val < EPSILON$1;
  8762. }
  8763. function isNotAroundZero$1(val) {
  8764. return val > EPSILON$1 || val < -EPSILON$1;
  8765. }
  8766. function cubicAt(p0, p1, p2, p3, t) {
  8767. var onet = 1 - t;
  8768. return onet * onet * (onet * p0 + 3 * t * p1)
  8769. + t * t * (t * p3 + 3 * onet * p2);
  8770. }
  8771. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  8772. var onet = 1 - t;
  8773. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  8774. + (p3 - p2) * t * t);
  8775. }
  8776. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  8777. var a = p3 + 3 * (p1 - p2) - p0;
  8778. var b = 3 * (p2 - p1 * 2 + p0);
  8779. var c = 3 * (p1 - p0);
  8780. var d = p0 - val;
  8781. var A = b * b - 3 * a * c;
  8782. var B = b * c - 9 * a * d;
  8783. var C = c * c - 3 * b * d;
  8784. var n = 0;
  8785. if (isAroundZero(A) && isAroundZero(B)) {
  8786. if (isAroundZero(b)) {
  8787. roots[0] = 0;
  8788. }
  8789. else {
  8790. var t1 = -c / b;
  8791. if (t1 >= 0 && t1 <= 1) {
  8792. roots[n++] = t1;
  8793. }
  8794. }
  8795. }
  8796. else {
  8797. var disc = B * B - 4 * A * C;
  8798. if (isAroundZero(disc)) {
  8799. var K = B / A;
  8800. var t1 = -b / a + K;
  8801. var t2 = -K / 2;
  8802. if (t1 >= 0 && t1 <= 1) {
  8803. roots[n++] = t1;
  8804. }
  8805. if (t2 >= 0 && t2 <= 1) {
  8806. roots[n++] = t2;
  8807. }
  8808. }
  8809. else if (disc > 0) {
  8810. var discSqrt = mathSqrt(disc);
  8811. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  8812. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  8813. if (Y1 < 0) {
  8814. Y1 = -mathPow(-Y1, ONE_THIRD);
  8815. }
  8816. else {
  8817. Y1 = mathPow(Y1, ONE_THIRD);
  8818. }
  8819. if (Y2 < 0) {
  8820. Y2 = -mathPow(-Y2, ONE_THIRD);
  8821. }
  8822. else {
  8823. Y2 = mathPow(Y2, ONE_THIRD);
  8824. }
  8825. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  8826. if (t1 >= 0 && t1 <= 1) {
  8827. roots[n++] = t1;
  8828. }
  8829. }
  8830. else {
  8831. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  8832. var theta = Math.acos(T) / 3;
  8833. var ASqrt = mathSqrt(A);
  8834. var tmp = Math.cos(theta);
  8835. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  8836. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  8837. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  8838. if (t1 >= 0 && t1 <= 1) {
  8839. roots[n++] = t1;
  8840. }
  8841. if (t2 >= 0 && t2 <= 1) {
  8842. roots[n++] = t2;
  8843. }
  8844. if (t3 >= 0 && t3 <= 1) {
  8845. roots[n++] = t3;
  8846. }
  8847. }
  8848. }
  8849. return n;
  8850. }
  8851. function cubicExtrema(p0, p1, p2, p3, extrema) {
  8852. var b = 6 * p2 - 12 * p1 + 6 * p0;
  8853. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  8854. var c = 3 * p1 - 3 * p0;
  8855. var n = 0;
  8856. if (isAroundZero(a)) {
  8857. if (isNotAroundZero$1(b)) {
  8858. var t1 = -c / b;
  8859. if (t1 >= 0 && t1 <= 1) {
  8860. extrema[n++] = t1;
  8861. }
  8862. }
  8863. }
  8864. else {
  8865. var disc = b * b - 4 * a * c;
  8866. if (isAroundZero(disc)) {
  8867. extrema[0] = -b / (2 * a);
  8868. }
  8869. else if (disc > 0) {
  8870. var discSqrt = mathSqrt(disc);
  8871. var t1 = (-b + discSqrt) / (2 * a);
  8872. var t2 = (-b - discSqrt) / (2 * a);
  8873. if (t1 >= 0 && t1 <= 1) {
  8874. extrema[n++] = t1;
  8875. }
  8876. if (t2 >= 0 && t2 <= 1) {
  8877. extrema[n++] = t2;
  8878. }
  8879. }
  8880. }
  8881. return n;
  8882. }
  8883. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  8884. var p01 = (p1 - p0) * t + p0;
  8885. var p12 = (p2 - p1) * t + p1;
  8886. var p23 = (p3 - p2) * t + p2;
  8887. var p012 = (p12 - p01) * t + p01;
  8888. var p123 = (p23 - p12) * t + p12;
  8889. var p0123 = (p123 - p012) * t + p012;
  8890. out[0] = p0;
  8891. out[1] = p01;
  8892. out[2] = p012;
  8893. out[3] = p0123;
  8894. out[4] = p0123;
  8895. out[5] = p123;
  8896. out[6] = p23;
  8897. out[7] = p3;
  8898. }
  8899. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  8900. var t;
  8901. var interval = 0.005;
  8902. var d = Infinity;
  8903. var prev;
  8904. var next;
  8905. var d1;
  8906. var d2;
  8907. _v0[0] = x;
  8908. _v0[1] = y;
  8909. for (var _t = 0; _t < 1; _t += 0.05) {
  8910. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  8911. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  8912. d1 = distSquare(_v0, _v1);
  8913. if (d1 < d) {
  8914. t = _t;
  8915. d = d1;
  8916. }
  8917. }
  8918. d = Infinity;
  8919. for (var i = 0; i < 32; i++) {
  8920. if (interval < EPSILON_NUMERIC) {
  8921. break;
  8922. }
  8923. prev = t - interval;
  8924. next = t + interval;
  8925. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  8926. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  8927. d1 = distSquare(_v1, _v0);
  8928. if (prev >= 0 && d1 < d) {
  8929. t = prev;
  8930. d = d1;
  8931. }
  8932. else {
  8933. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  8934. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  8935. d2 = distSquare(_v2, _v0);
  8936. if (next <= 1 && d2 < d) {
  8937. t = next;
  8938. d = d2;
  8939. }
  8940. else {
  8941. interval *= 0.5;
  8942. }
  8943. }
  8944. }
  8945. if (out) {
  8946. out[0] = cubicAt(x0, x1, x2, x3, t);
  8947. out[1] = cubicAt(y0, y1, y2, y3, t);
  8948. }
  8949. return mathSqrt(d);
  8950. }
  8951. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  8952. var px = x0;
  8953. var py = y0;
  8954. var d = 0;
  8955. var step = 1 / iteration;
  8956. for (var i = 1; i <= iteration; i++) {
  8957. var t = i * step;
  8958. var x = cubicAt(x0, x1, x2, x3, t);
  8959. var y = cubicAt(y0, y1, y2, y3, t);
  8960. var dx = x - px;
  8961. var dy = y - py;
  8962. d += Math.sqrt(dx * dx + dy * dy);
  8963. px = x;
  8964. py = y;
  8965. }
  8966. return d;
  8967. }
  8968. function quadraticAt(p0, p1, p2, t) {
  8969. var onet = 1 - t;
  8970. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  8971. }
  8972. function quadraticDerivativeAt(p0, p1, p2, t) {
  8973. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  8974. }
  8975. function quadraticRootAt(p0, p1, p2, val, roots) {
  8976. var a = p0 - 2 * p1 + p2;
  8977. var b = 2 * (p1 - p0);
  8978. var c = p0 - val;
  8979. var n = 0;
  8980. if (isAroundZero(a)) {
  8981. if (isNotAroundZero$1(b)) {
  8982. var t1 = -c / b;
  8983. if (t1 >= 0 && t1 <= 1) {
  8984. roots[n++] = t1;
  8985. }
  8986. }
  8987. }
  8988. else {
  8989. var disc = b * b - 4 * a * c;
  8990. if (isAroundZero(disc)) {
  8991. var t1 = -b / (2 * a);
  8992. if (t1 >= 0 && t1 <= 1) {
  8993. roots[n++] = t1;
  8994. }
  8995. }
  8996. else if (disc > 0) {
  8997. var discSqrt = mathSqrt(disc);
  8998. var t1 = (-b + discSqrt) / (2 * a);
  8999. var t2 = (-b - discSqrt) / (2 * a);
  9000. if (t1 >= 0 && t1 <= 1) {
  9001. roots[n++] = t1;
  9002. }
  9003. if (t2 >= 0 && t2 <= 1) {
  9004. roots[n++] = t2;
  9005. }
  9006. }
  9007. }
  9008. return n;
  9009. }
  9010. function quadraticExtremum(p0, p1, p2) {
  9011. var divider = p0 + p2 - 2 * p1;
  9012. if (divider === 0) {
  9013. return 0.5;
  9014. }
  9015. else {
  9016. return (p0 - p1) / divider;
  9017. }
  9018. }
  9019. function quadraticSubdivide(p0, p1, p2, t, out) {
  9020. var p01 = (p1 - p0) * t + p0;
  9021. var p12 = (p2 - p1) * t + p1;
  9022. var p012 = (p12 - p01) * t + p01;
  9023. out[0] = p0;
  9024. out[1] = p01;
  9025. out[2] = p012;
  9026. out[3] = p012;
  9027. out[4] = p12;
  9028. out[5] = p2;
  9029. }
  9030. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  9031. var t;
  9032. var interval = 0.005;
  9033. var d = Infinity;
  9034. _v0[0] = x;
  9035. _v0[1] = y;
  9036. for (var _t = 0; _t < 1; _t += 0.05) {
  9037. _v1[0] = quadraticAt(x0, x1, x2, _t);
  9038. _v1[1] = quadraticAt(y0, y1, y2, _t);
  9039. var d1 = distSquare(_v0, _v1);
  9040. if (d1 < d) {
  9041. t = _t;
  9042. d = d1;
  9043. }
  9044. }
  9045. d = Infinity;
  9046. for (var i = 0; i < 32; i++) {
  9047. if (interval < EPSILON_NUMERIC) {
  9048. break;
  9049. }
  9050. var prev = t - interval;
  9051. var next = t + interval;
  9052. _v1[0] = quadraticAt(x0, x1, x2, prev);
  9053. _v1[1] = quadraticAt(y0, y1, y2, prev);
  9054. var d1 = distSquare(_v1, _v0);
  9055. if (prev >= 0 && d1 < d) {
  9056. t = prev;
  9057. d = d1;
  9058. }
  9059. else {
  9060. _v2[0] = quadraticAt(x0, x1, x2, next);
  9061. _v2[1] = quadraticAt(y0, y1, y2, next);
  9062. var d2 = distSquare(_v2, _v0);
  9063. if (next <= 1 && d2 < d) {
  9064. t = next;
  9065. d = d2;
  9066. }
  9067. else {
  9068. interval *= 0.5;
  9069. }
  9070. }
  9071. }
  9072. if (out) {
  9073. out[0] = quadraticAt(x0, x1, x2, t);
  9074. out[1] = quadraticAt(y0, y1, y2, t);
  9075. }
  9076. return mathSqrt(d);
  9077. }
  9078. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  9079. var px = x0;
  9080. var py = y0;
  9081. var d = 0;
  9082. var step = 1 / iteration;
  9083. for (var i = 1; i <= iteration; i++) {
  9084. var t = i * step;
  9085. var x = quadraticAt(x0, x1, x2, t);
  9086. var y = quadraticAt(y0, y1, y2, t);
  9087. var dx = x - px;
  9088. var dy = y - py;
  9089. d += Math.sqrt(dx * dx + dy * dy);
  9090. px = x;
  9091. py = y;
  9092. }
  9093. return d;
  9094. }
  9095. var mathMin$1 = Math.min;
  9096. var mathMax$1 = Math.max;
  9097. var mathSin = Math.sin;
  9098. var mathCos = Math.cos;
  9099. var PI2 = Math.PI * 2;
  9100. var start = create();
  9101. var end = create();
  9102. var extremity = create();
  9103. function fromPoints(points, min, max) {
  9104. if (points.length === 0) {
  9105. return;
  9106. }
  9107. var p = points[0];
  9108. var left = p[0];
  9109. var right = p[0];
  9110. var top = p[1];
  9111. var bottom = p[1];
  9112. for (var i = 1; i < points.length; i++) {
  9113. p = points[i];
  9114. left = mathMin$1(left, p[0]);
  9115. right = mathMax$1(right, p[0]);
  9116. top = mathMin$1(top, p[1]);
  9117. bottom = mathMax$1(bottom, p[1]);
  9118. }
  9119. min[0] = left;
  9120. min[1] = top;
  9121. max[0] = right;
  9122. max[1] = bottom;
  9123. }
  9124. function fromLine(x0, y0, x1, y1, min, max) {
  9125. min[0] = mathMin$1(x0, x1);
  9126. min[1] = mathMin$1(y0, y1);
  9127. max[0] = mathMax$1(x0, x1);
  9128. max[1] = mathMax$1(y0, y1);
  9129. }
  9130. var xDim = [];
  9131. var yDim = [];
  9132. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9133. var cubicExtrema$1 = cubicExtrema;
  9134. var cubicAt$1 = cubicAt;
  9135. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9136. min[0] = Infinity;
  9137. min[1] = Infinity;
  9138. max[0] = -Infinity;
  9139. max[1] = -Infinity;
  9140. for (var i = 0; i < n; i++) {
  9141. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9142. min[0] = mathMin$1(x, min[0]);
  9143. max[0] = mathMax$1(x, max[0]);
  9144. }
  9145. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9146. for (var i = 0; i < n; i++) {
  9147. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9148. min[1] = mathMin$1(y, min[1]);
  9149. max[1] = mathMax$1(y, max[1]);
  9150. }
  9151. min[0] = mathMin$1(x0, min[0]);
  9152. max[0] = mathMax$1(x0, max[0]);
  9153. min[0] = mathMin$1(x3, min[0]);
  9154. max[0] = mathMax$1(x3, max[0]);
  9155. min[1] = mathMin$1(y0, min[1]);
  9156. max[1] = mathMax$1(y0, max[1]);
  9157. min[1] = mathMin$1(y3, min[1]);
  9158. max[1] = mathMax$1(y3, max[1]);
  9159. }
  9160. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9161. var quadraticExtremum$1 = quadraticExtremum;
  9162. var quadraticAt$1 = quadraticAt;
  9163. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9164. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9165. var x = quadraticAt$1(x0, x1, x2, tx);
  9166. var y = quadraticAt$1(y0, y1, y2, ty);
  9167. min[0] = mathMin$1(x0, x2, x);
  9168. min[1] = mathMin$1(y0, y2, y);
  9169. max[0] = mathMax$1(x0, x2, x);
  9170. max[1] = mathMax$1(y0, y2, y);
  9171. }
  9172. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9173. var vec2Min = min;
  9174. var vec2Max = max;
  9175. var diff = Math.abs(startAngle - endAngle);
  9176. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9177. min$1[0] = x - rx;
  9178. min$1[1] = y - ry;
  9179. max$1[0] = x + rx;
  9180. max$1[1] = y + ry;
  9181. return;
  9182. }
  9183. start[0] = mathCos(startAngle) * rx + x;
  9184. start[1] = mathSin(startAngle) * ry + y;
  9185. end[0] = mathCos(endAngle) * rx + x;
  9186. end[1] = mathSin(endAngle) * ry + y;
  9187. vec2Min(min$1, start, end);
  9188. vec2Max(max$1, start, end);
  9189. startAngle = startAngle % (PI2);
  9190. if (startAngle < 0) {
  9191. startAngle = startAngle + PI2;
  9192. }
  9193. endAngle = endAngle % (PI2);
  9194. if (endAngle < 0) {
  9195. endAngle = endAngle + PI2;
  9196. }
  9197. if (startAngle > endAngle && !anticlockwise) {
  9198. endAngle += PI2;
  9199. }
  9200. else if (startAngle < endAngle && anticlockwise) {
  9201. startAngle += PI2;
  9202. }
  9203. if (anticlockwise) {
  9204. var tmp = endAngle;
  9205. endAngle = startAngle;
  9206. startAngle = tmp;
  9207. }
  9208. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9209. if (angle > startAngle) {
  9210. extremity[0] = mathCos(angle) * rx + x;
  9211. extremity[1] = mathSin(angle) * ry + y;
  9212. vec2Min(min$1, extremity, min$1);
  9213. vec2Max(max$1, extremity, max$1);
  9214. }
  9215. }
  9216. }
  9217. var CMD = {
  9218. M: 1,
  9219. L: 2,
  9220. C: 3,
  9221. Q: 4,
  9222. A: 5,
  9223. Z: 6,
  9224. R: 7
  9225. };
  9226. var tmpOutX = [];
  9227. var tmpOutY = [];
  9228. var min$1 = [];
  9229. var max$1 = [];
  9230. var min2 = [];
  9231. var max2 = [];
  9232. var mathMin$2 = Math.min;
  9233. var mathMax$2 = Math.max;
  9234. var mathCos$1 = Math.cos;
  9235. var mathSin$1 = Math.sin;
  9236. var mathSqrt$1 = Math.sqrt;
  9237. var mathAbs = Math.abs;
  9238. var PI = Math.PI;
  9239. var PI2$1 = PI * 2;
  9240. var hasTypedArray = typeof Float32Array !== 'undefined';
  9241. var tmpAngles = [];
  9242. function modPI2(radian) {
  9243. var n = Math.round(radian / PI * 1e8) / 1e8;
  9244. return (n % 2) * PI;
  9245. }
  9246. function normalizeArcAngles(angles, anticlockwise) {
  9247. var newStartAngle = modPI2(angles[0]);
  9248. if (newStartAngle < 0) {
  9249. newStartAngle += PI2$1;
  9250. }
  9251. var delta = newStartAngle - angles[0];
  9252. var newEndAngle = angles[1];
  9253. newEndAngle += delta;
  9254. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9255. newEndAngle = newStartAngle + PI2$1;
  9256. }
  9257. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9258. newEndAngle = newStartAngle - PI2$1;
  9259. }
  9260. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9261. newEndAngle = newStartAngle +
  9262. (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9263. }
  9264. else if (anticlockwise && newStartAngle < newEndAngle) {
  9265. newEndAngle = newStartAngle -
  9266. (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9267. }
  9268. angles[0] = newStartAngle;
  9269. angles[1] = newEndAngle;
  9270. }
  9271. var PathProxy = (function () {
  9272. function PathProxy(notSaveData) {
  9273. this.dpr = 1;
  9274. this._version = 0;
  9275. this._xi = 0;
  9276. this._yi = 0;
  9277. this._x0 = 0;
  9278. this._y0 = 0;
  9279. this._len = 0;
  9280. if (notSaveData) {
  9281. this._saveData = false;
  9282. }
  9283. if (this._saveData) {
  9284. this.data = [];
  9285. }
  9286. }
  9287. PathProxy.prototype.increaseVersion = function () {
  9288. this._version++;
  9289. };
  9290. PathProxy.prototype.getVersion = function () {
  9291. return this._version;
  9292. };
  9293. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9294. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9295. if (segmentIgnoreThreshold > 0) {
  9296. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9297. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9298. }
  9299. };
  9300. PathProxy.prototype.setDPR = function (dpr) {
  9301. this.dpr = dpr;
  9302. };
  9303. PathProxy.prototype.setContext = function (ctx) {
  9304. this._ctx = ctx;
  9305. };
  9306. PathProxy.prototype.getContext = function () {
  9307. return this._ctx;
  9308. };
  9309. PathProxy.prototype.beginPath = function () {
  9310. this._ctx && this._ctx.beginPath();
  9311. this.reset();
  9312. return this;
  9313. };
  9314. PathProxy.prototype.reset = function () {
  9315. if (this._saveData) {
  9316. this._len = 0;
  9317. }
  9318. if (this._lineDash) {
  9319. this._lineDash = null;
  9320. this._dashOffset = 0;
  9321. }
  9322. if (this._pathSegLen) {
  9323. this._pathSegLen = null;
  9324. this._pathLen = 0;
  9325. }
  9326. this._version++;
  9327. };
  9328. PathProxy.prototype.moveTo = function (x, y) {
  9329. this.addData(CMD.M, x, y);
  9330. this._ctx && this._ctx.moveTo(x, y);
  9331. this._x0 = x;
  9332. this._y0 = y;
  9333. this._xi = x;
  9334. this._yi = y;
  9335. return this;
  9336. };
  9337. PathProxy.prototype.lineTo = function (x, y) {
  9338. var exceedUnit = mathAbs(x - this._xi) > this._ux
  9339. || mathAbs(y - this._yi) > this._uy
  9340. || this._len < 5;
  9341. this.addData(CMD.L, x, y);
  9342. if (this._ctx && exceedUnit) {
  9343. this._needsDash ? this._dashedLineTo(x, y)
  9344. : this._ctx.lineTo(x, y);
  9345. }
  9346. if (exceedUnit) {
  9347. this._xi = x;
  9348. this._yi = y;
  9349. }
  9350. return this;
  9351. };
  9352. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9353. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9354. if (this._ctx) {
  9355. this._needsDash ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  9356. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9357. }
  9358. this._xi = x3;
  9359. this._yi = y3;
  9360. return this;
  9361. };
  9362. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9363. this.addData(CMD.Q, x1, y1, x2, y2);
  9364. if (this._ctx) {
  9365. this._needsDash ? this._dashedQuadraticTo(x1, y1, x2, y2)
  9366. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9367. }
  9368. this._xi = x2;
  9369. this._yi = y2;
  9370. return this;
  9371. };
  9372. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9373. tmpAngles[0] = startAngle;
  9374. tmpAngles[1] = endAngle;
  9375. normalizeArcAngles(tmpAngles, anticlockwise);
  9376. startAngle = tmpAngles[0];
  9377. endAngle = tmpAngles[1];
  9378. var delta = endAngle - startAngle;
  9379. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9380. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9381. this._xi = mathCos$1(endAngle) * r + cx;
  9382. this._yi = mathSin$1(endAngle) * r + cy;
  9383. return this;
  9384. };
  9385. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9386. if (this._ctx) {
  9387. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9388. }
  9389. return this;
  9390. };
  9391. PathProxy.prototype.rect = function (x, y, w, h) {
  9392. this._ctx && this._ctx.rect(x, y, w, h);
  9393. this.addData(CMD.R, x, y, w, h);
  9394. return this;
  9395. };
  9396. PathProxy.prototype.closePath = function () {
  9397. this.addData(CMD.Z);
  9398. var ctx = this._ctx;
  9399. var x0 = this._x0;
  9400. var y0 = this._y0;
  9401. if (ctx) {
  9402. this._needsDash && this._dashedLineTo(x0, y0);
  9403. ctx.closePath();
  9404. }
  9405. this._xi = x0;
  9406. this._yi = y0;
  9407. return this;
  9408. };
  9409. PathProxy.prototype.fill = function (ctx) {
  9410. ctx && ctx.fill();
  9411. this.toStatic();
  9412. };
  9413. PathProxy.prototype.stroke = function (ctx) {
  9414. ctx && ctx.stroke();
  9415. this.toStatic();
  9416. };
  9417. PathProxy.prototype.setLineDash = function (lineDash) {
  9418. if (lineDash instanceof Array) {
  9419. this._lineDash = lineDash;
  9420. this._dashIdx = 0;
  9421. var lineDashSum = 0;
  9422. for (var i = 0; i < lineDash.length; i++) {
  9423. lineDashSum += lineDash[i];
  9424. }
  9425. this._dashSum = lineDashSum;
  9426. this._needsDash = true;
  9427. }
  9428. else {
  9429. this._lineDash = null;
  9430. this._needsDash = false;
  9431. }
  9432. return this;
  9433. };
  9434. PathProxy.prototype.setLineDashOffset = function (offset) {
  9435. this._dashOffset = offset;
  9436. return this;
  9437. };
  9438. PathProxy.prototype.len = function () {
  9439. return this._len;
  9440. };
  9441. PathProxy.prototype.setData = function (data) {
  9442. var len = data.length;
  9443. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9444. this.data = new Float32Array(len);
  9445. }
  9446. for (var i = 0; i < len; i++) {
  9447. this.data[i] = data[i];
  9448. }
  9449. this._len = len;
  9450. };
  9451. PathProxy.prototype.appendPath = function (path) {
  9452. if (!(path instanceof Array)) {
  9453. path = [path];
  9454. }
  9455. var len = path.length;
  9456. var appendSize = 0;
  9457. var offset = this._len;
  9458. for (var i = 0; i < len; i++) {
  9459. appendSize += path[i].len();
  9460. }
  9461. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9462. this.data = new Float32Array(offset + appendSize);
  9463. }
  9464. for (var i = 0; i < len; i++) {
  9465. var appendPathData = path[i].data;
  9466. for (var k = 0; k < appendPathData.length; k++) {
  9467. this.data[offset++] = appendPathData[k];
  9468. }
  9469. }
  9470. this._len = offset;
  9471. };
  9472. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9473. if (!this._saveData) {
  9474. return;
  9475. }
  9476. var data = this.data;
  9477. if (this._len + arguments.length > data.length) {
  9478. this._expandData();
  9479. data = this.data;
  9480. }
  9481. for (var i = 0; i < arguments.length; i++) {
  9482. data[this._len++] = arguments[i];
  9483. }
  9484. };
  9485. PathProxy.prototype._expandData = function () {
  9486. if (!(this.data instanceof Array)) {
  9487. var newData = [];
  9488. for (var i = 0; i < this._len; i++) {
  9489. newData[i] = this.data[i];
  9490. }
  9491. this.data = newData;
  9492. }
  9493. };
  9494. PathProxy.prototype._dashedLineTo = function (x1, y1) {
  9495. var dashSum = this._dashSum;
  9496. var lineDash = this._lineDash;
  9497. var ctx = this._ctx;
  9498. var offset = this._dashOffset;
  9499. var x0 = this._xi;
  9500. var y0 = this._yi;
  9501. var dx = x1 - x0;
  9502. var dy = y1 - y0;
  9503. var dist = mathSqrt$1(dx * dx + dy * dy);
  9504. var x = x0;
  9505. var y = y0;
  9506. var nDash = lineDash.length;
  9507. var dash;
  9508. var idx;
  9509. dx /= dist;
  9510. dy /= dist;
  9511. if (offset < 0) {
  9512. offset = dashSum + offset;
  9513. }
  9514. offset %= dashSum;
  9515. x -= offset * dx;
  9516. y -= offset * dy;
  9517. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  9518. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  9519. idx = this._dashIdx;
  9520. dash = lineDash[idx];
  9521. x += dx * dash;
  9522. y += dy * dash;
  9523. this._dashIdx = (idx + 1) % nDash;
  9524. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  9525. continue;
  9526. }
  9527. 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));
  9528. }
  9529. dx = x - x1;
  9530. dy = y - y1;
  9531. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9532. };
  9533. PathProxy.prototype._dashedBezierTo = function (x1, y1, x2, y2, x3, y3) {
  9534. var ctx = this._ctx;
  9535. var dashSum = this._dashSum;
  9536. var offset = this._dashOffset;
  9537. var lineDash = this._lineDash;
  9538. var x0 = this._xi;
  9539. var y0 = this._yi;
  9540. var bezierLen = 0;
  9541. var idx = this._dashIdx;
  9542. var nDash = lineDash.length;
  9543. var t;
  9544. var dx;
  9545. var dy;
  9546. var x;
  9547. var y;
  9548. var tmpLen = 0;
  9549. if (offset < 0) {
  9550. offset = dashSum + offset;
  9551. }
  9552. offset %= dashSum;
  9553. for (t = 0; t < 1; t += 0.1) {
  9554. dx = cubicAt(x0, x1, x2, x3, t + 0.1)
  9555. - cubicAt(x0, x1, x2, x3, t);
  9556. dy = cubicAt(y0, y1, y2, y3, t + 0.1)
  9557. - cubicAt(y0, y1, y2, y3, t);
  9558. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  9559. }
  9560. for (; idx < nDash; idx++) {
  9561. tmpLen += lineDash[idx];
  9562. if (tmpLen > offset) {
  9563. break;
  9564. }
  9565. }
  9566. t = (tmpLen - offset) / bezierLen;
  9567. while (t <= 1) {
  9568. x = cubicAt(x0, x1, x2, x3, t);
  9569. y = cubicAt(y0, y1, y2, y3, t);
  9570. idx % 2 ? ctx.moveTo(x, y)
  9571. : ctx.lineTo(x, y);
  9572. t += lineDash[idx] / bezierLen;
  9573. idx = (idx + 1) % nDash;
  9574. }
  9575. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  9576. dx = x3 - x;
  9577. dy = y3 - y;
  9578. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9579. };
  9580. PathProxy.prototype._dashedQuadraticTo = function (x1, y1, x2, y2) {
  9581. var x3 = x2;
  9582. var y3 = y2;
  9583. x2 = (x2 + 2 * x1) / 3;
  9584. y2 = (y2 + 2 * y1) / 3;
  9585. x1 = (this._xi + 2 * x1) / 3;
  9586. y1 = (this._yi + 2 * y1) / 3;
  9587. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  9588. };
  9589. PathProxy.prototype.toStatic = function () {
  9590. if (!this._saveData) {
  9591. return;
  9592. }
  9593. var data = this.data;
  9594. if (data instanceof Array) {
  9595. data.length = this._len;
  9596. if (hasTypedArray && this._len > 11) {
  9597. this.data = new Float32Array(data);
  9598. }
  9599. }
  9600. };
  9601. PathProxy.prototype.getBoundingRect = function () {
  9602. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9603. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9604. var data = this.data;
  9605. var xi = 0;
  9606. var yi = 0;
  9607. var x0 = 0;
  9608. var y0 = 0;
  9609. var i;
  9610. for (i = 0; i < this._len;) {
  9611. var cmd = data[i++];
  9612. var isFirst = i === 1;
  9613. if (isFirst) {
  9614. xi = data[i];
  9615. yi = data[i + 1];
  9616. x0 = xi;
  9617. y0 = yi;
  9618. }
  9619. switch (cmd) {
  9620. case CMD.M:
  9621. xi = x0 = data[i++];
  9622. yi = y0 = data[i++];
  9623. min2[0] = x0;
  9624. min2[1] = y0;
  9625. max2[0] = x0;
  9626. max2[1] = y0;
  9627. break;
  9628. case CMD.L:
  9629. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9630. xi = data[i++];
  9631. yi = data[i++];
  9632. break;
  9633. case CMD.C:
  9634. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9635. xi = data[i++];
  9636. yi = data[i++];
  9637. break;
  9638. case CMD.Q:
  9639. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9640. xi = data[i++];
  9641. yi = data[i++];
  9642. break;
  9643. case CMD.A:
  9644. var cx = data[i++];
  9645. var cy = data[i++];
  9646. var rx = data[i++];
  9647. var ry = data[i++];
  9648. var startAngle = data[i++];
  9649. var endAngle = data[i++] + startAngle;
  9650. i += 1;
  9651. var anticlockwise = !data[i++];
  9652. if (isFirst) {
  9653. x0 = mathCos$1(startAngle) * rx + cx;
  9654. y0 = mathSin$1(startAngle) * ry + cy;
  9655. }
  9656. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9657. xi = mathCos$1(endAngle) * rx + cx;
  9658. yi = mathSin$1(endAngle) * ry + cy;
  9659. break;
  9660. case CMD.R:
  9661. x0 = xi = data[i++];
  9662. y0 = yi = data[i++];
  9663. var width = data[i++];
  9664. var height = data[i++];
  9665. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9666. break;
  9667. case CMD.Z:
  9668. xi = x0;
  9669. yi = y0;
  9670. break;
  9671. }
  9672. min(min$1, min$1, min2);
  9673. max(max$1, max$1, max2);
  9674. }
  9675. if (i === 0) {
  9676. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9677. }
  9678. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9679. };
  9680. PathProxy.prototype._calculateLength = function () {
  9681. var data = this.data;
  9682. var len = this._len;
  9683. var ux = this._ux;
  9684. var uy = this._uy;
  9685. var xi = 0;
  9686. var yi = 0;
  9687. var x0 = 0;
  9688. var y0 = 0;
  9689. if (!this._pathSegLen) {
  9690. this._pathSegLen = [];
  9691. }
  9692. var pathSegLen = this._pathSegLen;
  9693. var pathTotalLen = 0;
  9694. var segCount = 0;
  9695. for (var i = 0; i < len;) {
  9696. var cmd = data[i++];
  9697. var isFirst = i === 1;
  9698. if (isFirst) {
  9699. xi = data[i];
  9700. yi = data[i + 1];
  9701. x0 = xi;
  9702. y0 = yi;
  9703. }
  9704. var l = -1;
  9705. switch (cmd) {
  9706. case CMD.M:
  9707. xi = x0 = data[i++];
  9708. yi = y0 = data[i++];
  9709. break;
  9710. case CMD.L: {
  9711. var x2 = data[i++];
  9712. var y2 = data[i++];
  9713. var dx = x2 - xi;
  9714. var dy = y2 - yi;
  9715. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  9716. l = Math.sqrt(dx * dx + dy * dy);
  9717. xi = x2;
  9718. yi = y2;
  9719. }
  9720. break;
  9721. }
  9722. case CMD.C: {
  9723. var x1 = data[i++];
  9724. var y1 = data[i++];
  9725. var x2 = data[i++];
  9726. var y2 = data[i++];
  9727. var x3 = data[i++];
  9728. var y3 = data[i++];
  9729. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  9730. xi = x3;
  9731. yi = y3;
  9732. break;
  9733. }
  9734. case CMD.Q: {
  9735. var x1 = data[i++];
  9736. var y1 = data[i++];
  9737. var x2 = data[i++];
  9738. var y2 = data[i++];
  9739. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  9740. xi = x2;
  9741. yi = y2;
  9742. break;
  9743. }
  9744. case CMD.A:
  9745. var cx = data[i++];
  9746. var cy = data[i++];
  9747. var rx = data[i++];
  9748. var ry = data[i++];
  9749. var startAngle = data[i++];
  9750. var delta = data[i++];
  9751. var endAngle = delta + startAngle;
  9752. i += 1;
  9753. var anticlockwise = !data[i++];
  9754. if (isFirst) {
  9755. x0 = mathCos$1(startAngle) * rx + cx;
  9756. y0 = mathSin$1(startAngle) * ry + cy;
  9757. }
  9758. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  9759. xi = mathCos$1(endAngle) * rx + cx;
  9760. yi = mathSin$1(endAngle) * ry + cy;
  9761. break;
  9762. case CMD.R: {
  9763. x0 = xi = data[i++];
  9764. y0 = yi = data[i++];
  9765. var width = data[i++];
  9766. var height = data[i++];
  9767. l = width * 2 + height * 2;
  9768. break;
  9769. }
  9770. case CMD.Z: {
  9771. var dx = x0 - xi;
  9772. var dy = y0 - yi;
  9773. l = Math.sqrt(dx * dx + dy * dy);
  9774. xi = x0;
  9775. yi = y0;
  9776. break;
  9777. }
  9778. }
  9779. if (l >= 0) {
  9780. pathSegLen[segCount++] = l;
  9781. pathTotalLen += l;
  9782. }
  9783. }
  9784. this._pathLen = pathTotalLen;
  9785. return pathTotalLen;
  9786. };
  9787. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  9788. var d = this.data;
  9789. var ux = this._ux;
  9790. var uy = this._uy;
  9791. var len = this._len;
  9792. var x0;
  9793. var y0;
  9794. var xi;
  9795. var yi;
  9796. var x;
  9797. var y;
  9798. var drawPart = percent < 1;
  9799. var pathSegLen;
  9800. var pathTotalLen;
  9801. var accumLength = 0;
  9802. var segCount = 0;
  9803. var displayedLength;
  9804. if (drawPart) {
  9805. if (!this._pathSegLen) {
  9806. this._calculateLength();
  9807. }
  9808. pathSegLen = this._pathSegLen;
  9809. pathTotalLen = this._pathLen;
  9810. displayedLength = percent * pathTotalLen;
  9811. if (!displayedLength) {
  9812. return;
  9813. }
  9814. }
  9815. lo: for (var i = 0; i < len;) {
  9816. var cmd = d[i++];
  9817. var isFirst = i === 1;
  9818. if (isFirst) {
  9819. xi = d[i];
  9820. yi = d[i + 1];
  9821. x0 = xi;
  9822. y0 = yi;
  9823. }
  9824. switch (cmd) {
  9825. case CMD.M:
  9826. x0 = xi = d[i++];
  9827. y0 = yi = d[i++];
  9828. ctx.moveTo(xi, yi);
  9829. break;
  9830. case CMD.L: {
  9831. x = d[i++];
  9832. y = d[i++];
  9833. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len - 1) {
  9834. if (drawPart) {
  9835. var l = pathSegLen[segCount++];
  9836. if (accumLength + l > displayedLength) {
  9837. var t = (displayedLength - accumLength) / l;
  9838. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  9839. break lo;
  9840. }
  9841. accumLength += l;
  9842. }
  9843. ctx.lineTo(x, y);
  9844. xi = x;
  9845. yi = y;
  9846. }
  9847. break;
  9848. }
  9849. case CMD.C: {
  9850. var x1 = d[i++];
  9851. var y1 = d[i++];
  9852. var x2 = d[i++];
  9853. var y2 = d[i++];
  9854. var x3 = d[i++];
  9855. var y3 = d[i++];
  9856. if (drawPart) {
  9857. var l = pathSegLen[segCount++];
  9858. if (accumLength + l > displayedLength) {
  9859. var t = (displayedLength - accumLength) / l;
  9860. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  9861. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  9862. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  9863. break lo;
  9864. }
  9865. accumLength += l;
  9866. }
  9867. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9868. xi = x3;
  9869. yi = y3;
  9870. break;
  9871. }
  9872. case CMD.Q: {
  9873. var x1 = d[i++];
  9874. var y1 = d[i++];
  9875. var x2 = d[i++];
  9876. var y2 = d[i++];
  9877. if (drawPart) {
  9878. var l = pathSegLen[segCount++];
  9879. if (accumLength + l > displayedLength) {
  9880. var t = (displayedLength - accumLength) / l;
  9881. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  9882. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  9883. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  9884. break lo;
  9885. }
  9886. accumLength += l;
  9887. }
  9888. ctx.quadraticCurveTo(x1, y1, x2, y2);
  9889. xi = x2;
  9890. yi = y2;
  9891. break;
  9892. }
  9893. case CMD.A:
  9894. var cx = d[i++];
  9895. var cy = d[i++];
  9896. var rx = d[i++];
  9897. var ry = d[i++];
  9898. var startAngle = d[i++];
  9899. var delta = d[i++];
  9900. var psi = d[i++];
  9901. var anticlockwise = !d[i++];
  9902. var r = (rx > ry) ? rx : ry;
  9903. var isEllipse = mathAbs(rx - ry) > 1e-3;
  9904. var endAngle = startAngle + delta;
  9905. var breakBuild = false;
  9906. if (drawPart) {
  9907. var l = pathSegLen[segCount++];
  9908. if (accumLength + l > displayedLength) {
  9909. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  9910. breakBuild = true;
  9911. }
  9912. accumLength += l;
  9913. }
  9914. if (isEllipse && ctx.ellipse) {
  9915. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  9916. }
  9917. else {
  9918. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9919. }
  9920. if (breakBuild) {
  9921. break lo;
  9922. }
  9923. if (isFirst) {
  9924. x0 = mathCos$1(startAngle) * rx + cx;
  9925. y0 = mathSin$1(startAngle) * ry + cy;
  9926. }
  9927. xi = mathCos$1(endAngle) * rx + cx;
  9928. yi = mathSin$1(endAngle) * ry + cy;
  9929. break;
  9930. case CMD.R:
  9931. x0 = xi = d[i];
  9932. y0 = yi = d[i + 1];
  9933. x = d[i++];
  9934. y = d[i++];
  9935. var width = d[i++];
  9936. var height = d[i++];
  9937. if (drawPart) {
  9938. var l = pathSegLen[segCount++];
  9939. if (accumLength + l > displayedLength) {
  9940. var d_1 = displayedLength - accumLength;
  9941. ctx.moveTo(x, y);
  9942. ctx.lineTo(x + mathMin$2(d_1, width), y);
  9943. d_1 -= width;
  9944. if (d_1 > 0) {
  9945. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  9946. }
  9947. d_1 -= height;
  9948. if (d_1 > 0) {
  9949. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  9950. }
  9951. d_1 -= width;
  9952. if (d_1 > 0) {
  9953. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  9954. }
  9955. break lo;
  9956. }
  9957. accumLength += l;
  9958. }
  9959. ctx.rect(x, y, width, height);
  9960. break;
  9961. case CMD.Z:
  9962. if (drawPart) {
  9963. var l = pathSegLen[segCount++];
  9964. if (accumLength + l > displayedLength) {
  9965. var t = (displayedLength - accumLength) / l;
  9966. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  9967. break lo;
  9968. }
  9969. accumLength += l;
  9970. }
  9971. ctx.closePath();
  9972. xi = x0;
  9973. yi = y0;
  9974. }
  9975. }
  9976. };
  9977. PathProxy.CMD = CMD;
  9978. PathProxy.initDefaultProps = (function () {
  9979. var proto = PathProxy.prototype;
  9980. proto._saveData = true;
  9981. proto._needsDash = false;
  9982. proto._dashOffset = 0;
  9983. proto._dashIdx = 0;
  9984. proto._dashSum = 0;
  9985. proto._ux = 0;
  9986. proto._uy = 0;
  9987. })();
  9988. return PathProxy;
  9989. }());
  9990. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  9991. if (lineWidth === 0) {
  9992. return false;
  9993. }
  9994. var _l = lineWidth;
  9995. var _a = 0;
  9996. var _b = x0;
  9997. if ((y > y0 + _l && y > y1 + _l)
  9998. || (y < y0 - _l && y < y1 - _l)
  9999. || (x > x0 + _l && x > x1 + _l)
  10000. || (x < x0 - _l && x < x1 - _l)) {
  10001. return false;
  10002. }
  10003. if (x0 !== x1) {
  10004. _a = (y0 - y1) / (x0 - x1);
  10005. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10006. }
  10007. else {
  10008. return Math.abs(x - x0) <= _l / 2;
  10009. }
  10010. var tmp = _a * x - y + _b;
  10011. var _s = tmp * tmp / (_a * _a + 1);
  10012. return _s <= _l / 2 * _l / 2;
  10013. }
  10014. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10015. if (lineWidth === 0) {
  10016. return false;
  10017. }
  10018. var _l = lineWidth;
  10019. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10020. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10021. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10022. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10023. return false;
  10024. }
  10025. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10026. return d <= _l / 2;
  10027. }
  10028. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10029. if (lineWidth === 0) {
  10030. return false;
  10031. }
  10032. var _l = lineWidth;
  10033. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10034. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10035. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10036. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10037. return false;
  10038. }
  10039. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10040. return d <= _l / 2;
  10041. }
  10042. var PI2$2 = Math.PI * 2;
  10043. function normalizeRadian(angle) {
  10044. angle %= PI2$2;
  10045. if (angle < 0) {
  10046. angle += PI2$2;
  10047. }
  10048. return angle;
  10049. }
  10050. var PI2$3 = Math.PI * 2;
  10051. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10052. if (lineWidth === 0) {
  10053. return false;
  10054. }
  10055. var _l = lineWidth;
  10056. x -= cx;
  10057. y -= cy;
  10058. var d = Math.sqrt(x * x + y * y);
  10059. if ((d - _l > r) || (d + _l < r)) {
  10060. return false;
  10061. }
  10062. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10063. return true;
  10064. }
  10065. if (anticlockwise) {
  10066. var tmp = startAngle;
  10067. startAngle = normalizeRadian(endAngle);
  10068. endAngle = normalizeRadian(tmp);
  10069. }
  10070. else {
  10071. startAngle = normalizeRadian(startAngle);
  10072. endAngle = normalizeRadian(endAngle);
  10073. }
  10074. if (startAngle > endAngle) {
  10075. endAngle += PI2$3;
  10076. }
  10077. var angle = Math.atan2(y, x);
  10078. if (angle < 0) {
  10079. angle += PI2$3;
  10080. }
  10081. return (angle >= startAngle && angle <= endAngle)
  10082. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10083. }
  10084. function windingLine(x0, y0, x1, y1, x, y) {
  10085. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10086. return 0;
  10087. }
  10088. if (y1 === y0) {
  10089. return 0;
  10090. }
  10091. var t = (y - y0) / (y1 - y0);
  10092. var dir = y1 < y0 ? 1 : -1;
  10093. if (t === 1 || t === 0) {
  10094. dir = y1 < y0 ? 0.5 : -0.5;
  10095. }
  10096. var x_ = t * (x1 - x0) + x0;
  10097. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10098. }
  10099. var CMD$1 = PathProxy.CMD;
  10100. var PI2$4 = Math.PI * 2;
  10101. var EPSILON$2 = 1e-4;
  10102. function isAroundEqual(a, b) {
  10103. return Math.abs(a - b) < EPSILON$2;
  10104. }
  10105. var roots = [-1, -1, -1];
  10106. var extrema = [-1, -1];
  10107. function swapExtrema() {
  10108. var tmp = extrema[0];
  10109. extrema[0] = extrema[1];
  10110. extrema[1] = tmp;
  10111. }
  10112. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10113. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10114. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10115. return 0;
  10116. }
  10117. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10118. if (nRoots === 0) {
  10119. return 0;
  10120. }
  10121. else {
  10122. var w = 0;
  10123. var nExtrema = -1;
  10124. var y0_ = void 0;
  10125. var y1_ = void 0;
  10126. for (var i = 0; i < nRoots; i++) {
  10127. var t = roots[i];
  10128. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10129. var x_ = cubicAt(x0, x1, x2, x3, t);
  10130. if (x_ < x) {
  10131. continue;
  10132. }
  10133. if (nExtrema < 0) {
  10134. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10135. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10136. swapExtrema();
  10137. }
  10138. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10139. if (nExtrema > 1) {
  10140. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10141. }
  10142. }
  10143. if (nExtrema === 2) {
  10144. if (t < extrema[0]) {
  10145. w += y0_ < y0 ? unit : -unit;
  10146. }
  10147. else if (t < extrema[1]) {
  10148. w += y1_ < y0_ ? unit : -unit;
  10149. }
  10150. else {
  10151. w += y3 < y1_ ? unit : -unit;
  10152. }
  10153. }
  10154. else {
  10155. if (t < extrema[0]) {
  10156. w += y0_ < y0 ? unit : -unit;
  10157. }
  10158. else {
  10159. w += y3 < y0_ ? unit : -unit;
  10160. }
  10161. }
  10162. }
  10163. return w;
  10164. }
  10165. }
  10166. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10167. if ((y > y0 && y > y1 && y > y2)
  10168. || (y < y0 && y < y1 && y < y2)) {
  10169. return 0;
  10170. }
  10171. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10172. if (nRoots === 0) {
  10173. return 0;
  10174. }
  10175. else {
  10176. var t = quadraticExtremum(y0, y1, y2);
  10177. if (t >= 0 && t <= 1) {
  10178. var w = 0;
  10179. var y_ = quadraticAt(y0, y1, y2, t);
  10180. for (var i = 0; i < nRoots; i++) {
  10181. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10182. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10183. if (x_ < x) {
  10184. continue;
  10185. }
  10186. if (roots[i] < t) {
  10187. w += y_ < y0 ? unit : -unit;
  10188. }
  10189. else {
  10190. w += y2 < y_ ? unit : -unit;
  10191. }
  10192. }
  10193. return w;
  10194. }
  10195. else {
  10196. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10197. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10198. if (x_ < x) {
  10199. return 0;
  10200. }
  10201. return y2 < y0 ? unit : -unit;
  10202. }
  10203. }
  10204. }
  10205. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10206. y -= cy;
  10207. if (y > r || y < -r) {
  10208. return 0;
  10209. }
  10210. var tmp = Math.sqrt(r * r - y * y);
  10211. roots[0] = -tmp;
  10212. roots[1] = tmp;
  10213. var dTheta = Math.abs(startAngle - endAngle);
  10214. if (dTheta < 1e-4) {
  10215. return 0;
  10216. }
  10217. if (dTheta >= PI2$4 - 1e-4) {
  10218. startAngle = 0;
  10219. endAngle = PI2$4;
  10220. var dir = anticlockwise ? 1 : -1;
  10221. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10222. return dir;
  10223. }
  10224. else {
  10225. return 0;
  10226. }
  10227. }
  10228. if (startAngle > endAngle) {
  10229. var tmp_1 = startAngle;
  10230. startAngle = endAngle;
  10231. endAngle = tmp_1;
  10232. }
  10233. if (startAngle < 0) {
  10234. startAngle += PI2$4;
  10235. endAngle += PI2$4;
  10236. }
  10237. var w = 0;
  10238. for (var i = 0; i < 2; i++) {
  10239. var x_ = roots[i];
  10240. if (x_ + cx > x) {
  10241. var angle = Math.atan2(y, x_);
  10242. var dir = anticlockwise ? 1 : -1;
  10243. if (angle < 0) {
  10244. angle = PI2$4 + angle;
  10245. }
  10246. if ((angle >= startAngle && angle <= endAngle)
  10247. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10248. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10249. dir = -dir;
  10250. }
  10251. w += dir;
  10252. }
  10253. }
  10254. }
  10255. return w;
  10256. }
  10257. function containPath(path, lineWidth, isStroke, x, y) {
  10258. var data = path.data;
  10259. var len = path.len();
  10260. var w = 0;
  10261. var xi = 0;
  10262. var yi = 0;
  10263. var x0 = 0;
  10264. var y0 = 0;
  10265. var x1;
  10266. var y1;
  10267. for (var i = 0; i < len;) {
  10268. var cmd = data[i++];
  10269. var isFirst = i === 1;
  10270. if (cmd === CMD$1.M && i > 1) {
  10271. if (!isStroke) {
  10272. w += windingLine(xi, yi, x0, y0, x, y);
  10273. }
  10274. }
  10275. if (isFirst) {
  10276. xi = data[i];
  10277. yi = data[i + 1];
  10278. x0 = xi;
  10279. y0 = yi;
  10280. }
  10281. switch (cmd) {
  10282. case CMD$1.M:
  10283. x0 = data[i++];
  10284. y0 = data[i++];
  10285. xi = x0;
  10286. yi = y0;
  10287. break;
  10288. case CMD$1.L:
  10289. if (isStroke) {
  10290. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10291. return true;
  10292. }
  10293. }
  10294. else {
  10295. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10296. }
  10297. xi = data[i++];
  10298. yi = data[i++];
  10299. break;
  10300. case CMD$1.C:
  10301. if (isStroke) {
  10302. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10303. return true;
  10304. }
  10305. }
  10306. else {
  10307. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10308. }
  10309. xi = data[i++];
  10310. yi = data[i++];
  10311. break;
  10312. case CMD$1.Q:
  10313. if (isStroke) {
  10314. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10315. return true;
  10316. }
  10317. }
  10318. else {
  10319. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10320. }
  10321. xi = data[i++];
  10322. yi = data[i++];
  10323. break;
  10324. case CMD$1.A:
  10325. var cx = data[i++];
  10326. var cy = data[i++];
  10327. var rx = data[i++];
  10328. var ry = data[i++];
  10329. var theta = data[i++];
  10330. var dTheta = data[i++];
  10331. i += 1;
  10332. var anticlockwise = !!(1 - data[i++]);
  10333. x1 = Math.cos(theta) * rx + cx;
  10334. y1 = Math.sin(theta) * ry + cy;
  10335. if (!isFirst) {
  10336. w += windingLine(xi, yi, x1, y1, x, y);
  10337. }
  10338. else {
  10339. x0 = x1;
  10340. y0 = y1;
  10341. }
  10342. var _x = (x - cx) * ry / rx + cx;
  10343. if (isStroke) {
  10344. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10345. return true;
  10346. }
  10347. }
  10348. else {
  10349. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10350. }
  10351. xi = Math.cos(theta + dTheta) * rx + cx;
  10352. yi = Math.sin(theta + dTheta) * ry + cy;
  10353. break;
  10354. case CMD$1.R:
  10355. x0 = xi = data[i++];
  10356. y0 = yi = data[i++];
  10357. var width = data[i++];
  10358. var height = data[i++];
  10359. x1 = x0 + width;
  10360. y1 = y0 + height;
  10361. if (isStroke) {
  10362. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10363. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10364. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10365. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10366. return true;
  10367. }
  10368. }
  10369. else {
  10370. w += windingLine(x1, y0, x1, y1, x, y);
  10371. w += windingLine(x0, y1, x0, y0, x, y);
  10372. }
  10373. break;
  10374. case CMD$1.Z:
  10375. if (isStroke) {
  10376. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10377. return true;
  10378. }
  10379. }
  10380. else {
  10381. w += windingLine(xi, yi, x0, y0, x, y);
  10382. }
  10383. xi = x0;
  10384. yi = y0;
  10385. break;
  10386. }
  10387. }
  10388. if (!isStroke && !isAroundEqual(yi, y0)) {
  10389. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10390. }
  10391. return w !== 0;
  10392. }
  10393. function contain(pathProxy, x, y) {
  10394. return containPath(pathProxy, 0, false, x, y);
  10395. }
  10396. function containStroke$4(pathProxy, lineWidth, x, y) {
  10397. return containPath(pathProxy, lineWidth, true, x, y);
  10398. }
  10399. var DEFAULT_PATH_STYLE = defaults({
  10400. fill: '#000',
  10401. stroke: null,
  10402. strokePercent: 1,
  10403. fillOpacity: 1,
  10404. strokeOpacity: 1,
  10405. lineDashOffset: 0,
  10406. lineWidth: 1,
  10407. lineCap: 'butt',
  10408. miterLimit: 10,
  10409. strokeNoScale: false,
  10410. strokeFirst: false
  10411. }, DEFAULT_COMMON_STYLE);
  10412. var DEFAULT_PATH_ANIMATION_PROPS = {
  10413. style: defaults({
  10414. fill: true,
  10415. stroke: true,
  10416. strokePercent: true,
  10417. fillOpacity: true,
  10418. strokeOpacity: true,
  10419. lineDashOffset: true,
  10420. lineWidth: true,
  10421. miterLimit: true
  10422. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10423. };
  10424. var pathCopyParams = [
  10425. 'x', 'y', 'rotation', 'scaleX', 'scaleY', 'originX', 'originY', 'invisible',
  10426. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10427. ];
  10428. var Path = (function (_super) {
  10429. __extends(Path, _super);
  10430. function Path(opts) {
  10431. return _super.call(this, opts) || this;
  10432. }
  10433. Path.prototype.update = function () {
  10434. var _this = this;
  10435. _super.prototype.update.call(this);
  10436. var style = this.style;
  10437. if (style.decal) {
  10438. var decalEl = this._decalEl
  10439. = this._decalEl || new Path();
  10440. if (decalEl.buildPath === Path.prototype.buildPath) {
  10441. decalEl.buildPath = function (ctx) {
  10442. _this.buildPath(ctx, _this.shape);
  10443. };
  10444. }
  10445. decalEl.silent = true;
  10446. var decalElStyle = decalEl.style;
  10447. for (var key in style) {
  10448. if (decalElStyle[key] !== style[key]) {
  10449. decalElStyle[key] = style[key];
  10450. }
  10451. }
  10452. decalElStyle.fill = style.fill ? style.decal : null;
  10453. decalElStyle.decal = null;
  10454. decalElStyle.shadowColor = null;
  10455. style.strokeFirst && (decalElStyle.stroke = null);
  10456. for (var i = 0; i < pathCopyParams.length; ++i) {
  10457. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10458. }
  10459. decalEl.__dirty |= Element.REDARAW_BIT;
  10460. }
  10461. else if (this._decalEl) {
  10462. this._decalEl = null;
  10463. }
  10464. };
  10465. Path.prototype.getDecalElement = function () {
  10466. return this._decalEl;
  10467. };
  10468. Path.prototype._init = function (props) {
  10469. var keysArr = keys(props);
  10470. this.shape = this.getDefaultShape();
  10471. var defaultStyle = this.getDefaultStyle();
  10472. if (defaultStyle) {
  10473. this.useStyle(defaultStyle);
  10474. }
  10475. for (var i = 0; i < keysArr.length; i++) {
  10476. var key = keysArr[i];
  10477. var value = props[key];
  10478. if (key === 'style') {
  10479. if (!this.style) {
  10480. this.useStyle(value);
  10481. }
  10482. else {
  10483. extend(this.style, value);
  10484. }
  10485. }
  10486. else if (key === 'shape') {
  10487. extend(this.shape, value);
  10488. }
  10489. else {
  10490. _super.prototype.attrKV.call(this, key, value);
  10491. }
  10492. }
  10493. if (!this.style) {
  10494. this.useStyle({});
  10495. }
  10496. };
  10497. Path.prototype.getDefaultStyle = function () {
  10498. return null;
  10499. };
  10500. Path.prototype.getDefaultShape = function () {
  10501. return {};
  10502. };
  10503. Path.prototype.canBeInsideText = function () {
  10504. return this.hasFill();
  10505. };
  10506. Path.prototype.getInsideTextFill = function () {
  10507. var pathFill = this.style.fill;
  10508. if (pathFill !== 'none') {
  10509. if (isString(pathFill)) {
  10510. var fillLum = lum(pathFill, 0);
  10511. if (fillLum > 0.5) {
  10512. return DARK_LABEL_COLOR;
  10513. }
  10514. else if (fillLum > 0.2) {
  10515. return LIGHTER_LABEL_COLOR;
  10516. }
  10517. return LIGHT_LABEL_COLOR;
  10518. }
  10519. else if (pathFill) {
  10520. return LIGHT_LABEL_COLOR;
  10521. }
  10522. }
  10523. return DARK_LABEL_COLOR;
  10524. };
  10525. Path.prototype.getInsideTextStroke = function (textFill) {
  10526. var pathFill = this.style.fill;
  10527. if (isString(pathFill)) {
  10528. var zr = this.__zr;
  10529. var isDarkMode = !!(zr && zr.isDarkMode());
  10530. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10531. if (isDarkMode === isDarkLabel) {
  10532. return pathFill;
  10533. }
  10534. }
  10535. };
  10536. Path.prototype.buildPath = function (ctx, shapeCfg, inBundle) { };
  10537. Path.prototype.pathUpdated = function () {
  10538. this.__dirty &= ~Path.SHAPE_CHANGED_BIT;
  10539. };
  10540. Path.prototype.createPathProxy = function () {
  10541. this.path = new PathProxy(false);
  10542. };
  10543. Path.prototype.hasStroke = function () {
  10544. var style = this.style;
  10545. var stroke = style.stroke;
  10546. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10547. };
  10548. Path.prototype.hasFill = function () {
  10549. var style = this.style;
  10550. var fill = style.fill;
  10551. return fill != null && fill !== 'none';
  10552. };
  10553. Path.prototype.getBoundingRect = function () {
  10554. var rect = this._rect;
  10555. var style = this.style;
  10556. var needsUpdateRect = !rect;
  10557. if (needsUpdateRect) {
  10558. var firstInvoke = false;
  10559. if (!this.path) {
  10560. firstInvoke = true;
  10561. this.createPathProxy();
  10562. }
  10563. var path = this.path;
  10564. if (firstInvoke || (this.__dirty & Path.SHAPE_CHANGED_BIT)) {
  10565. path.beginPath();
  10566. this.buildPath(path, this.shape, false);
  10567. this.pathUpdated();
  10568. }
  10569. rect = path.getBoundingRect();
  10570. }
  10571. this._rect = rect;
  10572. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10573. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  10574. if (this.__dirty || needsUpdateRect) {
  10575. rectWithStroke.copy(rect);
  10576. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10577. var w = style.lineWidth;
  10578. if (!this.hasFill()) {
  10579. var strokeContainThreshold = this.strokeContainThreshold;
  10580. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10581. }
  10582. if (lineScale > 1e-10) {
  10583. rectWithStroke.width += w / lineScale;
  10584. rectWithStroke.height += w / lineScale;
  10585. rectWithStroke.x -= w / lineScale / 2;
  10586. rectWithStroke.y -= w / lineScale / 2;
  10587. }
  10588. }
  10589. return rectWithStroke;
  10590. }
  10591. return rect;
  10592. };
  10593. Path.prototype.contain = function (x, y) {
  10594. var localPos = this.transformCoordToLocal(x, y);
  10595. var rect = this.getBoundingRect();
  10596. var style = this.style;
  10597. x = localPos[0];
  10598. y = localPos[1];
  10599. if (rect.contain(x, y)) {
  10600. var pathProxy = this.path;
  10601. if (this.hasStroke()) {
  10602. var lineWidth = style.lineWidth;
  10603. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10604. if (lineScale > 1e-10) {
  10605. if (!this.hasFill()) {
  10606. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10607. }
  10608. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10609. return true;
  10610. }
  10611. }
  10612. }
  10613. if (this.hasFill()) {
  10614. return contain(pathProxy, x, y);
  10615. }
  10616. }
  10617. return false;
  10618. };
  10619. Path.prototype.dirtyShape = function () {
  10620. this.__dirty |= Path.SHAPE_CHANGED_BIT;
  10621. if (this._rect) {
  10622. this._rect = null;
  10623. }
  10624. if (this._decalEl) {
  10625. this._decalEl.dirtyShape();
  10626. }
  10627. this.markRedraw();
  10628. };
  10629. Path.prototype.dirty = function () {
  10630. this.dirtyStyle();
  10631. this.dirtyShape();
  10632. };
  10633. Path.prototype.animateShape = function (loop) {
  10634. return this.animate('shape', loop);
  10635. };
  10636. Path.prototype.updateDuringAnimation = function (targetKey) {
  10637. if (targetKey === 'style') {
  10638. this.dirtyStyle();
  10639. }
  10640. else if (targetKey === 'shape') {
  10641. this.dirtyShape();
  10642. }
  10643. else {
  10644. this.markRedraw();
  10645. }
  10646. };
  10647. Path.prototype.attrKV = function (key, value) {
  10648. if (key === 'shape') {
  10649. this.setShape(value);
  10650. }
  10651. else {
  10652. _super.prototype.attrKV.call(this, key, value);
  10653. }
  10654. };
  10655. Path.prototype.setShape = function (keyOrObj, value) {
  10656. var shape = this.shape;
  10657. if (!shape) {
  10658. shape = this.shape = {};
  10659. }
  10660. if (typeof keyOrObj === 'string') {
  10661. shape[keyOrObj] = value;
  10662. }
  10663. else {
  10664. extend(shape, keyOrObj);
  10665. }
  10666. this.dirtyShape();
  10667. return this;
  10668. };
  10669. Path.prototype.shapeChanged = function () {
  10670. return !!(this.__dirty & Path.SHAPE_CHANGED_BIT);
  10671. };
  10672. Path.prototype.createStyle = function (obj) {
  10673. return createObject(DEFAULT_PATH_STYLE, obj);
  10674. };
  10675. Path.prototype._innerSaveToNormal = function (toState) {
  10676. _super.prototype._innerSaveToNormal.call(this, toState);
  10677. var normalState = this._normalState;
  10678. if (toState.shape && !normalState.shape) {
  10679. normalState.shape = extend({}, this.shape);
  10680. }
  10681. };
  10682. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10683. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10684. var needsRestoreToNormal = !(state && keepCurrentStates);
  10685. var targetShape;
  10686. if (state && state.shape) {
  10687. if (transition) {
  10688. if (keepCurrentStates) {
  10689. targetShape = state.shape;
  10690. }
  10691. else {
  10692. targetShape = extend({}, normalState.shape);
  10693. extend(targetShape, state.shape);
  10694. }
  10695. }
  10696. else {
  10697. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  10698. extend(targetShape, state.shape);
  10699. }
  10700. }
  10701. else if (needsRestoreToNormal) {
  10702. targetShape = normalState.shape;
  10703. }
  10704. if (targetShape) {
  10705. if (transition) {
  10706. this.shape = extend({}, this.shape);
  10707. var targetShapePrimaryProps = {};
  10708. var shapeKeys = keys(targetShape);
  10709. for (var i = 0; i < shapeKeys.length; i++) {
  10710. var key = shapeKeys[i];
  10711. if (typeof targetShape[key] === 'object') {
  10712. this.shape[key] = targetShape[key];
  10713. }
  10714. else {
  10715. targetShapePrimaryProps[key] = targetShape[key];
  10716. }
  10717. }
  10718. this._transitionState(stateName, {
  10719. shape: targetShapePrimaryProps
  10720. }, animationCfg);
  10721. }
  10722. else {
  10723. this.shape = targetShape;
  10724. this.dirtyShape();
  10725. }
  10726. }
  10727. };
  10728. Path.prototype._mergeStates = function (states) {
  10729. var mergedState = _super.prototype._mergeStates.call(this, states);
  10730. var mergedShape;
  10731. for (var i = 0; i < states.length; i++) {
  10732. var state = states[i];
  10733. if (state.shape) {
  10734. mergedShape = mergedShape || {};
  10735. this._mergeStyle(mergedShape, state.shape);
  10736. }
  10737. }
  10738. if (mergedShape) {
  10739. mergedState.shape = mergedShape;
  10740. }
  10741. return mergedState;
  10742. };
  10743. Path.prototype.getAnimationStyleProps = function () {
  10744. return DEFAULT_PATH_ANIMATION_PROPS;
  10745. };
  10746. Path.prototype.isZeroArea = function () {
  10747. return false;
  10748. };
  10749. Path.extend = function (defaultProps) {
  10750. var Sub = (function (_super) {
  10751. __extends(Sub, _super);
  10752. function Sub(opts) {
  10753. var _this = _super.call(this, opts) || this;
  10754. defaultProps.init && defaultProps.init.call(_this, opts);
  10755. return _this;
  10756. }
  10757. Sub.prototype.getDefaultStyle = function () {
  10758. return clone(defaultProps.style);
  10759. };
  10760. Sub.prototype.getDefaultShape = function () {
  10761. return clone(defaultProps.shape);
  10762. };
  10763. return Sub;
  10764. }(Path));
  10765. for (var key in defaultProps) {
  10766. if (typeof defaultProps[key] === 'function') {
  10767. Sub.prototype[key] = defaultProps[key];
  10768. }
  10769. }
  10770. return Sub;
  10771. };
  10772. Path.SHAPE_CHANGED_BIT = 4;
  10773. Path.initDefaultProps = (function () {
  10774. var pathProto = Path.prototype;
  10775. pathProto.type = 'path';
  10776. pathProto.strokeContainThreshold = 5;
  10777. pathProto.segmentIgnoreThreshold = 0;
  10778. pathProto.subPixelOptimize = false;
  10779. pathProto.autoBatch = false;
  10780. pathProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT | Path.SHAPE_CHANGED_BIT;
  10781. })();
  10782. return Path;
  10783. }(Displayable));
  10784. var DEFAULT_TSPAN_STYLE = defaults({
  10785. strokeFirst: true,
  10786. font: DEFAULT_FONT,
  10787. x: 0,
  10788. y: 0,
  10789. textAlign: 'left',
  10790. textBaseline: 'top',
  10791. miterLimit: 2
  10792. }, DEFAULT_PATH_STYLE);
  10793. var TSpan = (function (_super) {
  10794. __extends(TSpan, _super);
  10795. function TSpan() {
  10796. return _super !== null && _super.apply(this, arguments) || this;
  10797. }
  10798. TSpan.prototype.hasStroke = function () {
  10799. var style = this.style;
  10800. var stroke = style.stroke;
  10801. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  10802. };
  10803. TSpan.prototype.hasFill = function () {
  10804. var style = this.style;
  10805. var fill = style.fill;
  10806. return fill != null && fill !== 'none';
  10807. };
  10808. TSpan.prototype.createStyle = function (obj) {
  10809. return createObject(DEFAULT_TSPAN_STYLE, obj);
  10810. };
  10811. TSpan.prototype.setBoundingRect = function (rect) {
  10812. this._rect = rect;
  10813. };
  10814. TSpan.prototype.getBoundingRect = function () {
  10815. var style = this.style;
  10816. if (!this._rect) {
  10817. var text = style.text;
  10818. text != null ? (text += '') : (text = '');
  10819. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  10820. rect.x += style.x || 0;
  10821. rect.y += style.y || 0;
  10822. if (this.hasStroke()) {
  10823. var w = style.lineWidth;
  10824. rect.x -= w / 2;
  10825. rect.y -= w / 2;
  10826. rect.width += w;
  10827. rect.height += w;
  10828. }
  10829. this._rect = rect;
  10830. }
  10831. return this._rect;
  10832. };
  10833. TSpan.initDefaultProps = (function () {
  10834. var tspanProto = TSpan.prototype;
  10835. tspanProto.dirtyRectTolerance = 10;
  10836. })();
  10837. return TSpan;
  10838. }(Displayable));
  10839. TSpan.prototype.type = 'tspan';
  10840. var DEFAULT_IMAGE_STYLE = defaults({
  10841. x: 0,
  10842. y: 0
  10843. }, DEFAULT_COMMON_STYLE);
  10844. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  10845. style: defaults({
  10846. x: true,
  10847. y: true,
  10848. width: true,
  10849. height: true,
  10850. sx: true,
  10851. sy: true,
  10852. sWidth: true,
  10853. sHeight: true
  10854. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10855. };
  10856. function isImageLike(source) {
  10857. return !!(source
  10858. && typeof source !== 'string'
  10859. && source.width && source.height);
  10860. }
  10861. var ZRImage = (function (_super) {
  10862. __extends(ZRImage, _super);
  10863. function ZRImage() {
  10864. return _super !== null && _super.apply(this, arguments) || this;
  10865. }
  10866. ZRImage.prototype.createStyle = function (obj) {
  10867. return createObject(DEFAULT_IMAGE_STYLE, obj);
  10868. };
  10869. ZRImage.prototype._getSize = function (dim) {
  10870. var style = this.style;
  10871. var size = style[dim];
  10872. if (size != null) {
  10873. return size;
  10874. }
  10875. var imageSource = isImageLike(style.image)
  10876. ? style.image : this.__image;
  10877. if (!imageSource) {
  10878. return 0;
  10879. }
  10880. var otherDim = dim === 'width' ? 'height' : 'width';
  10881. var otherDimSize = style[otherDim];
  10882. if (otherDimSize == null) {
  10883. return imageSource[dim];
  10884. }
  10885. else {
  10886. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  10887. }
  10888. };
  10889. ZRImage.prototype.getWidth = function () {
  10890. return this._getSize('width');
  10891. };
  10892. ZRImage.prototype.getHeight = function () {
  10893. return this._getSize('height');
  10894. };
  10895. ZRImage.prototype.getAnimationStyleProps = function () {
  10896. return DEFAULT_IMAGE_ANIMATION_PROPS;
  10897. };
  10898. ZRImage.prototype.getBoundingRect = function () {
  10899. var style = this.style;
  10900. if (!this._rect) {
  10901. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  10902. }
  10903. return this._rect;
  10904. };
  10905. return ZRImage;
  10906. }(Displayable));
  10907. ZRImage.prototype.type = 'image';
  10908. function buildPath(ctx, shape) {
  10909. var x = shape.x;
  10910. var y = shape.y;
  10911. var width = shape.width;
  10912. var height = shape.height;
  10913. var r = shape.r;
  10914. var r1;
  10915. var r2;
  10916. var r3;
  10917. var r4;
  10918. if (width < 0) {
  10919. x = x + width;
  10920. width = -width;
  10921. }
  10922. if (height < 0) {
  10923. y = y + height;
  10924. height = -height;
  10925. }
  10926. if (typeof r === 'number') {
  10927. r1 = r2 = r3 = r4 = r;
  10928. }
  10929. else if (r instanceof Array) {
  10930. if (r.length === 1) {
  10931. r1 = r2 = r3 = r4 = r[0];
  10932. }
  10933. else if (r.length === 2) {
  10934. r1 = r3 = r[0];
  10935. r2 = r4 = r[1];
  10936. }
  10937. else if (r.length === 3) {
  10938. r1 = r[0];
  10939. r2 = r4 = r[1];
  10940. r3 = r[2];
  10941. }
  10942. else {
  10943. r1 = r[0];
  10944. r2 = r[1];
  10945. r3 = r[2];
  10946. r4 = r[3];
  10947. }
  10948. }
  10949. else {
  10950. r1 = r2 = r3 = r4 = 0;
  10951. }
  10952. var total;
  10953. if (r1 + r2 > width) {
  10954. total = r1 + r2;
  10955. r1 *= width / total;
  10956. r2 *= width / total;
  10957. }
  10958. if (r3 + r4 > width) {
  10959. total = r3 + r4;
  10960. r3 *= width / total;
  10961. r4 *= width / total;
  10962. }
  10963. if (r2 + r3 > height) {
  10964. total = r2 + r3;
  10965. r2 *= height / total;
  10966. r3 *= height / total;
  10967. }
  10968. if (r1 + r4 > height) {
  10969. total = r1 + r4;
  10970. r1 *= height / total;
  10971. r4 *= height / total;
  10972. }
  10973. ctx.moveTo(x + r1, y);
  10974. ctx.lineTo(x + width - r2, y);
  10975. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  10976. ctx.lineTo(x + width, y + height - r3);
  10977. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  10978. ctx.lineTo(x + r4, y + height);
  10979. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  10980. ctx.lineTo(x, y + r1);
  10981. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  10982. }
  10983. var round$1 = Math.round;
  10984. function subPixelOptimizeLine(outputShape, inputShape, style) {
  10985. if (!inputShape) {
  10986. return;
  10987. }
  10988. var x1 = inputShape.x1;
  10989. var x2 = inputShape.x2;
  10990. var y1 = inputShape.y1;
  10991. var y2 = inputShape.y2;
  10992. outputShape.x1 = x1;
  10993. outputShape.x2 = x2;
  10994. outputShape.y1 = y1;
  10995. outputShape.y2 = y2;
  10996. var lineWidth = style && style.lineWidth;
  10997. if (!lineWidth) {
  10998. return outputShape;
  10999. }
  11000. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11001. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11002. }
  11003. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11004. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11005. }
  11006. return outputShape;
  11007. }
  11008. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11009. if (!inputShape) {
  11010. return;
  11011. }
  11012. var originX = inputShape.x;
  11013. var originY = inputShape.y;
  11014. var originWidth = inputShape.width;
  11015. var originHeight = inputShape.height;
  11016. outputShape.x = originX;
  11017. outputShape.y = originY;
  11018. outputShape.width = originWidth;
  11019. outputShape.height = originHeight;
  11020. var lineWidth = style && style.lineWidth;
  11021. if (!lineWidth) {
  11022. return outputShape;
  11023. }
  11024. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11025. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11026. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11027. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11028. return outputShape;
  11029. }
  11030. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11031. if (!lineWidth) {
  11032. return position;
  11033. }
  11034. var doubledPosition = round$1(position * 2);
  11035. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11036. ? doubledPosition / 2
  11037. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11038. }
  11039. var RectShape = (function () {
  11040. function RectShape() {
  11041. this.x = 0;
  11042. this.y = 0;
  11043. this.width = 0;
  11044. this.height = 0;
  11045. }
  11046. return RectShape;
  11047. }());
  11048. var subPixelOptimizeOutputShape = {};
  11049. var Rect = (function (_super) {
  11050. __extends(Rect, _super);
  11051. function Rect(opts) {
  11052. return _super.call(this, opts) || this;
  11053. }
  11054. Rect.prototype.getDefaultShape = function () {
  11055. return new RectShape();
  11056. };
  11057. Rect.prototype.buildPath = function (ctx, shape) {
  11058. var x;
  11059. var y;
  11060. var width;
  11061. var height;
  11062. if (this.subPixelOptimize) {
  11063. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11064. x = optimizedShape.x;
  11065. y = optimizedShape.y;
  11066. width = optimizedShape.width;
  11067. height = optimizedShape.height;
  11068. optimizedShape.r = shape.r;
  11069. shape = optimizedShape;
  11070. }
  11071. else {
  11072. x = shape.x;
  11073. y = shape.y;
  11074. width = shape.width;
  11075. height = shape.height;
  11076. }
  11077. if (!shape.r) {
  11078. ctx.rect(x, y, width, height);
  11079. }
  11080. else {
  11081. buildPath(ctx, shape);
  11082. }
  11083. };
  11084. Rect.prototype.isZeroArea = function () {
  11085. return !this.shape.width || !this.shape.height;
  11086. };
  11087. return Rect;
  11088. }(Path));
  11089. Rect.prototype.type = 'rect';
  11090. var DEFAULT_RICH_TEXT_COLOR = {
  11091. fill: '#000'
  11092. };
  11093. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11094. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11095. style: defaults({
  11096. fill: true,
  11097. stroke: true,
  11098. fillOpacity: true,
  11099. strokeOpacity: true,
  11100. lineWidth: true,
  11101. fontSize: true,
  11102. lineHeight: true,
  11103. width: true,
  11104. height: true,
  11105. textShadowColor: true,
  11106. textShadowBlur: true,
  11107. textShadowOffsetX: true,
  11108. textShadowOffsetY: true,
  11109. backgroundColor: true,
  11110. padding: true,
  11111. borderColor: true,
  11112. borderWidth: true,
  11113. borderRadius: true
  11114. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11115. };
  11116. var ZRText = (function (_super) {
  11117. __extends(ZRText, _super);
  11118. function ZRText(opts) {
  11119. var _this = _super.call(this) || this;
  11120. _this.type = 'text';
  11121. _this._children = [];
  11122. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11123. _this.attr(opts);
  11124. return _this;
  11125. }
  11126. ZRText.prototype.childrenRef = function () {
  11127. return this._children;
  11128. };
  11129. ZRText.prototype.update = function () {
  11130. if (this.styleChanged()) {
  11131. this._updateSubTexts();
  11132. }
  11133. for (var i = 0; i < this._children.length; i++) {
  11134. var child = this._children[i];
  11135. child.zlevel = this.zlevel;
  11136. child.z = this.z;
  11137. child.z2 = this.z2;
  11138. child.culling = this.culling;
  11139. child.cursor = this.cursor;
  11140. child.invisible = this.invisible;
  11141. }
  11142. var attachedTransform = this.attachedTransform;
  11143. if (attachedTransform) {
  11144. attachedTransform.updateTransform();
  11145. var m = attachedTransform.transform;
  11146. if (m) {
  11147. this.transform = this.transform || [];
  11148. copy$1(this.transform, m);
  11149. }
  11150. else {
  11151. this.transform = null;
  11152. }
  11153. }
  11154. else {
  11155. _super.prototype.update.call(this);
  11156. }
  11157. };
  11158. ZRText.prototype.getComputedTransform = function () {
  11159. if (this.__hostTarget) {
  11160. this.__hostTarget.getComputedTransform();
  11161. this.__hostTarget.updateInnerText(true);
  11162. }
  11163. return this.attachedTransform ? this.attachedTransform.getComputedTransform()
  11164. : _super.prototype.getComputedTransform.call(this);
  11165. };
  11166. ZRText.prototype._updateSubTexts = function () {
  11167. this._childCursor = 0;
  11168. normalizeTextStyle(this.style);
  11169. this.style.rich
  11170. ? this._updateRichTexts()
  11171. : this._updatePlainTexts();
  11172. this._children.length = this._childCursor;
  11173. this.styleUpdated();
  11174. };
  11175. ZRText.prototype.addSelfToZr = function (zr) {
  11176. _super.prototype.addSelfToZr.call(this, zr);
  11177. for (var i = 0; i < this._children.length; i++) {
  11178. this._children[i].__zr = zr;
  11179. }
  11180. };
  11181. ZRText.prototype.removeSelfFromZr = function (zr) {
  11182. _super.prototype.removeSelfFromZr.call(this, zr);
  11183. for (var i = 0; i < this._children.length; i++) {
  11184. this._children[i].__zr = null;
  11185. }
  11186. };
  11187. ZRText.prototype.getBoundingRect = function () {
  11188. if (this.styleChanged()) {
  11189. this._updateSubTexts();
  11190. }
  11191. if (!this._rect) {
  11192. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11193. var children = this._children;
  11194. var tmpMat = [];
  11195. var rect = null;
  11196. for (var i = 0; i < children.length; i++) {
  11197. var child = children[i];
  11198. var childRect = child.getBoundingRect();
  11199. var transform = child.getLocalTransform(tmpMat);
  11200. if (transform) {
  11201. tmpRect.copy(childRect);
  11202. tmpRect.applyTransform(transform);
  11203. rect = rect || tmpRect.clone();
  11204. rect.union(tmpRect);
  11205. }
  11206. else {
  11207. rect = rect || childRect.clone();
  11208. rect.union(childRect);
  11209. }
  11210. }
  11211. this._rect = rect || tmpRect;
  11212. }
  11213. return this._rect;
  11214. };
  11215. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11216. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11217. };
  11218. ZRText.prototype.setTextContent = function (textContent) {
  11219. throw new Error('Can\'t attach text on another text');
  11220. };
  11221. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11222. if (!sourceStyle) {
  11223. return targetStyle;
  11224. }
  11225. var sourceRich = sourceStyle.rich;
  11226. var targetRich = targetStyle.rich || (sourceRich && {});
  11227. extend(targetStyle, sourceStyle);
  11228. if (sourceRich && targetRich) {
  11229. this._mergeRich(targetRich, sourceRich);
  11230. targetStyle.rich = targetRich;
  11231. }
  11232. else if (targetRich) {
  11233. targetStyle.rich = targetRich;
  11234. }
  11235. return targetStyle;
  11236. };
  11237. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11238. var richNames = keys(sourceRich);
  11239. for (var i = 0; i < richNames.length; i++) {
  11240. var richName = richNames[i];
  11241. targetRich[richName] = targetRich[richName] || {};
  11242. extend(targetRich[richName], sourceRich[richName]);
  11243. }
  11244. };
  11245. ZRText.prototype.getAnimationStyleProps = function () {
  11246. return DEFAULT_TEXT_ANIMATION_PROPS;
  11247. };
  11248. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11249. var child = this._children[this._childCursor];
  11250. if (!child || !(child instanceof Ctor)) {
  11251. child = new Ctor();
  11252. }
  11253. this._children[this._childCursor++] = child;
  11254. child.__zr = this.__zr;
  11255. child.parent = this;
  11256. return child;
  11257. };
  11258. ZRText.prototype._updatePlainTexts = function () {
  11259. var style = this.style;
  11260. var textFont = style.font || DEFAULT_FONT;
  11261. var textPadding = style.padding;
  11262. var text = getStyleText(style);
  11263. var contentBlock = parsePlainText(text, style);
  11264. var needDrawBg = needDrawBackground(style);
  11265. var bgColorDrawn = !!(style.backgroundColor);
  11266. var outerHeight = contentBlock.outerHeight;
  11267. var textLines = contentBlock.lines;
  11268. var lineHeight = contentBlock.lineHeight;
  11269. var defaultStyle = this._defaultStyle;
  11270. var baseX = style.x || 0;
  11271. var baseY = style.y || 0;
  11272. var textAlign = style.align || defaultStyle.align || 'left';
  11273. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11274. var textX = baseX;
  11275. var textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign);
  11276. if (needDrawBg || textPadding) {
  11277. var outerWidth_1 = contentBlock.width;
  11278. textPadding && (outerWidth_1 += textPadding[1] + textPadding[3]);
  11279. var boxX = adjustTextX(baseX, outerWidth_1, textAlign);
  11280. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11281. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth_1, outerHeight);
  11282. }
  11283. textY += lineHeight / 2;
  11284. if (textPadding) {
  11285. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11286. if (verticalAlign === 'top') {
  11287. textY += textPadding[0];
  11288. }
  11289. else if (verticalAlign === 'bottom') {
  11290. textY -= textPadding[2];
  11291. }
  11292. }
  11293. var defaultLineWidth = 0;
  11294. var useDefaultFill = false;
  11295. var textFill = getFill('fill' in style
  11296. ? style.fill
  11297. : (useDefaultFill = true, defaultStyle.fill));
  11298. var textStroke = getStroke('stroke' in style
  11299. ? style.stroke
  11300. : (!bgColorDrawn
  11301. && (!defaultStyle.autoStroke || useDefaultFill))
  11302. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11303. : null);
  11304. var hasShadow = style.textShadowBlur > 0;
  11305. var fixedBoundingRect = style.width != null
  11306. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11307. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11308. for (var i = 0; i < textLines.length; i++) {
  11309. var el = this._getOrCreateChild(TSpan);
  11310. var subElStyle = el.createStyle();
  11311. el.useStyle(subElStyle);
  11312. subElStyle.text = textLines[i];
  11313. subElStyle.x = textX;
  11314. subElStyle.y = textY;
  11315. if (textAlign) {
  11316. subElStyle.textAlign = textAlign;
  11317. }
  11318. subElStyle.textBaseline = 'middle';
  11319. subElStyle.opacity = style.opacity;
  11320. subElStyle.strokeFirst = true;
  11321. if (hasShadow) {
  11322. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11323. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11324. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11325. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11326. }
  11327. if (textStroke) {
  11328. subElStyle.stroke = textStroke;
  11329. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11330. subElStyle.lineDash = style.lineDash;
  11331. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11332. }
  11333. if (textFill) {
  11334. subElStyle.fill = textFill;
  11335. }
  11336. subElStyle.font = textFont;
  11337. textY += lineHeight;
  11338. if (fixedBoundingRect) {
  11339. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), style.width, calculatedLineHeight));
  11340. }
  11341. }
  11342. };
  11343. ZRText.prototype._updateRichTexts = function () {
  11344. var style = this.style;
  11345. var text = getStyleText(style);
  11346. var contentBlock = parseRichText(text, style);
  11347. var contentWidth = contentBlock.width;
  11348. var outerWidth = contentBlock.outerWidth;
  11349. var outerHeight = contentBlock.outerHeight;
  11350. var textPadding = style.padding;
  11351. var baseX = style.x || 0;
  11352. var baseY = style.y || 0;
  11353. var defaultStyle = this._defaultStyle;
  11354. var textAlign = style.align || defaultStyle.align;
  11355. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11356. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11357. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11358. var xLeft = boxX;
  11359. var lineTop = boxY;
  11360. if (textPadding) {
  11361. xLeft += textPadding[3];
  11362. lineTop += textPadding[0];
  11363. }
  11364. var xRight = xLeft + contentWidth;
  11365. if (needDrawBackground(style)) {
  11366. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11367. }
  11368. var bgColorDrawn = !!(style.backgroundColor);
  11369. for (var i = 0; i < contentBlock.lines.length; i++) {
  11370. var line = contentBlock.lines[i];
  11371. var tokens = line.tokens;
  11372. var tokenCount = tokens.length;
  11373. var lineHeight = line.lineHeight;
  11374. var remainedWidth = line.width;
  11375. var leftIndex = 0;
  11376. var lineXLeft = xLeft;
  11377. var lineXRight = xRight;
  11378. var rightIndex = tokenCount - 1;
  11379. var token = void 0;
  11380. while (leftIndex < tokenCount
  11381. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11382. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11383. remainedWidth -= token.width;
  11384. lineXLeft += token.width;
  11385. leftIndex++;
  11386. }
  11387. while (rightIndex >= 0
  11388. && (token = tokens[rightIndex], token.align === 'right')) {
  11389. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11390. remainedWidth -= token.width;
  11391. lineXRight -= token.width;
  11392. rightIndex--;
  11393. }
  11394. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11395. while (leftIndex <= rightIndex) {
  11396. token = tokens[leftIndex];
  11397. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11398. lineXLeft += token.width;
  11399. leftIndex++;
  11400. }
  11401. lineTop += lineHeight;
  11402. }
  11403. };
  11404. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11405. var tokenStyle = style.rich[token.styleName] || {};
  11406. tokenStyle.text = token.text;
  11407. var verticalAlign = token.verticalAlign;
  11408. var y = lineTop + lineHeight / 2;
  11409. if (verticalAlign === 'top') {
  11410. y = lineTop + token.height / 2;
  11411. }
  11412. else if (verticalAlign === 'bottom') {
  11413. y = lineTop + lineHeight - token.height / 2;
  11414. }
  11415. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11416. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11417. ? x - token.width
  11418. : textAlign === 'center'
  11419. ? x - token.width / 2
  11420. : x, y - token.height / 2, token.width, token.height);
  11421. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11422. var textPadding = token.textPadding;
  11423. if (textPadding) {
  11424. x = getTextXForPadding(x, textAlign, textPadding);
  11425. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11426. }
  11427. var el = this._getOrCreateChild(TSpan);
  11428. var subElStyle = el.createStyle();
  11429. el.useStyle(subElStyle);
  11430. var defaultStyle = this._defaultStyle;
  11431. var useDefaultFill = false;
  11432. var defaultLineWidth = 0;
  11433. var textFill = getStroke('fill' in tokenStyle ? tokenStyle.fill
  11434. : 'fill' in style ? style.fill
  11435. : (useDefaultFill = true, defaultStyle.fill));
  11436. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11437. : 'stroke' in style ? style.stroke
  11438. : (!bgColorDrawn
  11439. && !parentBgColorDrawn
  11440. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11441. : null);
  11442. var hasShadow = tokenStyle.textShadowBlur > 0
  11443. || style.textShadowBlur > 0;
  11444. subElStyle.text = token.text;
  11445. subElStyle.x = x;
  11446. subElStyle.y = y;
  11447. if (hasShadow) {
  11448. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11449. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11450. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11451. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11452. }
  11453. subElStyle.textAlign = textAlign;
  11454. subElStyle.textBaseline = 'middle';
  11455. subElStyle.font = token.font || DEFAULT_FONT;
  11456. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11457. if (textStroke) {
  11458. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11459. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11460. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11461. subElStyle.stroke = textStroke;
  11462. }
  11463. if (textFill) {
  11464. subElStyle.fill = textFill;
  11465. }
  11466. var textWidth = token.contentWidth;
  11467. var textHeight = token.contentHeight;
  11468. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11469. };
  11470. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11471. var textBackgroundColor = style.backgroundColor;
  11472. var textBorderWidth = style.borderWidth;
  11473. var textBorderColor = style.borderColor;
  11474. var isPlainBg = isString(textBackgroundColor);
  11475. var textBorderRadius = style.borderRadius;
  11476. var self = this;
  11477. var rectEl;
  11478. var imgEl;
  11479. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  11480. rectEl = this._getOrCreateChild(Rect);
  11481. rectEl.useStyle(rectEl.createStyle());
  11482. rectEl.style.fill = null;
  11483. var rectShape = rectEl.shape;
  11484. rectShape.x = x;
  11485. rectShape.y = y;
  11486. rectShape.width = width;
  11487. rectShape.height = height;
  11488. rectShape.r = textBorderRadius;
  11489. rectEl.dirtyShape();
  11490. }
  11491. if (isPlainBg) {
  11492. var rectStyle = rectEl.style;
  11493. rectStyle.fill = textBackgroundColor || null;
  11494. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11495. }
  11496. else if (textBackgroundColor && textBackgroundColor.image) {
  11497. imgEl = this._getOrCreateChild(ZRImage);
  11498. imgEl.onload = function () {
  11499. self.dirtyStyle();
  11500. };
  11501. var imgStyle = imgEl.style;
  11502. imgStyle.image = textBackgroundColor.image;
  11503. imgStyle.x = x;
  11504. imgStyle.y = y;
  11505. imgStyle.width = width;
  11506. imgStyle.height = height;
  11507. }
  11508. if (textBorderWidth && textBorderColor) {
  11509. var rectStyle = rectEl.style;
  11510. rectStyle.lineWidth = textBorderWidth;
  11511. rectStyle.stroke = textBorderColor;
  11512. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11513. rectStyle.lineDash = style.borderDash;
  11514. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11515. rectEl.strokeContainThreshold = 0;
  11516. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11517. rectStyle.strokeFirst = true;
  11518. rectStyle.lineWidth *= 2;
  11519. }
  11520. }
  11521. var commonStyle = (rectEl || imgEl).style;
  11522. commonStyle.shadowBlur = style.shadowBlur || 0;
  11523. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11524. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11525. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11526. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11527. };
  11528. ZRText.makeFont = function (style) {
  11529. var font = '';
  11530. if (style.fontSize || style.fontFamily || style.fontWeight) {
  11531. var fontSize = '';
  11532. if (typeof style.fontSize === 'string'
  11533. && (style.fontSize.indexOf('px') !== -1
  11534. || style.fontSize.indexOf('rem') !== -1
  11535. || style.fontSize.indexOf('em') !== -1)) {
  11536. fontSize = style.fontSize;
  11537. }
  11538. else if (!isNaN(+style.fontSize)) {
  11539. fontSize = style.fontSize + 'px';
  11540. }
  11541. else {
  11542. fontSize = '12px';
  11543. }
  11544. font = [
  11545. style.fontStyle,
  11546. style.fontWeight,
  11547. fontSize,
  11548. style.fontFamily || 'sans-serif'
  11549. ].join(' ');
  11550. }
  11551. return font && trim(font) || style.textFont || style.font;
  11552. };
  11553. return ZRText;
  11554. }(Displayable));
  11555. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11556. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11557. function normalizeTextStyle(style) {
  11558. normalizeStyle(style);
  11559. each(style.rich, normalizeStyle);
  11560. return style;
  11561. }
  11562. function normalizeStyle(style) {
  11563. if (style) {
  11564. style.font = ZRText.makeFont(style);
  11565. var textAlign = style.align;
  11566. textAlign === 'middle' && (textAlign = 'center');
  11567. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11568. var verticalAlign = style.verticalAlign;
  11569. verticalAlign === 'center' && (verticalAlign = 'middle');
  11570. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11571. var textPadding = style.padding;
  11572. if (textPadding) {
  11573. style.padding = normalizeCssArray(style.padding);
  11574. }
  11575. }
  11576. }
  11577. function getStroke(stroke, lineWidth) {
  11578. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11579. ? null
  11580. : (stroke.image || stroke.colorStops)
  11581. ? '#000'
  11582. : stroke;
  11583. }
  11584. function getFill(fill) {
  11585. return (fill == null || fill === 'none')
  11586. ? null
  11587. : (fill.image || fill.colorStops)
  11588. ? '#000'
  11589. : fill;
  11590. }
  11591. function getTextXForPadding(x, textAlign, textPadding) {
  11592. return textAlign === 'right'
  11593. ? (x - textPadding[1])
  11594. : textAlign === 'center'
  11595. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11596. : (x + textPadding[3]);
  11597. }
  11598. function getStyleText(style) {
  11599. var text = style.text;
  11600. text != null && (text += '');
  11601. return text;
  11602. }
  11603. function needDrawBackground(style) {
  11604. return !!(style.backgroundColor
  11605. || (style.borderWidth && style.borderColor));
  11606. }
  11607. var getECData = makeInner();
  11608. var _highlightNextDigit = 1;
  11609. var _highlightKeyMap = {};
  11610. var getSavedStates = makeInner();
  11611. var HOVER_STATE_NORMAL = 0;
  11612. var HOVER_STATE_BLUR = 1;
  11613. var HOVER_STATE_EMPHASIS = 2;
  11614. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11615. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11616. var Z2_EMPHASIS_LIFT = 10;
  11617. var Z2_SELECT_LIFT = 9;
  11618. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11619. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11620. var SELECT_ACTION_TYPE = 'select';
  11621. var UNSELECT_ACTION_TYPE = 'unselect';
  11622. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11623. function hasFillOrStroke(fillOrStroke) {
  11624. return fillOrStroke != null && fillOrStroke !== 'none';
  11625. } // Most lifted color are duplicated.
  11626. var liftedColorCache = new LRU(100);
  11627. function liftColor(color$1) {
  11628. if (typeof color$1 !== 'string') {
  11629. return color$1;
  11630. }
  11631. var liftedColor = liftedColorCache.get(color$1);
  11632. if (!liftedColor) {
  11633. liftedColor = lift(color$1, -0.1);
  11634. liftedColorCache.put(color$1, liftedColor);
  11635. }
  11636. return liftedColor;
  11637. }
  11638. function doChangeHoverState(el, stateName, hoverStateEnum) {
  11639. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  11640. el.onHoverStateChange(stateName);
  11641. }
  11642. el.hoverState = hoverStateEnum;
  11643. }
  11644. function singleEnterEmphasis(el) {
  11645. // Only mark the flag.
  11646. // States will be applied in the echarts.ts in next frame.
  11647. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  11648. }
  11649. function singleLeaveEmphasis(el) {
  11650. // Only mark the flag.
  11651. // States will be applied in the echarts.ts in next frame.
  11652. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  11653. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11654. }
  11655. }
  11656. function singleEnterBlur(el) {
  11657. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  11658. }
  11659. function singleLeaveBlur(el) {
  11660. if (el.hoverState === HOVER_STATE_BLUR) {
  11661. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11662. }
  11663. }
  11664. function singleEnterSelect(el) {
  11665. el.selected = true;
  11666. }
  11667. function singleLeaveSelect(el) {
  11668. el.selected = false;
  11669. }
  11670. function updateElementState(el, updater, commonParam) {
  11671. updater(el, commonParam);
  11672. }
  11673. function traverseUpdateState(el, updater, commonParam) {
  11674. updateElementState(el, updater, commonParam);
  11675. el.isGroup && el.traverse(function (child) {
  11676. updateElementState(child, updater, commonParam);
  11677. });
  11678. }
  11679. function setStatesFlag(el, stateName) {
  11680. switch (stateName) {
  11681. case 'emphasis':
  11682. el.hoverState = HOVER_STATE_EMPHASIS;
  11683. break;
  11684. case 'normal':
  11685. el.hoverState = HOVER_STATE_NORMAL;
  11686. break;
  11687. case 'blur':
  11688. el.hoverState = HOVER_STATE_BLUR;
  11689. break;
  11690. case 'select':
  11691. el.selected = true;
  11692. }
  11693. }
  11694. function getFromStateStyle(el, props, toStateName, defaultValue) {
  11695. var style = el.style;
  11696. var fromState = {};
  11697. for (var i = 0; i < props.length; i++) {
  11698. var propName = props[i];
  11699. var val = style[propName];
  11700. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  11701. }
  11702. for (var i = 0; i < el.animators.length; i++) {
  11703. var animator = el.animators[i];
  11704. if (animator.__fromStateTransition // Dont consider the animation to emphasis state.
  11705. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  11706. animator.saveFinalToTarget(fromState, props);
  11707. }
  11708. }
  11709. return fromState;
  11710. }
  11711. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  11712. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  11713. var cloned = false;
  11714. if (el instanceof Path) {
  11715. var store = getSavedStates(el);
  11716. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  11717. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  11718. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  11719. state = state || {}; // Apply default color lift
  11720. var emphasisStyle = state.style || {};
  11721. if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  11722. cloned = true; // Not modify the original value.
  11723. state = extend({}, state);
  11724. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  11725. emphasisStyle.fill = liftColor(fromFill);
  11726. } // Not highlight stroke if fill has been highlighted.
  11727. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  11728. if (!cloned) {
  11729. state = extend({}, state);
  11730. emphasisStyle = extend({}, emphasisStyle);
  11731. }
  11732. emphasisStyle.stroke = liftColor(fromStroke);
  11733. }
  11734. state.style = emphasisStyle;
  11735. }
  11736. }
  11737. if (state) {
  11738. // TODO Share with textContent?
  11739. if (state.z2 == null) {
  11740. if (!cloned) {
  11741. state = extend({}, state);
  11742. }
  11743. var z2EmphasisLift = el.z2EmphasisLift;
  11744. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  11745. }
  11746. }
  11747. return state;
  11748. }
  11749. function createSelectDefaultState(el, stateName, state) {
  11750. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  11751. if (state) {
  11752. // TODO Share with textContent?
  11753. if (state.z2 == null) {
  11754. state = extend({}, state);
  11755. var z2SelectLift = el.z2SelectLift;
  11756. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  11757. }
  11758. }
  11759. return state;
  11760. }
  11761. function createBlurDefaultState(el, stateName, state) {
  11762. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  11763. var currentOpacity = el.style.opacity;
  11764. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  11765. opacity: 1
  11766. }) : null;
  11767. state = state || {};
  11768. var blurStyle = state.style || {};
  11769. if (blurStyle.opacity == null) {
  11770. // clone state
  11771. state = extend({}, state);
  11772. blurStyle = extend({
  11773. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  11774. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  11775. }, blurStyle);
  11776. state.style = blurStyle;
  11777. }
  11778. return state;
  11779. }
  11780. function elementStateProxy(stateName, targetStates) {
  11781. var state = this.states[stateName];
  11782. if (this.style) {
  11783. if (stateName === 'emphasis') {
  11784. return createEmphasisDefaultState(this, stateName, targetStates, state);
  11785. } else if (stateName === 'blur') {
  11786. return createBlurDefaultState(this, stateName, state);
  11787. } else if (stateName === 'select') {
  11788. return createSelectDefaultState(this, stateName, state);
  11789. }
  11790. }
  11791. return state;
  11792. }
  11793. /**FI
  11794. * Set hover style (namely "emphasis style") of element.
  11795. * @param el Should not be `zrender/graphic/Group`.
  11796. * @param focus 'self' | 'selfInSeries' | 'series'
  11797. */
  11798. function setDefaultStateProxy(el) {
  11799. el.stateProxy = elementStateProxy;
  11800. var textContent = el.getTextContent();
  11801. var textGuide = el.getTextGuideLine();
  11802. if (textContent) {
  11803. textContent.stateProxy = elementStateProxy;
  11804. }
  11805. if (textGuide) {
  11806. textGuide.stateProxy = elementStateProxy;
  11807. }
  11808. }
  11809. function enterEmphasisWhenMouseOver(el, e) {
  11810. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11811. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  11812. }
  11813. function leaveEmphasisWhenMouseOut(el, e) {
  11814. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11815. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  11816. }
  11817. function enterEmphasis(el, highlightDigit) {
  11818. el.__highByOuter |= 1 << (highlightDigit || 0);
  11819. traverseUpdateState(el, singleEnterEmphasis);
  11820. }
  11821. function leaveEmphasis(el, highlightDigit) {
  11822. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  11823. }
  11824. function enterBlur(el) {
  11825. traverseUpdateState(el, singleEnterBlur);
  11826. }
  11827. function leaveBlur(el) {
  11828. traverseUpdateState(el, singleLeaveBlur);
  11829. }
  11830. function enterSelect(el) {
  11831. traverseUpdateState(el, singleEnterSelect);
  11832. }
  11833. function leaveSelect(el) {
  11834. traverseUpdateState(el, singleLeaveSelect);
  11835. }
  11836. function shouldSilent(el, e) {
  11837. return el.__highDownSilentOnTouch && e.zrByTouch;
  11838. }
  11839. function allLeaveBlur(api) {
  11840. var model = api.getModel();
  11841. model.eachComponent(function (componentType, componentModel) {
  11842. var view = componentType === 'series' ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel); // Leave blur anyway
  11843. view.group.traverse(function (child) {
  11844. singleLeaveBlur(child);
  11845. });
  11846. });
  11847. }
  11848. function toggleSeriesBlurState(targetSeriesIndex, focus, blurScope, api, isBlur) {
  11849. var ecModel = api.getModel();
  11850. blurScope = blurScope || 'coordinateSystem';
  11851. function leaveBlurOfIndices(data, dataIndices) {
  11852. for (var i = 0; i < dataIndices.length; i++) {
  11853. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  11854. itemEl && leaveBlur(itemEl);
  11855. }
  11856. }
  11857. if (!isBlur) {
  11858. allLeaveBlur(api);
  11859. return;
  11860. }
  11861. if (targetSeriesIndex == null) {
  11862. return;
  11863. }
  11864. if (!focus || focus === 'none') {
  11865. return;
  11866. }
  11867. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  11868. var targetCoordSys = targetSeriesModel.coordinateSystem;
  11869. if (targetCoordSys && targetCoordSys.master) {
  11870. targetCoordSys = targetCoordSys.master;
  11871. }
  11872. var blurredSeries = [];
  11873. ecModel.eachSeries(function (seriesModel) {
  11874. var sameSeries = targetSeriesModel === seriesModel;
  11875. var coordSys = seriesModel.coordinateSystem;
  11876. if (coordSys && coordSys.master) {
  11877. coordSys = coordSys.master;
  11878. }
  11879. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  11880. if (!( // Not blur other series if blurScope series
  11881. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  11882. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  11883. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  11884. )) {
  11885. var view = api.getViewOfSeriesModel(seriesModel);
  11886. view.group.traverse(function (child) {
  11887. singleEnterBlur(child);
  11888. });
  11889. if (isArrayLike(focus)) {
  11890. leaveBlurOfIndices(seriesModel.getData(), focus);
  11891. } else if (isObject(focus)) {
  11892. var dataTypes = keys(focus);
  11893. for (var d = 0; d < dataTypes.length; d++) {
  11894. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  11895. }
  11896. }
  11897. blurredSeries.push(seriesModel);
  11898. }
  11899. });
  11900. ecModel.eachComponent(function (componentType, componentModel) {
  11901. if (componentType === 'series') {
  11902. return;
  11903. }
  11904. var view = api.getViewOfComponentModel(componentModel);
  11905. if (view && view.blurSeries) {
  11906. view.blurSeries(blurredSeries, ecModel);
  11907. }
  11908. });
  11909. }
  11910. function toggleSeriesBlurStateFromPayload(seriesModel, payload, api) {
  11911. if (!isHighDownPayload(payload)) {
  11912. return;
  11913. }
  11914. var isHighlight = payload.type === HIGHLIGHT_ACTION_TYPE;
  11915. var seriesIndex = seriesModel.seriesIndex;
  11916. var data = seriesModel.getData(payload.dataType);
  11917. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  11918. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  11919. var el = data.getItemGraphicEl(dataIndex);
  11920. if (!el) {
  11921. var count = data.count();
  11922. var current = 0; // If data on dataIndex is NaN.
  11923. while (!el && current < count) {
  11924. el = data.getItemGraphicEl(current++);
  11925. }
  11926. }
  11927. if (el) {
  11928. var ecData = getECData(el);
  11929. toggleSeriesBlurState(seriesIndex, ecData.focus, ecData.blurScope, api, isHighlight);
  11930. } else {
  11931. // If there is no element put on the data. Try getting it from raw option
  11932. // TODO Should put it on seriesModel?
  11933. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  11934. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  11935. if (focus_1 != null) {
  11936. toggleSeriesBlurState(seriesIndex, focus_1, blurScope, api, isHighlight);
  11937. }
  11938. }
  11939. }
  11940. function toggleSelectionFromPayload(seriesModel, payload, api) {
  11941. if (!isSelectChangePayload(payload)) {
  11942. return;
  11943. }
  11944. var dataType = payload.dataType;
  11945. var data = seriesModel.getData(dataType);
  11946. var dataIndex = queryDataIndex(data, payload);
  11947. if (!isArray(dataIndex)) {
  11948. dataIndex = [dataIndex];
  11949. }
  11950. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  11951. }
  11952. function updateSeriesElementSelection(seriesModel) {
  11953. var allData = seriesModel.getAllData();
  11954. each(allData, function (_a) {
  11955. var data = _a.data,
  11956. type = _a.type;
  11957. data.eachItemGraphicEl(function (el, idx) {
  11958. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  11959. });
  11960. });
  11961. }
  11962. function getAllSelectedIndices(ecModel) {
  11963. var ret = [];
  11964. ecModel.eachSeries(function (seriesModel) {
  11965. var allData = seriesModel.getAllData();
  11966. each(allData, function (_a) {
  11967. var data = _a.data,
  11968. type = _a.type;
  11969. var dataIndices = seriesModel.getSelectedDataIndices();
  11970. if (dataIndices.length > 0) {
  11971. var item = {
  11972. dataIndex: dataIndices,
  11973. seriesIndex: seriesModel.seriesIndex
  11974. };
  11975. if (type != null) {
  11976. item.dataType = type;
  11977. }
  11978. ret.push(item);
  11979. }
  11980. });
  11981. });
  11982. return ret;
  11983. }
  11984. /**
  11985. * Enable the function that mouseover will trigger the emphasis state.
  11986. *
  11987. * NOTE:
  11988. * This function should be used on the element with dataIndex, seriesIndex.
  11989. *
  11990. */
  11991. function enableHoverEmphasis(el, focus, blurScope) {
  11992. setAsHighDownDispatcher(el, true);
  11993. traverseUpdateState(el, setDefaultStateProxy);
  11994. enableHoverFocus(el, focus, blurScope);
  11995. }
  11996. function enableHoverFocus(el, focus, blurScope) {
  11997. var ecData = getECData(el);
  11998. if (focus != null) {
  11999. // TODO dataIndex may be set after this function. This check is not useful.
  12000. // if (ecData.dataIndex == null) {
  12001. // if (__DEV__) {
  12002. // console.warn('focus can only been set on element with dataIndex');
  12003. // }
  12004. // }
  12005. // else {
  12006. ecData.focus = focus;
  12007. ecData.blurScope = blurScope; // }
  12008. } else if (ecData.focus) {
  12009. ecData.focus = null;
  12010. }
  12011. }
  12012. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12013. var defaultStyleGetterMap = {
  12014. itemStyle: 'getItemStyle',
  12015. lineStyle: 'getLineStyle',
  12016. areaStyle: 'getAreaStyle'
  12017. };
  12018. /**
  12019. * Set emphasis/blur/selected states of element.
  12020. */
  12021. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12022. getter) {
  12023. styleType = styleType || 'itemStyle';
  12024. for (var i = 0; i < OTHER_STATES.length; i++) {
  12025. var stateName = OTHER_STATES[i];
  12026. var model = itemModel.getModel([stateName, styleType]);
  12027. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12028. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12029. }
  12030. }
  12031. /**
  12032. * @parame el
  12033. * @param el.highDownSilentOnTouch
  12034. * In touch device, mouseover event will be trigger on touchstart event
  12035. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12036. * conveniently use hoverStyle when tap on touch screen without additional
  12037. * code for compatibility.
  12038. * But if the chart/component has select feature, which usually also use
  12039. * hoverStyle, there might be conflict between 'select-highlight' and
  12040. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12041. * In this case, `highDownSilentOnTouch` should be used to disable
  12042. * hover-highlight on touch device.
  12043. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12044. */
  12045. function setAsHighDownDispatcher(el, asDispatcher) {
  12046. var disable = asDispatcher === false;
  12047. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12048. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12049. if (el.highDownSilentOnTouch) {
  12050. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12051. } // Simple optimize, since this method might be
  12052. // called for each elements of a group in some cases.
  12053. if (!disable || extendedEl.__highDownDispatcher) {
  12054. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12055. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12056. // Also keep previous record.
  12057. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12058. extendedEl.__highDownDispatcher = !disable;
  12059. }
  12060. }
  12061. function isHighDownDispatcher(el) {
  12062. return !!(el && el.__highDownDispatcher);
  12063. }
  12064. /**
  12065. * Support hightlight/downplay record on each elements.
  12066. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12067. * user triggerred hightlight/downplay should not conflict.
  12068. * Only all of the highlightDigit cleared, return to normal.
  12069. * @param {string} highlightKey
  12070. * @return {number} highlightDigit
  12071. */
  12072. function getHighlightDigit(highlightKey) {
  12073. var highlightDigit = _highlightKeyMap[highlightKey];
  12074. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12075. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12076. }
  12077. return highlightDigit;
  12078. }
  12079. function isSelectChangePayload(payload) {
  12080. var payloadType = payload.type;
  12081. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12082. }
  12083. function isHighDownPayload(payload) {
  12084. var payloadType = payload.type;
  12085. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12086. }
  12087. function savePathStates(el) {
  12088. var store = getSavedStates(el);
  12089. store.normalFill = el.style.fill;
  12090. store.normalStroke = el.style.stroke;
  12091. var selectState = el.states.select || {};
  12092. store.selectFill = selectState.style && selectState.style.fill || null;
  12093. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12094. }
  12095. var CMD$2 = PathProxy.CMD;
  12096. var points = [[], [], []];
  12097. var mathSqrt$2 = Math.sqrt;
  12098. var mathAtan2 = Math.atan2;
  12099. function transformPath(path, m) {
  12100. var data = path.data;
  12101. var len = path.len();
  12102. var cmd;
  12103. var nPoint;
  12104. var i;
  12105. var j;
  12106. var k;
  12107. var p;
  12108. var M = CMD$2.M;
  12109. var C = CMD$2.C;
  12110. var L = CMD$2.L;
  12111. var R = CMD$2.R;
  12112. var A = CMD$2.A;
  12113. var Q = CMD$2.Q;
  12114. for (i = 0, j = 0; i < len;) {
  12115. cmd = data[i++];
  12116. j = i;
  12117. nPoint = 0;
  12118. switch (cmd) {
  12119. case M:
  12120. nPoint = 1;
  12121. break;
  12122. case L:
  12123. nPoint = 1;
  12124. break;
  12125. case C:
  12126. nPoint = 3;
  12127. break;
  12128. case Q:
  12129. nPoint = 2;
  12130. break;
  12131. case A:
  12132. var x = m[4];
  12133. var y = m[5];
  12134. var sx = mathSqrt$2(m[0] * m[0] + m[1] * m[1]);
  12135. var sy = mathSqrt$2(m[2] * m[2] + m[3] * m[3]);
  12136. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12137. data[i] *= sx;
  12138. data[i++] += x;
  12139. data[i] *= sy;
  12140. data[i++] += y;
  12141. data[i++] *= sx;
  12142. data[i++] *= sy;
  12143. data[i++] += angle;
  12144. data[i++] += angle;
  12145. i += 2;
  12146. j = i;
  12147. break;
  12148. case R:
  12149. p[0] = data[i++];
  12150. p[1] = data[i++];
  12151. applyTransform(p, p, m);
  12152. data[j++] = p[0];
  12153. data[j++] = p[1];
  12154. p[0] += data[i++];
  12155. p[1] += data[i++];
  12156. applyTransform(p, p, m);
  12157. data[j++] = p[0];
  12158. data[j++] = p[1];
  12159. }
  12160. for (k = 0; k < nPoint; k++) {
  12161. var p_1 = points[k];
  12162. p_1[0] = data[i++];
  12163. p_1[1] = data[i++];
  12164. applyTransform(p_1, p_1, m);
  12165. data[j++] = p_1[0];
  12166. data[j++] = p_1[1];
  12167. }
  12168. }
  12169. path.increaseVersion();
  12170. }
  12171. var mathSqrt$3 = Math.sqrt;
  12172. var mathSin$2 = Math.sin;
  12173. var mathCos$2 = Math.cos;
  12174. var PI$1 = Math.PI;
  12175. function vMag(v) {
  12176. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12177. }
  12178. function vRatio(u, v) {
  12179. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12180. }
  12181. function vAngle(u, v) {
  12182. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12183. * Math.acos(vRatio(u, v));
  12184. }
  12185. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12186. var psi = psiDeg * (PI$1 / 180.0);
  12187. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12188. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12189. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12190. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12191. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12192. if (lambda > 1) {
  12193. rx *= mathSqrt$3(lambda);
  12194. ry *= mathSqrt$3(lambda);
  12195. }
  12196. var f = (fa === fs ? -1 : 1)
  12197. * mathSqrt$3((((rx * rx) * (ry * ry))
  12198. - ((rx * rx) * (yp * yp))
  12199. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12200. + (ry * ry) * (xp * xp))) || 0;
  12201. var cxp = f * rx * yp / ry;
  12202. var cyp = f * -ry * xp / rx;
  12203. var cx = (x1 + x2) / 2.0
  12204. + mathCos$2(psi) * cxp
  12205. - mathSin$2(psi) * cyp;
  12206. var cy = (y1 + y2) / 2.0
  12207. + mathSin$2(psi) * cxp
  12208. + mathCos$2(psi) * cyp;
  12209. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12210. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12211. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12212. var dTheta = vAngle(u, v);
  12213. if (vRatio(u, v) <= -1) {
  12214. dTheta = PI$1;
  12215. }
  12216. if (vRatio(u, v) >= 1) {
  12217. dTheta = 0;
  12218. }
  12219. if (dTheta < 0) {
  12220. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12221. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12222. }
  12223. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12224. }
  12225. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12226. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12227. function createPathProxyFromString(data) {
  12228. var path = new PathProxy();
  12229. if (!data) {
  12230. return path;
  12231. }
  12232. var cpx = 0;
  12233. var cpy = 0;
  12234. var subpathX = cpx;
  12235. var subpathY = cpy;
  12236. var prevCmd;
  12237. var CMD = PathProxy.CMD;
  12238. var cmdList = data.match(commandReg);
  12239. if (!cmdList) {
  12240. return path;
  12241. }
  12242. for (var l = 0; l < cmdList.length; l++) {
  12243. var cmdText = cmdList[l];
  12244. var cmdStr = cmdText.charAt(0);
  12245. var cmd = void 0;
  12246. var p = cmdText.match(numberReg) || [];
  12247. var pLen = p.length;
  12248. for (var i = 0; i < pLen; i++) {
  12249. p[i] = parseFloat(p[i]);
  12250. }
  12251. var off = 0;
  12252. while (off < pLen) {
  12253. var ctlPtx = void 0;
  12254. var ctlPty = void 0;
  12255. var rx = void 0;
  12256. var ry = void 0;
  12257. var psi = void 0;
  12258. var fa = void 0;
  12259. var fs = void 0;
  12260. var x1 = cpx;
  12261. var y1 = cpy;
  12262. var len = void 0;
  12263. var pathData = void 0;
  12264. switch (cmdStr) {
  12265. case 'l':
  12266. cpx += p[off++];
  12267. cpy += p[off++];
  12268. cmd = CMD.L;
  12269. path.addData(cmd, cpx, cpy);
  12270. break;
  12271. case 'L':
  12272. cpx = p[off++];
  12273. cpy = p[off++];
  12274. cmd = CMD.L;
  12275. path.addData(cmd, cpx, cpy);
  12276. break;
  12277. case 'm':
  12278. cpx += p[off++];
  12279. cpy += p[off++];
  12280. cmd = CMD.M;
  12281. path.addData(cmd, cpx, cpy);
  12282. subpathX = cpx;
  12283. subpathY = cpy;
  12284. cmdStr = 'l';
  12285. break;
  12286. case 'M':
  12287. cpx = p[off++];
  12288. cpy = p[off++];
  12289. cmd = CMD.M;
  12290. path.addData(cmd, cpx, cpy);
  12291. subpathX = cpx;
  12292. subpathY = cpy;
  12293. cmdStr = 'L';
  12294. break;
  12295. case 'h':
  12296. cpx += p[off++];
  12297. cmd = CMD.L;
  12298. path.addData(cmd, cpx, cpy);
  12299. break;
  12300. case 'H':
  12301. cpx = p[off++];
  12302. cmd = CMD.L;
  12303. path.addData(cmd, cpx, cpy);
  12304. break;
  12305. case 'v':
  12306. cpy += p[off++];
  12307. cmd = CMD.L;
  12308. path.addData(cmd, cpx, cpy);
  12309. break;
  12310. case 'V':
  12311. cpy = p[off++];
  12312. cmd = CMD.L;
  12313. path.addData(cmd, cpx, cpy);
  12314. break;
  12315. case 'C':
  12316. cmd = CMD.C;
  12317. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12318. cpx = p[off - 2];
  12319. cpy = p[off - 1];
  12320. break;
  12321. case 'c':
  12322. cmd = CMD.C;
  12323. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12324. cpx += p[off - 2];
  12325. cpy += p[off - 1];
  12326. break;
  12327. case 'S':
  12328. ctlPtx = cpx;
  12329. ctlPty = cpy;
  12330. len = path.len();
  12331. pathData = path.data;
  12332. if (prevCmd === CMD.C) {
  12333. ctlPtx += cpx - pathData[len - 4];
  12334. ctlPty += cpy - pathData[len - 3];
  12335. }
  12336. cmd = CMD.C;
  12337. x1 = p[off++];
  12338. y1 = p[off++];
  12339. cpx = p[off++];
  12340. cpy = p[off++];
  12341. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12342. break;
  12343. case 's':
  12344. ctlPtx = cpx;
  12345. ctlPty = cpy;
  12346. len = path.len();
  12347. pathData = path.data;
  12348. if (prevCmd === CMD.C) {
  12349. ctlPtx += cpx - pathData[len - 4];
  12350. ctlPty += cpy - pathData[len - 3];
  12351. }
  12352. cmd = CMD.C;
  12353. x1 = cpx + p[off++];
  12354. y1 = cpy + p[off++];
  12355. cpx += p[off++];
  12356. cpy += p[off++];
  12357. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12358. break;
  12359. case 'Q':
  12360. x1 = p[off++];
  12361. y1 = p[off++];
  12362. cpx = p[off++];
  12363. cpy = p[off++];
  12364. cmd = CMD.Q;
  12365. path.addData(cmd, x1, y1, cpx, cpy);
  12366. break;
  12367. case 'q':
  12368. x1 = p[off++] + cpx;
  12369. y1 = p[off++] + cpy;
  12370. cpx += p[off++];
  12371. cpy += p[off++];
  12372. cmd = CMD.Q;
  12373. path.addData(cmd, x1, y1, cpx, cpy);
  12374. break;
  12375. case 'T':
  12376. ctlPtx = cpx;
  12377. ctlPty = cpy;
  12378. len = path.len();
  12379. pathData = path.data;
  12380. if (prevCmd === CMD.Q) {
  12381. ctlPtx += cpx - pathData[len - 4];
  12382. ctlPty += cpy - pathData[len - 3];
  12383. }
  12384. cpx = p[off++];
  12385. cpy = p[off++];
  12386. cmd = CMD.Q;
  12387. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12388. break;
  12389. case 't':
  12390. ctlPtx = cpx;
  12391. ctlPty = cpy;
  12392. len = path.len();
  12393. pathData = path.data;
  12394. if (prevCmd === CMD.Q) {
  12395. ctlPtx += cpx - pathData[len - 4];
  12396. ctlPty += cpy - pathData[len - 3];
  12397. }
  12398. cpx += p[off++];
  12399. cpy += p[off++];
  12400. cmd = CMD.Q;
  12401. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12402. break;
  12403. case 'A':
  12404. rx = p[off++];
  12405. ry = p[off++];
  12406. psi = p[off++];
  12407. fa = p[off++];
  12408. fs = p[off++];
  12409. x1 = cpx, y1 = cpy;
  12410. cpx = p[off++];
  12411. cpy = p[off++];
  12412. cmd = CMD.A;
  12413. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12414. break;
  12415. case 'a':
  12416. rx = p[off++];
  12417. ry = p[off++];
  12418. psi = p[off++];
  12419. fa = p[off++];
  12420. fs = p[off++];
  12421. x1 = cpx, y1 = cpy;
  12422. cpx += p[off++];
  12423. cpy += p[off++];
  12424. cmd = CMD.A;
  12425. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12426. break;
  12427. }
  12428. }
  12429. if (cmdStr === 'z' || cmdStr === 'Z') {
  12430. cmd = CMD.Z;
  12431. path.addData(cmd);
  12432. cpx = subpathX;
  12433. cpy = subpathY;
  12434. }
  12435. prevCmd = cmd;
  12436. }
  12437. path.toStatic();
  12438. return path;
  12439. }
  12440. var SVGPath = (function (_super) {
  12441. __extends(SVGPath, _super);
  12442. function SVGPath() {
  12443. return _super !== null && _super.apply(this, arguments) || this;
  12444. }
  12445. SVGPath.prototype.applyTransform = function (m) { };
  12446. return SVGPath;
  12447. }(Path));
  12448. function isPathProxy(path) {
  12449. return path.setData != null;
  12450. }
  12451. function createPathOptions(str, opts) {
  12452. var pathProxy = createPathProxyFromString(str);
  12453. var innerOpts = extend({}, opts);
  12454. innerOpts.buildPath = function (path) {
  12455. if (isPathProxy(path)) {
  12456. path.setData(pathProxy.data);
  12457. var ctx = path.getContext();
  12458. if (ctx) {
  12459. path.rebuildPath(ctx, 1);
  12460. }
  12461. }
  12462. else {
  12463. var ctx = path;
  12464. pathProxy.rebuildPath(ctx, 1);
  12465. }
  12466. };
  12467. innerOpts.applyTransform = function (m) {
  12468. transformPath(pathProxy, m);
  12469. this.dirtyShape();
  12470. };
  12471. return innerOpts;
  12472. }
  12473. function createFromString(str, opts) {
  12474. return new SVGPath(createPathOptions(str, opts));
  12475. }
  12476. function extendFromString(str, defaultOpts) {
  12477. var innerOpts = createPathOptions(str, defaultOpts);
  12478. var Sub = (function (_super) {
  12479. __extends(Sub, _super);
  12480. function Sub(opts) {
  12481. var _this = _super.call(this, opts) || this;
  12482. _this.applyTransform = innerOpts.applyTransform;
  12483. _this.buildPath = innerOpts.buildPath;
  12484. return _this;
  12485. }
  12486. return Sub;
  12487. }(SVGPath));
  12488. return Sub;
  12489. }
  12490. function mergePath(pathEls, opts) {
  12491. var pathList = [];
  12492. var len = pathEls.length;
  12493. for (var i = 0; i < len; i++) {
  12494. var pathEl = pathEls[i];
  12495. if (!pathEl.path) {
  12496. pathEl.createPathProxy();
  12497. }
  12498. if (pathEl.shapeChanged()) {
  12499. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12500. }
  12501. pathList.push(pathEl.path);
  12502. }
  12503. var pathBundle = new Path(opts);
  12504. pathBundle.createPathProxy();
  12505. pathBundle.buildPath = function (path) {
  12506. if (isPathProxy(path)) {
  12507. path.appendPath(pathList);
  12508. var ctx = path.getContext();
  12509. if (ctx) {
  12510. path.rebuildPath(ctx, 1);
  12511. }
  12512. }
  12513. };
  12514. return pathBundle;
  12515. }
  12516. var CircleShape = (function () {
  12517. function CircleShape() {
  12518. this.cx = 0;
  12519. this.cy = 0;
  12520. this.r = 0;
  12521. }
  12522. return CircleShape;
  12523. }());
  12524. var Circle = (function (_super) {
  12525. __extends(Circle, _super);
  12526. function Circle(opts) {
  12527. return _super.call(this, opts) || this;
  12528. }
  12529. Circle.prototype.getDefaultShape = function () {
  12530. return new CircleShape();
  12531. };
  12532. Circle.prototype.buildPath = function (ctx, shape, inBundle) {
  12533. if (inBundle) {
  12534. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12535. }
  12536. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  12537. };
  12538. return Circle;
  12539. }(Path));
  12540. Circle.prototype.type = 'circle';
  12541. var EllipseShape = (function () {
  12542. function EllipseShape() {
  12543. this.cx = 0;
  12544. this.cy = 0;
  12545. this.rx = 0;
  12546. this.ry = 0;
  12547. }
  12548. return EllipseShape;
  12549. }());
  12550. var Ellipse = (function (_super) {
  12551. __extends(Ellipse, _super);
  12552. function Ellipse(opts) {
  12553. return _super.call(this, opts) || this;
  12554. }
  12555. Ellipse.prototype.getDefaultShape = function () {
  12556. return new EllipseShape();
  12557. };
  12558. Ellipse.prototype.buildPath = function (ctx, shape) {
  12559. var k = 0.5522848;
  12560. var x = shape.cx;
  12561. var y = shape.cy;
  12562. var a = shape.rx;
  12563. var b = shape.ry;
  12564. var ox = a * k;
  12565. var oy = b * k;
  12566. ctx.moveTo(x - a, y);
  12567. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  12568. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  12569. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  12570. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  12571. ctx.closePath();
  12572. };
  12573. return Ellipse;
  12574. }(Path));
  12575. Ellipse.prototype.type = 'ellipse';
  12576. var PI$2 = Math.PI;
  12577. var PI2$5 = PI$2 * 2;
  12578. var mathSin$3 = Math.sin;
  12579. var mathCos$3 = Math.cos;
  12580. var mathACos = Math.acos;
  12581. var mathATan2 = Math.atan2;
  12582. var mathAbs$1 = Math.abs;
  12583. var mathSqrt$4 = Math.sqrt;
  12584. var mathMax$3 = Math.max;
  12585. var mathMin$3 = Math.min;
  12586. var e = 1e-4;
  12587. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  12588. var x10 = x1 - x0;
  12589. var y10 = y1 - y0;
  12590. var x32 = x3 - x2;
  12591. var y32 = y3 - y2;
  12592. var t = y32 * x10 - x32 * y10;
  12593. if (t * t < e) {
  12594. return;
  12595. }
  12596. t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  12597. return [x0 + t * x10, y0 + t * y10];
  12598. }
  12599. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  12600. var x01 = x0 - x1;
  12601. var y01 = y0 - y1;
  12602. var lo = (clockwise ? cr : -cr) / mathSqrt$4(x01 * x01 + y01 * y01);
  12603. var ox = lo * y01;
  12604. var oy = -lo * x01;
  12605. var x11 = x0 + ox;
  12606. var y11 = y0 + oy;
  12607. var x10 = x1 + ox;
  12608. var y10 = y1 + oy;
  12609. var x00 = (x11 + x10) / 2;
  12610. var y00 = (y11 + y10) / 2;
  12611. var dx = x10 - x11;
  12612. var dy = y10 - y11;
  12613. var d2 = dx * dx + dy * dy;
  12614. var r = radius - cr;
  12615. var s = x11 * y10 - x10 * y11;
  12616. var d = (dy < 0 ? -1 : 1) * mathSqrt$4(mathMax$3(0, r * r * d2 - s * s));
  12617. var cx0 = (s * dy - dx * d) / d2;
  12618. var cy0 = (-s * dx - dy * d) / d2;
  12619. var cx1 = (s * dy + dx * d) / d2;
  12620. var cy1 = (-s * dx + dy * d) / d2;
  12621. var dx0 = cx0 - x00;
  12622. var dy0 = cy0 - y00;
  12623. var dx1 = cx1 - x00;
  12624. var dy1 = cy1 - y00;
  12625. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  12626. cx0 = cx1;
  12627. cy0 = cy1;
  12628. }
  12629. return {
  12630. cx: cx0,
  12631. cy: cy0,
  12632. x01: -ox,
  12633. y01: -oy,
  12634. x11: cx0 * (radius / r - 1),
  12635. y11: cy0 * (radius / r - 1)
  12636. };
  12637. }
  12638. function buildPath$1(ctx, shape) {
  12639. var radius = mathMax$3(shape.r, 0);
  12640. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  12641. var hasRadius = radius > 0;
  12642. var hasInnerRadius = innerRadius > 0;
  12643. if (!hasRadius && !hasInnerRadius) {
  12644. return;
  12645. }
  12646. if (!hasRadius) {
  12647. radius = innerRadius;
  12648. innerRadius = 0;
  12649. }
  12650. if (innerRadius > radius) {
  12651. var tmp = radius;
  12652. radius = innerRadius;
  12653. innerRadius = tmp;
  12654. }
  12655. var clockwise = !!shape.clockwise;
  12656. var startAngle = shape.startAngle;
  12657. var endAngle = shape.endAngle;
  12658. var arc;
  12659. if (startAngle === endAngle) {
  12660. arc = 0;
  12661. }
  12662. else {
  12663. var tmpAngles = [startAngle, endAngle];
  12664. normalizeArcAngles(tmpAngles, !clockwise);
  12665. arc = mathAbs$1(tmpAngles[0] - tmpAngles[1]);
  12666. }
  12667. var x = shape.cx;
  12668. var y = shape.cy;
  12669. var cornerRadius = shape.cornerRadius || 0;
  12670. var innerCornerRadius = shape.innerCornerRadius || 0;
  12671. if (!(radius > e)) {
  12672. ctx.moveTo(x, y);
  12673. }
  12674. else if (arc > PI2$5 - e) {
  12675. ctx.moveTo(x + radius * mathCos$3(startAngle), y + radius * mathSin$3(startAngle));
  12676. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  12677. if (innerRadius > e) {
  12678. ctx.moveTo(x + innerRadius * mathCos$3(endAngle), y + innerRadius * mathSin$3(endAngle));
  12679. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  12680. }
  12681. }
  12682. else {
  12683. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  12684. var cr = mathMin$3(halfRd, cornerRadius);
  12685. var icr = mathMin$3(halfRd, innerCornerRadius);
  12686. var cr0 = icr;
  12687. var cr1 = cr;
  12688. var xrs = radius * mathCos$3(startAngle);
  12689. var yrs = radius * mathSin$3(startAngle);
  12690. var xire = innerRadius * mathCos$3(endAngle);
  12691. var yire = innerRadius * mathSin$3(endAngle);
  12692. var xre = void 0;
  12693. var yre = void 0;
  12694. var xirs = void 0;
  12695. var yirs = void 0;
  12696. if (cr > e || icr > e) {
  12697. xre = radius * mathCos$3(endAngle);
  12698. yre = radius * mathSin$3(endAngle);
  12699. xirs = innerRadius * mathCos$3(startAngle);
  12700. yirs = innerRadius * mathSin$3(startAngle);
  12701. if (arc < PI$2) {
  12702. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  12703. if (it_1) {
  12704. var x0 = xrs - it_1[0];
  12705. var y0 = yrs - it_1[1];
  12706. var x1 = xre - it_1[0];
  12707. var y1 = yre - it_1[1];
  12708. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$4(x0 * x0 + y0 * y0) * mathSqrt$4(x1 * x1 + y1 * y1))) / 2);
  12709. var b = mathSqrt$4(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  12710. cr0 = mathMin$3(icr, (innerRadius - b) / (a - 1));
  12711. cr1 = mathMin$3(cr, (radius - b) / (a + 1));
  12712. }
  12713. }
  12714. }
  12715. if (!(arc > e)) {
  12716. ctx.moveTo(x + xrs, y + yrs);
  12717. }
  12718. else if (cr1 > e) {
  12719. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, cr1, clockwise);
  12720. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, cr1, clockwise);
  12721. ctx.moveTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  12722. if (cr1 < cr) {
  12723. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12724. }
  12725. else {
  12726. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  12727. ctx.arc(x, y, radius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), !clockwise);
  12728. ctx.arc(x + ct1.cx, y + ct1.cy, cr1, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12729. }
  12730. }
  12731. else {
  12732. ctx.moveTo(x + xrs, y + yrs);
  12733. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  12734. }
  12735. if (!(innerRadius > e) || !(arc > e)) {
  12736. ctx.lineTo(x + xire, y + yire);
  12737. }
  12738. else if (cr0 > e) {
  12739. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -cr0, clockwise);
  12740. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -cr0, clockwise);
  12741. ctx.lineTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  12742. if (cr0 < icr) {
  12743. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12744. }
  12745. else {
  12746. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  12747. ctx.arc(x, y, innerRadius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), clockwise);
  12748. ctx.arc(x + ct1.cx, y + ct1.cy, cr0, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12749. }
  12750. }
  12751. else {
  12752. ctx.lineTo(x + xire, y + yire);
  12753. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  12754. }
  12755. }
  12756. ctx.closePath();
  12757. }
  12758. var SectorShape = (function () {
  12759. function SectorShape() {
  12760. this.cx = 0;
  12761. this.cy = 0;
  12762. this.r0 = 0;
  12763. this.r = 0;
  12764. this.startAngle = 0;
  12765. this.endAngle = Math.PI * 2;
  12766. this.clockwise = true;
  12767. this.cornerRadius = 0;
  12768. this.innerCornerRadius = 0;
  12769. }
  12770. return SectorShape;
  12771. }());
  12772. var Sector = (function (_super) {
  12773. __extends(Sector, _super);
  12774. function Sector(opts) {
  12775. return _super.call(this, opts) || this;
  12776. }
  12777. Sector.prototype.getDefaultShape = function () {
  12778. return new SectorShape();
  12779. };
  12780. Sector.prototype.buildPath = function (ctx, shape) {
  12781. buildPath$1(ctx, shape);
  12782. };
  12783. Sector.prototype.isZeroArea = function () {
  12784. return this.shape.startAngle === this.shape.endAngle
  12785. || this.shape.r === this.shape.r0;
  12786. };
  12787. return Sector;
  12788. }(Path));
  12789. Sector.prototype.type = 'sector';
  12790. var RingShape = (function () {
  12791. function RingShape() {
  12792. this.cx = 0;
  12793. this.cy = 0;
  12794. this.r = 0;
  12795. this.r0 = 0;
  12796. }
  12797. return RingShape;
  12798. }());
  12799. var Ring = (function (_super) {
  12800. __extends(Ring, _super);
  12801. function Ring(opts) {
  12802. return _super.call(this, opts) || this;
  12803. }
  12804. Ring.prototype.getDefaultShape = function () {
  12805. return new RingShape();
  12806. };
  12807. Ring.prototype.buildPath = function (ctx, shape) {
  12808. var x = shape.cx;
  12809. var y = shape.cy;
  12810. var PI2 = Math.PI * 2;
  12811. ctx.moveTo(x + shape.r, y);
  12812. ctx.arc(x, y, shape.r, 0, PI2, false);
  12813. ctx.moveTo(x + shape.r0, y);
  12814. ctx.arc(x, y, shape.r0, 0, PI2, true);
  12815. };
  12816. return Ring;
  12817. }(Path));
  12818. Ring.prototype.type = 'ring';
  12819. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  12820. var v0 = (p2 - p0) * 0.5;
  12821. var v1 = (p3 - p1) * 0.5;
  12822. return (2 * (p1 - p2) + v0 + v1) * t3
  12823. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  12824. + v0 * t + p1;
  12825. }
  12826. function smoothSpline(points, isLoop) {
  12827. var len = points.length;
  12828. var ret = [];
  12829. var distance$1 = 0;
  12830. for (var i = 1; i < len; i++) {
  12831. distance$1 += distance(points[i - 1], points[i]);
  12832. }
  12833. var segs = distance$1 / 2;
  12834. segs = segs < len ? len : segs;
  12835. for (var i = 0; i < segs; i++) {
  12836. var pos = i / (segs - 1) * (isLoop ? len : len - 1);
  12837. var idx = Math.floor(pos);
  12838. var w = pos - idx;
  12839. var p0 = void 0;
  12840. var p1 = points[idx % len];
  12841. var p2 = void 0;
  12842. var p3 = void 0;
  12843. if (!isLoop) {
  12844. p0 = points[idx === 0 ? idx : idx - 1];
  12845. p2 = points[idx > len - 2 ? len - 1 : idx + 1];
  12846. p3 = points[idx > len - 3 ? len - 1 : idx + 2];
  12847. }
  12848. else {
  12849. p0 = points[(idx - 1 + len) % len];
  12850. p2 = points[(idx + 1) % len];
  12851. p3 = points[(idx + 2) % len];
  12852. }
  12853. var w2 = w * w;
  12854. var w3 = w * w2;
  12855. ret.push([
  12856. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  12857. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  12858. ]);
  12859. }
  12860. return ret;
  12861. }
  12862. function smoothBezier(points, smooth, isLoop, constraint) {
  12863. var cps = [];
  12864. var v = [];
  12865. var v1 = [];
  12866. var v2 = [];
  12867. var prevPoint;
  12868. var nextPoint;
  12869. var min$1;
  12870. var max$1;
  12871. if (constraint) {
  12872. min$1 = [Infinity, Infinity];
  12873. max$1 = [-Infinity, -Infinity];
  12874. for (var i = 0, len = points.length; i < len; i++) {
  12875. min(min$1, min$1, points[i]);
  12876. max(max$1, max$1, points[i]);
  12877. }
  12878. min(min$1, min$1, constraint[0]);
  12879. max(max$1, max$1, constraint[1]);
  12880. }
  12881. for (var i = 0, len = points.length; i < len; i++) {
  12882. var point = points[i];
  12883. if (isLoop) {
  12884. prevPoint = points[i ? i - 1 : len - 1];
  12885. nextPoint = points[(i + 1) % len];
  12886. }
  12887. else {
  12888. if (i === 0 || i === len - 1) {
  12889. cps.push(clone$1(points[i]));
  12890. continue;
  12891. }
  12892. else {
  12893. prevPoint = points[i - 1];
  12894. nextPoint = points[i + 1];
  12895. }
  12896. }
  12897. sub(v, nextPoint, prevPoint);
  12898. scale(v, v, smooth);
  12899. var d0 = distance(point, prevPoint);
  12900. var d1 = distance(point, nextPoint);
  12901. var sum = d0 + d1;
  12902. if (sum !== 0) {
  12903. d0 /= sum;
  12904. d1 /= sum;
  12905. }
  12906. scale(v1, v, -d0);
  12907. scale(v2, v, d1);
  12908. var cp0 = add([], point, v1);
  12909. var cp1 = add([], point, v2);
  12910. if (constraint) {
  12911. max(cp0, cp0, min$1);
  12912. min(cp0, cp0, max$1);
  12913. max(cp1, cp1, min$1);
  12914. min(cp1, cp1, max$1);
  12915. }
  12916. cps.push(cp0);
  12917. cps.push(cp1);
  12918. }
  12919. if (isLoop) {
  12920. cps.push(cps.shift());
  12921. }
  12922. return cps;
  12923. }
  12924. function buildPath$2(ctx, shape, closePath) {
  12925. var smooth = shape.smooth;
  12926. var points = shape.points;
  12927. if (points && points.length >= 2) {
  12928. if (smooth && smooth !== 'spline') {
  12929. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  12930. ctx.moveTo(points[0][0], points[0][1]);
  12931. var len = points.length;
  12932. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  12933. var cp1 = controlPoints[i * 2];
  12934. var cp2 = controlPoints[i * 2 + 1];
  12935. var p = points[(i + 1) % len];
  12936. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  12937. }
  12938. }
  12939. else {
  12940. if (smooth === 'spline') {
  12941. points = smoothSpline(points, closePath);
  12942. }
  12943. ctx.moveTo(points[0][0], points[0][1]);
  12944. for (var i = 1, l = points.length; i < l; i++) {
  12945. ctx.lineTo(points[i][0], points[i][1]);
  12946. }
  12947. }
  12948. closePath && ctx.closePath();
  12949. }
  12950. }
  12951. var PolygonShape = (function () {
  12952. function PolygonShape() {
  12953. this.points = null;
  12954. this.smooth = 0;
  12955. this.smoothConstraint = null;
  12956. }
  12957. return PolygonShape;
  12958. }());
  12959. var Polygon = (function (_super) {
  12960. __extends(Polygon, _super);
  12961. function Polygon(opts) {
  12962. return _super.call(this, opts) || this;
  12963. }
  12964. Polygon.prototype.getDefaultShape = function () {
  12965. return new PolygonShape();
  12966. };
  12967. Polygon.prototype.buildPath = function (ctx, shape) {
  12968. buildPath$2(ctx, shape, true);
  12969. };
  12970. return Polygon;
  12971. }(Path));
  12972. Polygon.prototype.type = 'polygon';
  12973. var PolylineShape = (function () {
  12974. function PolylineShape() {
  12975. this.points = null;
  12976. this.percent = 1;
  12977. this.smooth = 0;
  12978. this.smoothConstraint = null;
  12979. }
  12980. return PolylineShape;
  12981. }());
  12982. var Polyline = (function (_super) {
  12983. __extends(Polyline, _super);
  12984. function Polyline(opts) {
  12985. return _super.call(this, opts) || this;
  12986. }
  12987. Polyline.prototype.getDefaultStyle = function () {
  12988. return {
  12989. stroke: '#000',
  12990. fill: null
  12991. };
  12992. };
  12993. Polyline.prototype.getDefaultShape = function () {
  12994. return new PolylineShape();
  12995. };
  12996. Polyline.prototype.buildPath = function (ctx, shape) {
  12997. buildPath$2(ctx, shape, false);
  12998. };
  12999. return Polyline;
  13000. }(Path));
  13001. Polyline.prototype.type = 'polyline';
  13002. var subPixelOptimizeOutputShape$1 = {};
  13003. var LineShape = (function () {
  13004. function LineShape() {
  13005. this.x1 = 0;
  13006. this.y1 = 0;
  13007. this.x2 = 0;
  13008. this.y2 = 0;
  13009. this.percent = 1;
  13010. }
  13011. return LineShape;
  13012. }());
  13013. var Line = (function (_super) {
  13014. __extends(Line, _super);
  13015. function Line(opts) {
  13016. return _super.call(this, opts) || this;
  13017. }
  13018. Line.prototype.getDefaultStyle = function () {
  13019. return {
  13020. stroke: '#000',
  13021. fill: null
  13022. };
  13023. };
  13024. Line.prototype.getDefaultShape = function () {
  13025. return new LineShape();
  13026. };
  13027. Line.prototype.buildPath = function (ctx, shape) {
  13028. var x1;
  13029. var y1;
  13030. var x2;
  13031. var y2;
  13032. if (this.subPixelOptimize) {
  13033. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13034. x1 = optimizedShape.x1;
  13035. y1 = optimizedShape.y1;
  13036. x2 = optimizedShape.x2;
  13037. y2 = optimizedShape.y2;
  13038. }
  13039. else {
  13040. x1 = shape.x1;
  13041. y1 = shape.y1;
  13042. x2 = shape.x2;
  13043. y2 = shape.y2;
  13044. }
  13045. var percent = shape.percent;
  13046. if (percent === 0) {
  13047. return;
  13048. }
  13049. ctx.moveTo(x1, y1);
  13050. if (percent < 1) {
  13051. x2 = x1 * (1 - percent) + x2 * percent;
  13052. y2 = y1 * (1 - percent) + y2 * percent;
  13053. }
  13054. ctx.lineTo(x2, y2);
  13055. };
  13056. Line.prototype.pointAt = function (p) {
  13057. var shape = this.shape;
  13058. return [
  13059. shape.x1 * (1 - p) + shape.x2 * p,
  13060. shape.y1 * (1 - p) + shape.y2 * p
  13061. ];
  13062. };
  13063. return Line;
  13064. }(Path));
  13065. Line.prototype.type = 'line';
  13066. var out = [];
  13067. var BezierCurveShape = (function () {
  13068. function BezierCurveShape() {
  13069. this.x1 = 0;
  13070. this.y1 = 0;
  13071. this.x2 = 0;
  13072. this.y2 = 0;
  13073. this.cpx1 = 0;
  13074. this.cpy1 = 0;
  13075. this.percent = 1;
  13076. }
  13077. return BezierCurveShape;
  13078. }());
  13079. function someVectorAt(shape, t, isTangent) {
  13080. var cpx2 = shape.cpx2;
  13081. var cpy2 = shape.cpy2;
  13082. if (cpx2 === null || cpy2 === null) {
  13083. return [
  13084. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13085. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13086. ];
  13087. }
  13088. else {
  13089. return [
  13090. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13091. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13092. ];
  13093. }
  13094. }
  13095. var BezierCurve = (function (_super) {
  13096. __extends(BezierCurve, _super);
  13097. function BezierCurve(opts) {
  13098. return _super.call(this, opts) || this;
  13099. }
  13100. BezierCurve.prototype.getDefaultStyle = function () {
  13101. return {
  13102. stroke: '#000',
  13103. fill: null
  13104. };
  13105. };
  13106. BezierCurve.prototype.getDefaultShape = function () {
  13107. return new BezierCurveShape();
  13108. };
  13109. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13110. var x1 = shape.x1;
  13111. var y1 = shape.y1;
  13112. var x2 = shape.x2;
  13113. var y2 = shape.y2;
  13114. var cpx1 = shape.cpx1;
  13115. var cpy1 = shape.cpy1;
  13116. var cpx2 = shape.cpx2;
  13117. var cpy2 = shape.cpy2;
  13118. var percent = shape.percent;
  13119. if (percent === 0) {
  13120. return;
  13121. }
  13122. ctx.moveTo(x1, y1);
  13123. if (cpx2 == null || cpy2 == null) {
  13124. if (percent < 1) {
  13125. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13126. cpx1 = out[1];
  13127. x2 = out[2];
  13128. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13129. cpy1 = out[1];
  13130. y2 = out[2];
  13131. }
  13132. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13133. }
  13134. else {
  13135. if (percent < 1) {
  13136. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13137. cpx1 = out[1];
  13138. cpx2 = out[2];
  13139. x2 = out[3];
  13140. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13141. cpy1 = out[1];
  13142. cpy2 = out[2];
  13143. y2 = out[3];
  13144. }
  13145. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13146. }
  13147. };
  13148. BezierCurve.prototype.pointAt = function (t) {
  13149. return someVectorAt(this.shape, t, false);
  13150. };
  13151. BezierCurve.prototype.tangentAt = function (t) {
  13152. var p = someVectorAt(this.shape, t, true);
  13153. return normalize(p, p);
  13154. };
  13155. return BezierCurve;
  13156. }(Path));
  13157. BezierCurve.prototype.type = 'bezier-curve';
  13158. var ArcShape = (function () {
  13159. function ArcShape() {
  13160. this.cx = 0;
  13161. this.cy = 0;
  13162. this.r = 0;
  13163. this.startAngle = 0;
  13164. this.endAngle = Math.PI * 2;
  13165. this.clockwise = true;
  13166. }
  13167. return ArcShape;
  13168. }());
  13169. var Arc = (function (_super) {
  13170. __extends(Arc, _super);
  13171. function Arc(opts) {
  13172. return _super.call(this, opts) || this;
  13173. }
  13174. Arc.prototype.getDefaultStyle = function () {
  13175. return {
  13176. stroke: '#000',
  13177. fill: null
  13178. };
  13179. };
  13180. Arc.prototype.getDefaultShape = function () {
  13181. return new ArcShape();
  13182. };
  13183. Arc.prototype.buildPath = function (ctx, shape) {
  13184. var x = shape.cx;
  13185. var y = shape.cy;
  13186. var r = Math.max(shape.r, 0);
  13187. var startAngle = shape.startAngle;
  13188. var endAngle = shape.endAngle;
  13189. var clockwise = shape.clockwise;
  13190. var unitX = Math.cos(startAngle);
  13191. var unitY = Math.sin(startAngle);
  13192. ctx.moveTo(unitX * r + x, unitY * r + y);
  13193. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13194. };
  13195. return Arc;
  13196. }(Path));
  13197. Arc.prototype.type = 'arc';
  13198. var CompoundPath = (function (_super) {
  13199. __extends(CompoundPath, _super);
  13200. function CompoundPath() {
  13201. var _this = _super !== null && _super.apply(this, arguments) || this;
  13202. _this.type = 'compound';
  13203. return _this;
  13204. }
  13205. CompoundPath.prototype._updatePathDirty = function () {
  13206. var paths = this.shape.paths;
  13207. var dirtyPath = this.shapeChanged();
  13208. for (var i = 0; i < paths.length; i++) {
  13209. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13210. }
  13211. if (dirtyPath) {
  13212. this.dirtyShape();
  13213. }
  13214. };
  13215. CompoundPath.prototype.beforeBrush = function () {
  13216. this._updatePathDirty();
  13217. var paths = this.shape.paths || [];
  13218. var scale = this.getGlobalScale();
  13219. for (var i = 0; i < paths.length; i++) {
  13220. if (!paths[i].path) {
  13221. paths[i].createPathProxy();
  13222. }
  13223. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13224. }
  13225. };
  13226. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13227. var paths = shape.paths || [];
  13228. for (var i = 0; i < paths.length; i++) {
  13229. paths[i].buildPath(ctx, paths[i].shape, true);
  13230. }
  13231. };
  13232. CompoundPath.prototype.afterBrush = function () {
  13233. var paths = this.shape.paths || [];
  13234. for (var i = 0; i < paths.length; i++) {
  13235. paths[i].pathUpdated();
  13236. }
  13237. };
  13238. CompoundPath.prototype.getBoundingRect = function () {
  13239. this._updatePathDirty.call(this);
  13240. return Path.prototype.getBoundingRect.call(this);
  13241. };
  13242. return CompoundPath;
  13243. }(Path));
  13244. var Gradient = (function () {
  13245. function Gradient(colorStops) {
  13246. this.colorStops = colorStops || [];
  13247. }
  13248. Gradient.prototype.addColorStop = function (offset, color) {
  13249. this.colorStops.push({
  13250. offset: offset,
  13251. color: color
  13252. });
  13253. };
  13254. return Gradient;
  13255. }());
  13256. var LinearGradient = (function (_super) {
  13257. __extends(LinearGradient, _super);
  13258. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13259. var _this = _super.call(this, colorStops) || this;
  13260. _this.x = x == null ? 0 : x;
  13261. _this.y = y == null ? 0 : y;
  13262. _this.x2 = x2 == null ? 1 : x2;
  13263. _this.y2 = y2 == null ? 0 : y2;
  13264. _this.type = 'linear';
  13265. _this.global = globalCoord || false;
  13266. return _this;
  13267. }
  13268. return LinearGradient;
  13269. }(Gradient));
  13270. var RadialGradient = (function (_super) {
  13271. __extends(RadialGradient, _super);
  13272. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13273. var _this = _super.call(this, colorStops) || this;
  13274. _this.x = x == null ? 0.5 : x;
  13275. _this.y = y == null ? 0.5 : y;
  13276. _this.r = r == null ? 0.5 : r;
  13277. _this.type = 'radial';
  13278. _this.global = globalCoord || false;
  13279. return _this;
  13280. }
  13281. return RadialGradient;
  13282. }(Gradient));
  13283. var extent = [0, 0];
  13284. var extent2 = [0, 0];
  13285. var minTv$1 = new Point();
  13286. var maxTv$1 = new Point();
  13287. var OrientedBoundingRect = (function () {
  13288. function OrientedBoundingRect(rect, transform) {
  13289. this._corners = [];
  13290. this._axes = [];
  13291. this._origin = [0, 0];
  13292. for (var i = 0; i < 4; i++) {
  13293. this._corners[i] = new Point();
  13294. }
  13295. for (var i = 0; i < 2; i++) {
  13296. this._axes[i] = new Point();
  13297. }
  13298. if (rect) {
  13299. this.fromBoundingRect(rect, transform);
  13300. }
  13301. }
  13302. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13303. var corners = this._corners;
  13304. var axes = this._axes;
  13305. var x = rect.x;
  13306. var y = rect.y;
  13307. var x2 = x + rect.width;
  13308. var y2 = y + rect.height;
  13309. corners[0].set(x, y);
  13310. corners[1].set(x2, y);
  13311. corners[2].set(x2, y2);
  13312. corners[3].set(x, y2);
  13313. if (transform) {
  13314. for (var i = 0; i < 4; i++) {
  13315. corners[i].transform(transform);
  13316. }
  13317. }
  13318. Point.sub(axes[0], corners[1], corners[0]);
  13319. Point.sub(axes[1], corners[3], corners[0]);
  13320. axes[0].normalize();
  13321. axes[1].normalize();
  13322. for (var i = 0; i < 2; i++) {
  13323. this._origin[i] = axes[i].dot(corners[0]);
  13324. }
  13325. };
  13326. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13327. var overlapped = true;
  13328. var noMtv = !mtv;
  13329. minTv$1.set(Infinity, Infinity);
  13330. maxTv$1.set(0, 0);
  13331. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13332. overlapped = false;
  13333. if (noMtv) {
  13334. return overlapped;
  13335. }
  13336. }
  13337. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13338. overlapped = false;
  13339. if (noMtv) {
  13340. return overlapped;
  13341. }
  13342. }
  13343. if (!noMtv) {
  13344. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13345. }
  13346. return overlapped;
  13347. };
  13348. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13349. var overlapped = true;
  13350. for (var i = 0; i < 2; i++) {
  13351. var axis = this._axes[i];
  13352. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13353. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13354. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13355. overlapped = false;
  13356. if (noMtv) {
  13357. return overlapped;
  13358. }
  13359. var dist0 = Math.abs(extent2[0] - extent[1]);
  13360. var dist1 = Math.abs(extent[0] - extent2[1]);
  13361. if (Math.min(dist0, dist1) > maxTv.len()) {
  13362. if (dist0 < dist1) {
  13363. Point.scale(maxTv, axis, -dist0 * inverse);
  13364. }
  13365. else {
  13366. Point.scale(maxTv, axis, dist1 * inverse);
  13367. }
  13368. }
  13369. }
  13370. else if (minTv) {
  13371. var dist0 = Math.abs(extent2[0] - extent[1]);
  13372. var dist1 = Math.abs(extent[0] - extent2[1]);
  13373. if (Math.min(dist0, dist1) < minTv.len()) {
  13374. if (dist0 < dist1) {
  13375. Point.scale(minTv, axis, dist0 * inverse);
  13376. }
  13377. else {
  13378. Point.scale(minTv, axis, -dist1 * inverse);
  13379. }
  13380. }
  13381. }
  13382. }
  13383. return overlapped;
  13384. };
  13385. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13386. var axis = this._axes[dim];
  13387. var origin = this._origin;
  13388. var proj = corners[0].dot(axis) + origin[dim];
  13389. var min = proj;
  13390. var max = proj;
  13391. for (var i = 1; i < corners.length; i++) {
  13392. var proj_1 = corners[i].dot(axis) + origin[dim];
  13393. min = Math.min(proj_1, min);
  13394. max = Math.max(proj_1, max);
  13395. }
  13396. out[0] = min;
  13397. out[1] = max;
  13398. };
  13399. return OrientedBoundingRect;
  13400. }());
  13401. var m = [];
  13402. var IncrementalDisplayable = (function (_super) {
  13403. __extends(IncrementalDisplayable, _super);
  13404. function IncrementalDisplayable() {
  13405. var _this = _super !== null && _super.apply(this, arguments) || this;
  13406. _this.notClear = true;
  13407. _this.incremental = true;
  13408. _this._displayables = [];
  13409. _this._temporaryDisplayables = [];
  13410. _this._cursor = 0;
  13411. return _this;
  13412. }
  13413. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13414. cb.call(context, this);
  13415. };
  13416. IncrementalDisplayable.prototype.useStyle = function () {
  13417. this.style = {};
  13418. };
  13419. IncrementalDisplayable.prototype.getCursor = function () {
  13420. return this._cursor;
  13421. };
  13422. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13423. this._cursor = this._displayables.length;
  13424. };
  13425. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13426. this._displayables = [];
  13427. this._temporaryDisplayables = [];
  13428. this._cursor = 0;
  13429. this.markRedraw();
  13430. this.notClear = false;
  13431. };
  13432. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13433. this._temporaryDisplayables = [];
  13434. };
  13435. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13436. if (notPersistent) {
  13437. this._temporaryDisplayables.push(displayable);
  13438. }
  13439. else {
  13440. this._displayables.push(displayable);
  13441. }
  13442. this.markRedraw();
  13443. };
  13444. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13445. notPersistent = notPersistent || false;
  13446. for (var i = 0; i < displayables.length; i++) {
  13447. this.addDisplayable(displayables[i], notPersistent);
  13448. }
  13449. };
  13450. IncrementalDisplayable.prototype.getDisplayables = function () {
  13451. return this._displayables;
  13452. };
  13453. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13454. return this._temporaryDisplayables;
  13455. };
  13456. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13457. for (var i = this._cursor; i < this._displayables.length; i++) {
  13458. cb && cb(this._displayables[i]);
  13459. }
  13460. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13461. cb && cb(this._temporaryDisplayables[i]);
  13462. }
  13463. };
  13464. IncrementalDisplayable.prototype.update = function () {
  13465. this.updateTransform();
  13466. for (var i = this._cursor; i < this._displayables.length; i++) {
  13467. var displayable = this._displayables[i];
  13468. displayable.parent = this;
  13469. displayable.update();
  13470. displayable.parent = null;
  13471. }
  13472. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13473. var displayable = this._temporaryDisplayables[i];
  13474. displayable.parent = this;
  13475. displayable.update();
  13476. displayable.parent = null;
  13477. }
  13478. };
  13479. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13480. if (!this._rect) {
  13481. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13482. for (var i = 0; i < this._displayables.length; i++) {
  13483. var displayable = this._displayables[i];
  13484. var childRect = displayable.getBoundingRect().clone();
  13485. if (displayable.needLocalTransform()) {
  13486. childRect.applyTransform(displayable.getLocalTransform(m));
  13487. }
  13488. rect.union(childRect);
  13489. }
  13490. this._rect = rect;
  13491. }
  13492. return this._rect;
  13493. };
  13494. IncrementalDisplayable.prototype.contain = function (x, y) {
  13495. var localPos = this.transformCoordToLocal(x, y);
  13496. var rect = this.getBoundingRect();
  13497. if (rect.contain(localPos[0], localPos[1])) {
  13498. for (var i = 0; i < this._displayables.length; i++) {
  13499. var displayable = this._displayables[i];
  13500. if (displayable.contain(x, y)) {
  13501. return true;
  13502. }
  13503. }
  13504. }
  13505. return false;
  13506. };
  13507. return IncrementalDisplayable;
  13508. }(Displayable));
  13509. var mathMax$4 = Math.max;
  13510. var mathMin$4 = Math.min;
  13511. var _customShapeMap = {};
  13512. /**
  13513. * Extend shape with parameters
  13514. */
  13515. function extendShape(opts) {
  13516. return Path.extend(opts);
  13517. }
  13518. var extendPathFromString = extendFromString;
  13519. /**
  13520. * Extend path
  13521. */
  13522. function extendPath(pathData, opts) {
  13523. return extendPathFromString(pathData, opts);
  13524. }
  13525. /**
  13526. * Register a user defined shape.
  13527. * The shape class can be fetched by `getShapeClass`
  13528. * This method will overwrite the registered shapes, including
  13529. * the registered built-in shapes, if using the same `name`.
  13530. * The shape can be used in `custom series` and
  13531. * `graphic component` by declaring `{type: name}`.
  13532. *
  13533. * @param name
  13534. * @param ShapeClass Can be generated by `extendShape`.
  13535. */
  13536. function registerShape(name, ShapeClass) {
  13537. _customShapeMap[name] = ShapeClass;
  13538. }
  13539. /**
  13540. * Find shape class registered by `registerShape`. Usually used in
  13541. * fetching user defined shape.
  13542. *
  13543. * [Caution]:
  13544. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  13545. * to use user registered shapes.
  13546. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  13547. * `registerShape` by default. That enables users to get both built-in
  13548. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  13549. * the built-in shapes by using names like 'circle', 'rect' via calling
  13550. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  13551. * in case that it is overwritten by users, except that some features, like
  13552. * `custom series`, `graphic component`, do it deliberately.
  13553. *
  13554. * (2) In the features like `custom series`, `graphic component`, the user input
  13555. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  13556. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  13557. * are reserved names, that is, if some user register a shape named `'image'`,
  13558. * the shape will not be used. If we intending to add some more reserved names
  13559. * in feature, that might bring break changes (disable some existing user shape
  13560. * names). But that case probably rearly happen. So we dont make more mechanism
  13561. * to resolve this issue here.
  13562. *
  13563. * @param name
  13564. * @return The shape class. If not found, return nothing.
  13565. */
  13566. function getShapeClass(name) {
  13567. if (_customShapeMap.hasOwnProperty(name)) {
  13568. return _customShapeMap[name];
  13569. }
  13570. }
  13571. /**
  13572. * Create a path element from path data string
  13573. * @param pathData
  13574. * @param opts
  13575. * @param rect
  13576. * @param layout 'center' or 'cover' default to be cover
  13577. */
  13578. function makePath(pathData, opts, rect, layout) {
  13579. var path = createFromString(pathData, opts);
  13580. if (rect) {
  13581. if (layout === 'center') {
  13582. rect = centerGraphic(rect, path.getBoundingRect());
  13583. }
  13584. resizePath(path, rect);
  13585. }
  13586. return path;
  13587. }
  13588. /**
  13589. * Create a image element from image url
  13590. * @param imageUrl image url
  13591. * @param opts options
  13592. * @param rect constrain rect
  13593. * @param layout 'center' or 'cover'. Default to be 'cover'
  13594. */
  13595. function makeImage(imageUrl, rect, layout) {
  13596. var zrImg = new ZRImage({
  13597. style: {
  13598. image: imageUrl,
  13599. x: rect.x,
  13600. y: rect.y,
  13601. width: rect.width,
  13602. height: rect.height
  13603. },
  13604. onload: function (img) {
  13605. if (layout === 'center') {
  13606. var boundingRect = {
  13607. width: img.width,
  13608. height: img.height
  13609. };
  13610. zrImg.setStyle(centerGraphic(rect, boundingRect));
  13611. }
  13612. }
  13613. });
  13614. return zrImg;
  13615. }
  13616. /**
  13617. * Get position of centered element in bounding box.
  13618. *
  13619. * @param rect element local bounding box
  13620. * @param boundingRect constraint bounding box
  13621. * @return element position containing x, y, width, and height
  13622. */
  13623. function centerGraphic(rect, boundingRect) {
  13624. // Set rect to center, keep width / height ratio.
  13625. var aspect = boundingRect.width / boundingRect.height;
  13626. var width = rect.height * aspect;
  13627. var height;
  13628. if (width <= rect.width) {
  13629. height = rect.height;
  13630. } else {
  13631. width = rect.width;
  13632. height = width / aspect;
  13633. }
  13634. var cx = rect.x + rect.width / 2;
  13635. var cy = rect.y + rect.height / 2;
  13636. return {
  13637. x: cx - width / 2,
  13638. y: cy - height / 2,
  13639. width: width,
  13640. height: height
  13641. };
  13642. }
  13643. var mergePath$1 = mergePath;
  13644. /**
  13645. * Resize a path to fit the rect
  13646. * @param path
  13647. * @param rect
  13648. */
  13649. function resizePath(path, rect) {
  13650. if (!path.applyTransform) {
  13651. return;
  13652. }
  13653. var pathRect = path.getBoundingRect();
  13654. var m = pathRect.calculateTransform(rect);
  13655. path.applyTransform(m);
  13656. }
  13657. /**
  13658. * Sub pixel optimize line for canvas
  13659. */
  13660. function subPixelOptimizeLine$1(param) {
  13661. subPixelOptimizeLine(param.shape, param.shape, param.style);
  13662. return param;
  13663. }
  13664. /**
  13665. * Sub pixel optimize rect for canvas
  13666. */
  13667. function subPixelOptimizeRect$1(param) {
  13668. subPixelOptimizeRect(param.shape, param.shape, param.style);
  13669. return param;
  13670. }
  13671. /**
  13672. * Sub pixel optimize for canvas
  13673. *
  13674. * @param position Coordinate, such as x, y
  13675. * @param lineWidth Should be nonnegative integer.
  13676. * @param positiveOrNegative Default false (negative).
  13677. * @return Optimized position.
  13678. */
  13679. var subPixelOptimize$1 = subPixelOptimize;
  13680. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  13681. var isFrom = false;
  13682. var removeOpt;
  13683. if (typeof dataIndex === 'function') {
  13684. during = cb;
  13685. cb = dataIndex;
  13686. dataIndex = null;
  13687. } else if (isObject(dataIndex)) {
  13688. cb = dataIndex.cb;
  13689. during = dataIndex.during;
  13690. isFrom = dataIndex.isFrom;
  13691. removeOpt = dataIndex.removeOpt;
  13692. dataIndex = dataIndex.dataIndex;
  13693. }
  13694. var isUpdate = animationType === 'update';
  13695. var isRemove = animationType === 'remove';
  13696. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  13697. // If animation is enabled. Will use this animation config in payload.
  13698. // If animation is disabled. Just ignore it.
  13699. if (animatableModel && animatableModel.ecModel) {
  13700. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  13701. animationPayload = updatePayload && updatePayload.animation;
  13702. }
  13703. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  13704. if (!isRemove) {
  13705. // Must stop the remove animation.
  13706. el.stopAnimation('remove');
  13707. }
  13708. if (animationEnabled) {
  13709. var duration = void 0;
  13710. var animationEasing = void 0;
  13711. var animationDelay = void 0;
  13712. if (animationPayload) {
  13713. duration = animationPayload.duration || 0;
  13714. animationEasing = animationPayload.easing || 'cubicOut';
  13715. animationDelay = animationPayload.delay || 0;
  13716. } else if (isRemove) {
  13717. removeOpt = removeOpt || {};
  13718. duration = retrieve2(removeOpt.duration, 200);
  13719. animationEasing = retrieve2(removeOpt.easing, 'cubicOut');
  13720. animationDelay = 0;
  13721. } else {
  13722. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  13723. animationEasing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  13724. animationDelay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  13725. }
  13726. if (typeof animationDelay === 'function') {
  13727. animationDelay = animationDelay(dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  13728. }
  13729. if (typeof duration === 'function') {
  13730. duration = duration(dataIndex);
  13731. }
  13732. duration > 0 ? isFrom ? el.animateFrom(props, {
  13733. duration: duration,
  13734. delay: animationDelay || 0,
  13735. easing: animationEasing,
  13736. done: cb,
  13737. force: !!cb || !!during,
  13738. scope: animationType,
  13739. during: during
  13740. }) : el.animateTo(props, {
  13741. duration: duration,
  13742. delay: animationDelay || 0,
  13743. easing: animationEasing,
  13744. done: cb,
  13745. force: !!cb || !!during,
  13746. setToFinal: true,
  13747. scope: animationType,
  13748. during: during
  13749. }) : ( // FIXME:
  13750. // If `duration` is 0, only the animation on props
  13751. // can be stoped, other animation should be continued?
  13752. // But at present using duration 0 in `animateTo`, `animateFrom`
  13753. // might cause unexpected behavior.
  13754. el.stopAnimation(), // If `isFrom`, the props is the "from" props.
  13755. !isFrom && el.attr(props), cb && cb());
  13756. } else {
  13757. el.stopAnimation();
  13758. !isFrom && el.attr(props); // Call during once.
  13759. during && during(1);
  13760. cb && cb();
  13761. }
  13762. }
  13763. /**
  13764. * Update graphic element properties with or without animation according to the
  13765. * configuration in series.
  13766. *
  13767. * Caution: this method will stop previous animation.
  13768. * So do not use this method to one element twice before
  13769. * animation starts, unless you know what you are doing.
  13770. * @example
  13771. * graphic.updateProps(el, {
  13772. * position: [100, 100]
  13773. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  13774. * // Or
  13775. * graphic.updateProps(el, {
  13776. * position: [100, 100]
  13777. * }, seriesModel, function () { console.log('Animation done!'); });
  13778. */
  13779. function updateProps(el, props, // TODO: TYPE AnimatableModel
  13780. animatableModel, dataIndex, cb, during) {
  13781. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  13782. }
  13783. /**
  13784. * Init graphic element properties with or without animation according to the
  13785. * configuration in series.
  13786. *
  13787. * Caution: this method will stop previous animation.
  13788. * So do not use this method to one element twice before
  13789. * animation starts, unless you know what you are doing.
  13790. */
  13791. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  13792. animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during);
  13793. }
  13794. /**
  13795. * Remove graphic element
  13796. */
  13797. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  13798. // Don't do remove animation twice.
  13799. if (isElementRemoved(el)) {
  13800. return;
  13801. }
  13802. animateOrSetProps('remove', el, props, animatableModel, dataIndex, cb, during);
  13803. }
  13804. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  13805. el.removeTextContent();
  13806. el.removeTextGuideLine();
  13807. removeElement(el, {
  13808. style: {
  13809. opacity: 0
  13810. }
  13811. }, animatableModel, dataIndex, done);
  13812. }
  13813. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  13814. function doRemove() {
  13815. el.parent && el.parent.remove(el);
  13816. } // Hide label and labelLine first
  13817. // TODO Also use fade out animation?
  13818. if (!el.isGroup) {
  13819. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  13820. } else {
  13821. el.traverse(function (disp) {
  13822. if (!disp.isGroup) {
  13823. // Can invoke doRemove multiple times.
  13824. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  13825. }
  13826. });
  13827. }
  13828. }
  13829. /**
  13830. * If element is removed.
  13831. * It can determine if element is having remove animation.
  13832. */
  13833. function isElementRemoved(el) {
  13834. if (!el.__zr) {
  13835. return true;
  13836. }
  13837. for (var i = 0; i < el.animators.length; i++) {
  13838. var animator = el.animators[i];
  13839. if (animator.scope === 'remove') {
  13840. return true;
  13841. }
  13842. }
  13843. return false;
  13844. }
  13845. /**
  13846. * Get transform matrix of target (param target),
  13847. * in coordinate of its ancestor (param ancestor)
  13848. *
  13849. * @param target
  13850. * @param [ancestor]
  13851. */
  13852. function getTransform(target, ancestor) {
  13853. var mat = identity([]);
  13854. while (target && target !== ancestor) {
  13855. mul$1(mat, target.getLocalTransform(), mat);
  13856. target = target.parent;
  13857. }
  13858. return mat;
  13859. }
  13860. /**
  13861. * Apply transform to an vertex.
  13862. * @param target [x, y]
  13863. * @param transform Can be:
  13864. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  13865. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  13866. * @param invert Whether use invert matrix.
  13867. * @return [x, y]
  13868. */
  13869. function applyTransform$1(target, transform, invert$1) {
  13870. if (transform && !isArrayLike(transform)) {
  13871. transform = Transformable.getLocalTransform(transform);
  13872. }
  13873. if (invert$1) {
  13874. transform = invert([], transform);
  13875. }
  13876. return applyTransform([], target, transform);
  13877. }
  13878. /**
  13879. * @param direction 'left' 'right' 'top' 'bottom'
  13880. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  13881. * @param invert Whether use invert matrix.
  13882. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  13883. */
  13884. function transformDirection(direction, transform, invert) {
  13885. // Pick a base, ensure that transform result will not be (0, 0).
  13886. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  13887. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  13888. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  13889. vertex = applyTransform$1(vertex, transform, invert);
  13890. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  13891. }
  13892. function isNotGroup(el) {
  13893. return !el.isGroup;
  13894. }
  13895. function isPath(el) {
  13896. return el.shape != null;
  13897. }
  13898. /**
  13899. * Apply group transition animation from g1 to g2.
  13900. * If no animatableModel, no animation.
  13901. */
  13902. function groupTransition(g1, g2, animatableModel) {
  13903. if (!g1 || !g2) {
  13904. return;
  13905. }
  13906. function getElMap(g) {
  13907. var elMap = {};
  13908. g.traverse(function (el) {
  13909. if (isNotGroup(el) && el.anid) {
  13910. elMap[el.anid] = el;
  13911. }
  13912. });
  13913. return elMap;
  13914. }
  13915. function getAnimatableProps(el) {
  13916. var obj = {
  13917. x: el.x,
  13918. y: el.y,
  13919. rotation: el.rotation
  13920. };
  13921. if (isPath(el)) {
  13922. obj.shape = extend({}, el.shape);
  13923. }
  13924. return obj;
  13925. }
  13926. var elMap1 = getElMap(g1);
  13927. g2.traverse(function (el) {
  13928. if (isNotGroup(el) && el.anid) {
  13929. var oldEl = elMap1[el.anid];
  13930. if (oldEl) {
  13931. var newProp = getAnimatableProps(el);
  13932. el.attr(getAnimatableProps(oldEl));
  13933. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  13934. }
  13935. }
  13936. });
  13937. }
  13938. function clipPointsByRect(points, rect) {
  13939. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  13940. // and when element have border.
  13941. return map(points, function (point) {
  13942. var x = point[0];
  13943. x = mathMax$4(x, rect.x);
  13944. x = mathMin$4(x, rect.x + rect.width);
  13945. var y = point[1];
  13946. y = mathMax$4(y, rect.y);
  13947. y = mathMin$4(y, rect.y + rect.height);
  13948. return [x, y];
  13949. });
  13950. }
  13951. /**
  13952. * Return a new clipped rect. If rect size are negative, return undefined.
  13953. */
  13954. function clipRectByRect(targetRect, rect) {
  13955. var x = mathMax$4(targetRect.x, rect.x);
  13956. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  13957. var y = mathMax$4(targetRect.y, rect.y);
  13958. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  13959. // should be painted. So return undefined.
  13960. if (x2 >= x && y2 >= y) {
  13961. return {
  13962. x: x,
  13963. y: y,
  13964. width: x2 - x,
  13965. height: y2 - y
  13966. };
  13967. }
  13968. }
  13969. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  13970. opt, rect) {
  13971. var innerOpts = extend({
  13972. rectHover: true
  13973. }, opt);
  13974. var style = innerOpts.style = {
  13975. strokeNoScale: true
  13976. };
  13977. rect = rect || {
  13978. x: -1,
  13979. y: -1,
  13980. width: 2,
  13981. height: 2
  13982. };
  13983. if (iconStr) {
  13984. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  13985. }
  13986. }
  13987. /**
  13988. * Return `true` if the given line (line `a`) and the given polygon
  13989. * are intersect.
  13990. * Note that we do not count colinear as intersect here because no
  13991. * requirement for that. We could do that if required in future.
  13992. */
  13993. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  13994. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  13995. var p = points[i];
  13996. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  13997. return true;
  13998. }
  13999. p2 = p;
  14000. }
  14001. }
  14002. /**
  14003. * Return `true` if the given two lines (line `a` and line `b`)
  14004. * are intersect.
  14005. * Note that we do not count colinear as intersect here because no
  14006. * requirement for that. We could do that if required in future.
  14007. */
  14008. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14009. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14010. var mx = a2x - a1x;
  14011. var my = a2y - a1y;
  14012. var nx = b2x - b1x;
  14013. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14014. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14015. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14016. if (nearZero(nmCrossProduct)) {
  14017. return false;
  14018. } // `vec_m` and `vec_n` are intersect iff
  14019. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14020. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14021. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14022. var b1a1x = a1x - b1x;
  14023. var b1a1y = a1y - b1y;
  14024. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14025. if (q < 0 || q > 1) {
  14026. return false;
  14027. }
  14028. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14029. if (p < 0 || p > 1) {
  14030. return false;
  14031. }
  14032. return true;
  14033. }
  14034. /**
  14035. * Cross product of 2-dimension vector.
  14036. */
  14037. function crossProduct2d(x1, y1, x2, y2) {
  14038. return x1 * y2 - x2 * y1;
  14039. }
  14040. function nearZero(val) {
  14041. return val <= 1e-6 && val >= -1e-6;
  14042. } // Register built-in shapes. These shapes might be overwirtten
  14043. // by users, although we do not recommend that.
  14044. registerShape('circle', Circle);
  14045. registerShape('ellipse', Ellipse);
  14046. registerShape('sector', Sector);
  14047. registerShape('ring', Ring);
  14048. registerShape('polygon', Polygon);
  14049. registerShape('polyline', Polyline);
  14050. registerShape('rect', Rect);
  14051. registerShape('line', Line);
  14052. registerShape('bezierCurve', BezierCurve);
  14053. registerShape('arc', Arc);
  14054. var graphic = /*#__PURE__*/Object.freeze({
  14055. __proto__: null,
  14056. extendShape: extendShape,
  14057. extendPath: extendPath,
  14058. registerShape: registerShape,
  14059. getShapeClass: getShapeClass,
  14060. makePath: makePath,
  14061. makeImage: makeImage,
  14062. mergePath: mergePath$1,
  14063. resizePath: resizePath,
  14064. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14065. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14066. subPixelOptimize: subPixelOptimize$1,
  14067. updateProps: updateProps,
  14068. initProps: initProps,
  14069. removeElement: removeElement,
  14070. removeElementWithFadeOut: removeElementWithFadeOut,
  14071. isElementRemoved: isElementRemoved,
  14072. getTransform: getTransform,
  14073. applyTransform: applyTransform$1,
  14074. transformDirection: transformDirection,
  14075. groupTransition: groupTransition,
  14076. clipPointsByRect: clipPointsByRect,
  14077. clipRectByRect: clipRectByRect,
  14078. createIcon: createIcon,
  14079. linePolygonIntersect: linePolygonIntersect,
  14080. lineLineIntersect: lineLineIntersect,
  14081. Group: Group,
  14082. Image: ZRImage,
  14083. Text: ZRText,
  14084. Circle: Circle,
  14085. Ellipse: Ellipse,
  14086. Sector: Sector,
  14087. Ring: Ring,
  14088. Polygon: Polygon,
  14089. Polyline: Polyline,
  14090. Rect: Rect,
  14091. Line: Line,
  14092. BezierCurve: BezierCurve,
  14093. Arc: Arc,
  14094. IncrementalDisplayable: IncrementalDisplayable,
  14095. CompoundPath: CompoundPath,
  14096. LinearGradient: LinearGradient,
  14097. RadialGradient: RadialGradient,
  14098. BoundingRect: BoundingRect,
  14099. OrientedBoundingRect: OrientedBoundingRect,
  14100. Point: Point,
  14101. Path: Path
  14102. });
  14103. var EMPTY_OBJ = {};
  14104. function setLabelText(label, labelTexts) {
  14105. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14106. var stateName = SPECIAL_STATES[i];
  14107. var text = labelTexts[stateName];
  14108. var state = label.ensureState(stateName);
  14109. state.style = state.style || {};
  14110. state.style.text = text;
  14111. }
  14112. var oldStates = label.currentStates.slice();
  14113. label.clearStates(true);
  14114. label.setStyle({
  14115. text: labelTexts.normal
  14116. });
  14117. label.useStates(oldStates, true);
  14118. }
  14119. function getLabelText(opt, stateModels, interpolatedValue) {
  14120. var labelFetcher = opt.labelFetcher;
  14121. var labelDataIndex = opt.labelDataIndex;
  14122. var labelDimIndex = opt.labelDimIndex;
  14123. var normalModel = stateModels.normal;
  14124. var baseText;
  14125. if (labelFetcher) {
  14126. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14127. interpolatedValue: interpolatedValue
  14128. } : null);
  14129. }
  14130. if (baseText == null) {
  14131. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14132. }
  14133. var statesText = {
  14134. normal: baseText
  14135. };
  14136. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14137. var stateName = SPECIAL_STATES[i];
  14138. var stateModel = stateModels[stateName];
  14139. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14140. }
  14141. return statesText;
  14142. }
  14143. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14144. ) {
  14145. opt = opt || EMPTY_OBJ;
  14146. var isSetOnText = targetEl instanceof ZRText;
  14147. var needsCreateText = false;
  14148. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14149. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14150. if (stateModel && stateModel.getShallow('show')) {
  14151. needsCreateText = true;
  14152. break;
  14153. }
  14154. }
  14155. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14156. if (needsCreateText) {
  14157. if (!isSetOnText) {
  14158. // Reuse the previous
  14159. if (!textContent) {
  14160. textContent = new ZRText();
  14161. targetEl.setTextContent(textContent);
  14162. } // Use same state proxy
  14163. if (targetEl.stateProxy) {
  14164. textContent.stateProxy = targetEl.stateProxy;
  14165. }
  14166. }
  14167. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14168. var normalModel = labelStatesModels.normal;
  14169. var showNormal = !!normalModel.getShallow('show');
  14170. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14171. normalStyle.text = labelStatesTexts.normal;
  14172. if (!isSetOnText) {
  14173. // Always create new
  14174. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14175. }
  14176. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14177. var stateName = SPECIAL_STATES[i];
  14178. var stateModel = labelStatesModels[stateName];
  14179. if (stateModel) {
  14180. var stateObj = textContent.ensureState(stateName);
  14181. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14182. if (stateShow !== showNormal) {
  14183. stateObj.ignore = !stateShow;
  14184. }
  14185. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14186. stateObj.style.text = labelStatesTexts[stateName];
  14187. if (!isSetOnText) {
  14188. var targetElEmphasisState = targetEl.ensureState(stateName);
  14189. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14190. }
  14191. }
  14192. } // PENDING: if there is many requirements that emphasis position
  14193. // need to be different from normal position, we might consider
  14194. // auto slient is those cases.
  14195. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14196. if (textContent.style.x != null) {
  14197. normalStyle.x = textContent.style.x;
  14198. }
  14199. if (textContent.style.y != null) {
  14200. normalStyle.y = textContent.style.y;
  14201. }
  14202. textContent.ignore = !showNormal; // Always create new style.
  14203. textContent.useStyle(normalStyle);
  14204. textContent.dirty();
  14205. if (opt.enableTextSetter) {
  14206. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14207. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14208. setLabelText(textContent, labelStatesTexts);
  14209. };
  14210. }
  14211. } else if (textContent) {
  14212. // Not display rich text.
  14213. textContent.ignore = true;
  14214. }
  14215. targetEl.dirty();
  14216. }
  14217. function getLabelStatesModels(itemModel, labelName) {
  14218. labelName = labelName || 'label';
  14219. var statesModels = {
  14220. normal: itemModel.getModel(labelName)
  14221. };
  14222. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14223. var stateName = SPECIAL_STATES[i];
  14224. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14225. }
  14226. return statesModels;
  14227. }
  14228. /**
  14229. * Set basic textStyle properties.
  14230. */
  14231. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14232. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14233. ) {
  14234. var textStyle = {};
  14235. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14236. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14237. return textStyle;
  14238. }
  14239. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14240. opt = opt || {};
  14241. var textConfig = {};
  14242. var labelPosition;
  14243. var labelRotate = textStyleModel.getShallow('rotate');
  14244. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14245. var labelOffset = textStyleModel.getShallow('offset');
  14246. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14247. // in bar series, and magric type should be considered.
  14248. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14249. if (labelPosition != null) {
  14250. textConfig.position = labelPosition;
  14251. }
  14252. if (labelOffset != null) {
  14253. textConfig.offset = labelOffset;
  14254. }
  14255. if (labelRotate != null) {
  14256. labelRotate *= Math.PI / 180;
  14257. textConfig.rotation = labelRotate;
  14258. }
  14259. if (labelDistance != null) {
  14260. textConfig.distance = labelDistance;
  14261. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14262. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14263. return textConfig;
  14264. }
  14265. /**
  14266. * The uniform entry of set text style, that is, retrieve style definitions
  14267. * from `model` and set to `textStyle` object.
  14268. *
  14269. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14270. * properties will be set. (Consider the states of normal and emphasis and
  14271. * default value can be adopted, merge would make the logic too complicated
  14272. * to manage.)
  14273. */
  14274. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14275. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14276. opt = opt || EMPTY_OBJ;
  14277. var ecModel = textStyleModel.ecModel;
  14278. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14279. // {
  14280. // data: [{
  14281. // value: 12,
  14282. // label: {
  14283. // rich: {
  14284. // // no 'a' here but using parent 'a'.
  14285. // }
  14286. // }
  14287. // }],
  14288. // rich: {
  14289. // a: { ... }
  14290. // }
  14291. // }
  14292. var richItemNames = getRichItemNames(textStyleModel);
  14293. var richResult;
  14294. if (richItemNames) {
  14295. richResult = {};
  14296. for (var name_1 in richItemNames) {
  14297. if (richItemNames.hasOwnProperty(name_1)) {
  14298. // Cascade is supported in rich.
  14299. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14300. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14301. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14302. // That might confuses users. So probably we should put `textStyleModel` as the
  14303. // root ancestor of the `richTextStyle`. But that would be a break change.
  14304. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14305. }
  14306. }
  14307. }
  14308. if (richResult) {
  14309. textStyle.rich = richResult;
  14310. }
  14311. var overflow = textStyleModel.get('overflow');
  14312. if (overflow) {
  14313. textStyle.overflow = overflow;
  14314. }
  14315. var margin = textStyleModel.get('minMargin');
  14316. if (margin != null) {
  14317. textStyle.margin = margin;
  14318. }
  14319. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14320. } // Consider case:
  14321. // {
  14322. // data: [{
  14323. // value: 12,
  14324. // label: {
  14325. // rich: {
  14326. // // no 'a' here but using parent 'a'.
  14327. // }
  14328. // }
  14329. // }],
  14330. // rich: {
  14331. // a: { ... }
  14332. // }
  14333. // }
  14334. // TODO TextStyleModel
  14335. function getRichItemNames(textStyleModel) {
  14336. // Use object to remove duplicated names.
  14337. var richItemNameMap;
  14338. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14339. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14340. if (rich) {
  14341. richItemNameMap = richItemNameMap || {};
  14342. var richKeys = keys(rich);
  14343. for (var i = 0; i < richKeys.length; i++) {
  14344. var richKey = richKeys[i];
  14345. richItemNameMap[richKey] = 1;
  14346. }
  14347. }
  14348. textStyleModel = textStyleModel.parentModel;
  14349. }
  14350. return richItemNameMap;
  14351. }
  14352. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14353. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  14354. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14355. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14356. // In merge mode, default value should not be given.
  14357. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14358. var inheritColor = opt && opt.inheritColor;
  14359. var fillColor = textStyleModel.getShallow('color');
  14360. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14361. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14362. if (fillColor === 'inherit' || fillColor === 'auto') {
  14363. if ("development" !== 'production') {
  14364. if (fillColor === 'auto') {
  14365. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14366. }
  14367. }
  14368. if (inheritColor) {
  14369. fillColor = inheritColor;
  14370. } else {
  14371. fillColor = null;
  14372. }
  14373. }
  14374. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14375. if ("development" !== 'production') {
  14376. if (strokeColor === 'auto') {
  14377. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14378. }
  14379. }
  14380. if (inheritColor) {
  14381. strokeColor = inheritColor;
  14382. } else {
  14383. strokeColor = null;
  14384. }
  14385. }
  14386. if (!isAttached) {
  14387. // Only use default global textStyle.color if text is individual.
  14388. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14389. fillColor = fillColor || globalTextStyle.color;
  14390. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14391. }
  14392. if (fillColor != null) {
  14393. textStyle.fill = fillColor;
  14394. }
  14395. if (strokeColor != null) {
  14396. textStyle.stroke = strokeColor;
  14397. }
  14398. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14399. if (textBorderWidth != null) {
  14400. textStyle.lineWidth = textBorderWidth;
  14401. }
  14402. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14403. if (textBorderType != null) {
  14404. textStyle.lineDash = textBorderType;
  14405. }
  14406. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14407. if (textBorderDashOffset != null) {
  14408. textStyle.lineDashOffset = textBorderDashOffset;
  14409. }
  14410. if (!isNotNormal && opacity == null && !inRich) {
  14411. opacity = opt && opt.defaultOpacity;
  14412. }
  14413. if (opacity != null) {
  14414. textStyle.opacity = opacity;
  14415. } // TODO
  14416. if (!isNotNormal && !isAttached) {
  14417. // Set default finally.
  14418. if (textStyle.fill == null && opt.inheritColor) {
  14419. textStyle.fill = opt.inheritColor;
  14420. }
  14421. } // Do not use `getFont` here, because merge should be supported, where
  14422. // part of these properties may be changed in emphasis style, and the
  14423. // others should remain their original value got from normal style.
  14424. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14425. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14426. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14427. if (val != null) {
  14428. textStyle[key] = val;
  14429. }
  14430. }
  14431. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14432. var key = TEXT_PROPS_SELF[i];
  14433. var val = textStyleModel.getShallow(key);
  14434. if (val != null) {
  14435. textStyle[key] = val;
  14436. }
  14437. }
  14438. if (textStyle.verticalAlign == null) {
  14439. var baseline = textStyleModel.getShallow('baseline');
  14440. if (baseline != null) {
  14441. textStyle.verticalAlign = baseline;
  14442. }
  14443. }
  14444. if (!isBlock || !opt.disableBox) {
  14445. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  14446. var key = TEXT_PROPS_BOX[i];
  14447. var val = textStyleModel.getShallow(key);
  14448. if (val != null) {
  14449. textStyle[key] = val;
  14450. }
  14451. }
  14452. var borderType = textStyleModel.getShallow('borderType');
  14453. if (borderType != null) {
  14454. textStyle.borderDash = borderType;
  14455. }
  14456. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  14457. if ("development" !== 'production') {
  14458. if (textStyle.backgroundColor === 'auto') {
  14459. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  14460. }
  14461. }
  14462. textStyle.backgroundColor = inheritColor;
  14463. }
  14464. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  14465. if ("development" !== 'production') {
  14466. if (textStyle.borderColor === 'auto') {
  14467. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  14468. }
  14469. }
  14470. textStyle.borderColor = inheritColor;
  14471. }
  14472. }
  14473. }
  14474. function getFont(opt, ecModel) {
  14475. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14476. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14477. 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(' '));
  14478. }
  14479. var labelInner = makeInner();
  14480. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  14481. if (!label) {
  14482. return;
  14483. }
  14484. var obj = labelInner(label);
  14485. obj.prevValue = obj.value;
  14486. obj.value = value;
  14487. var normalLabelModel = labelStatesModels.normal;
  14488. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  14489. if (obj.valueAnimation) {
  14490. obj.precision = normalLabelModel.get('precision');
  14491. obj.defaultInterpolatedText = getDefaultText;
  14492. obj.statesModels = labelStatesModels;
  14493. }
  14494. }
  14495. function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) {
  14496. var labelInnerStore = labelInner(textEl);
  14497. if (!labelInnerStore.valueAnimation) {
  14498. return;
  14499. }
  14500. var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText; // Consider the case that being animating, do not use the `obj.value`,
  14501. // Otherwise it will jump to the `obj.value` when this new animation started.
  14502. var currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue);
  14503. var targetValue = labelInnerStore.value;
  14504. function during(percent) {
  14505. var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent);
  14506. labelInnerStore.interpolatedValue = percent === 1 ? null : interpolated;
  14507. var labelText = getLabelText({
  14508. labelDataIndex: dataIndex,
  14509. labelFetcher: labelFetcher,
  14510. defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + ''
  14511. }, labelInnerStore.statesModels, interpolated);
  14512. setLabelText(textEl, labelText);
  14513. }
  14514. (currValue == null ? initProps : updateProps)(textEl, {}, animatableModel, dataIndex, null, during);
  14515. }
  14516. var PATH_COLOR = ['textStyle', 'color']; // TODO Performance improvement?
  14517. var tmpRichText = new ZRText();
  14518. var TextStyleMixin =
  14519. /** @class */
  14520. function () {
  14521. function TextStyleMixin() {}
  14522. /**
  14523. * Get color property or get color from option.textStyle.color
  14524. */
  14525. // TODO Callback
  14526. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  14527. var ecModel = this.ecModel;
  14528. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  14529. };
  14530. /**
  14531. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14532. * @return {string}
  14533. */
  14534. TextStyleMixin.prototype.getFont = function () {
  14535. return getFont({
  14536. fontStyle: this.getShallow('fontStyle'),
  14537. fontWeight: this.getShallow('fontWeight'),
  14538. fontSize: this.getShallow('fontSize'),
  14539. fontFamily: this.getShallow('fontFamily')
  14540. }, this.ecModel);
  14541. };
  14542. TextStyleMixin.prototype.getTextRect = function (text) {
  14543. tmpRichText.useStyle({
  14544. text: text,
  14545. fontStyle: this.getShallow('fontStyle'),
  14546. fontWeight: this.getShallow('fontWeight'),
  14547. fontSize: this.getShallow('fontSize'),
  14548. fontFamily: this.getShallow('fontFamily'),
  14549. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14550. padding: this.getShallow('padding'),
  14551. lineHeight: this.getShallow('lineHeight'),
  14552. rich: this.getShallow('rich')
  14553. });
  14554. tmpRichText.update();
  14555. return tmpRichText.getBoundingRect();
  14556. };
  14557. return TextStyleMixin;
  14558. }();
  14559. 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`.
  14560. // So do not transfer decal directly.
  14561. ];
  14562. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  14563. var LineStyleMixin =
  14564. /** @class */
  14565. function () {
  14566. function LineStyleMixin() {}
  14567. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  14568. return getLineStyle(this, excludes);
  14569. };
  14570. return LineStyleMixin;
  14571. }();
  14572. 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`.
  14573. // So do not transfer decal directly.
  14574. ];
  14575. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  14576. var ItemStyleMixin =
  14577. /** @class */
  14578. function () {
  14579. function ItemStyleMixin() {}
  14580. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  14581. return getItemStyle(this, excludes, includes);
  14582. };
  14583. return ItemStyleMixin;
  14584. }();
  14585. var Model =
  14586. /** @class */
  14587. function () {
  14588. function Model(option, parentModel, ecModel) {
  14589. this.parentModel = parentModel;
  14590. this.ecModel = ecModel;
  14591. this.option = option; // Simple optimization
  14592. // if (this.init) {
  14593. // if (arguments.length <= 4) {
  14594. // this.init(option, parentModel, ecModel, extraOpt);
  14595. // }
  14596. // else {
  14597. // this.init.apply(this, arguments);
  14598. // }
  14599. // }
  14600. }
  14601. Model.prototype.init = function (option, parentModel, ecModel) {
  14602. var rest = [];
  14603. for (var _i = 3; _i < arguments.length; _i++) {
  14604. rest[_i - 3] = arguments[_i];
  14605. }
  14606. };
  14607. /**
  14608. * Merge the input option to me.
  14609. */
  14610. Model.prototype.mergeOption = function (option, ecModel) {
  14611. merge(this.option, option, true);
  14612. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `ModelOption`
  14613. // TODO: TYPE strict key check?
  14614. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  14615. Model.prototype.get = function (path, ignoreParent) {
  14616. if (path == null) {
  14617. return this.option;
  14618. }
  14619. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  14620. };
  14621. Model.prototype.getShallow = function (key, ignoreParent) {
  14622. var option = this.option;
  14623. var val = option == null ? option : option[key];
  14624. if (val == null && !ignoreParent) {
  14625. var parentModel = this.parentModel;
  14626. if (parentModel) {
  14627. // FIXME:TS do not know how to make it works
  14628. val = parentModel.getShallow(key);
  14629. }
  14630. }
  14631. return val;
  14632. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `Model<ModelOption>`
  14633. // getModel(path: string | string[], parentModel?: Model): Model;
  14634. // TODO 'xxx.yyy.zzz' is deprecated
  14635. Model.prototype.getModel = function (path, parentModel) {
  14636. var hasPath = path != null;
  14637. var pathFinal = hasPath ? this.parsePath(path) : null;
  14638. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  14639. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  14640. return new Model(obj, parentModel, this.ecModel);
  14641. };
  14642. /**
  14643. * Squash option stack into one.
  14644. * parentModel will be removed after squashed.
  14645. *
  14646. * NOTE: resolveParentPath will not be applied here for simplicity. DON'T use this function
  14647. * if resolveParentPath is modified.
  14648. *
  14649. * @param deepMerge If do deep merge. Default to be false.
  14650. */
  14651. // squash(
  14652. // deepMerge?: boolean,
  14653. // handleCallback?: (func: () => object) => object
  14654. // ) {
  14655. // const optionStack = [];
  14656. // let model: Model = this;
  14657. // while (model) {
  14658. // if (model.option) {
  14659. // optionStack.push(model.option);
  14660. // }
  14661. // model = model.parentModel;
  14662. // }
  14663. // const newOption = {} as Opt;
  14664. // let option;
  14665. // while (option = optionStack.pop()) { // Top down merge
  14666. // if (isFunction(option) && handleCallback) {
  14667. // option = handleCallback(option);
  14668. // }
  14669. // if (deepMerge) {
  14670. // merge(newOption, option);
  14671. // }
  14672. // else {
  14673. // extend(newOption, option);
  14674. // }
  14675. // }
  14676. // // Remove parentModel
  14677. // this.option = newOption;
  14678. // this.parentModel = null;
  14679. // }
  14680. /**
  14681. * If model has option
  14682. */
  14683. Model.prototype.isEmpty = function () {
  14684. return this.option == null;
  14685. };
  14686. Model.prototype.restoreData = function () {}; // Pending
  14687. Model.prototype.clone = function () {
  14688. var Ctor = this.constructor;
  14689. return new Ctor(clone(this.option));
  14690. }; // setReadOnly(properties): void {
  14691. // clazzUtil.setReadOnly(this, properties);
  14692. // }
  14693. // If path is null/undefined, return null/undefined.
  14694. Model.prototype.parsePath = function (path) {
  14695. if (typeof path === 'string') {
  14696. return path.split('.');
  14697. }
  14698. return path;
  14699. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  14700. // Default to be a identity resolver.
  14701. // Can be modified to a different resolver.
  14702. Model.prototype.resolveParentPath = function (path) {
  14703. return path;
  14704. }; // FIXME:TS check whether put this method here
  14705. Model.prototype.isAnimationEnabled = function () {
  14706. if (!env.node && this.option) {
  14707. if (this.option.animation != null) {
  14708. return !!this.option.animation;
  14709. } else if (this.parentModel) {
  14710. return this.parentModel.isAnimationEnabled();
  14711. }
  14712. }
  14713. };
  14714. Model.prototype._doGet = function (pathArr, parentModel) {
  14715. var obj = this.option;
  14716. if (!pathArr) {
  14717. return obj;
  14718. }
  14719. for (var i = 0; i < pathArr.length; i++) {
  14720. // Ignore empty
  14721. if (!pathArr[i]) {
  14722. continue;
  14723. } // obj could be number/string/... (like 0)
  14724. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  14725. if (obj == null) {
  14726. break;
  14727. }
  14728. }
  14729. if (obj == null && parentModel) {
  14730. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  14731. }
  14732. return obj;
  14733. };
  14734. return Model;
  14735. }();
  14736. enableClassExtend(Model);
  14737. enableClassCheck(Model);
  14738. mixin(Model, LineStyleMixin);
  14739. mixin(Model, ItemStyleMixin);
  14740. mixin(Model, AreaStyleMixin);
  14741. mixin(Model, TextStyleMixin);
  14742. var base = Math.round(Math.random() * 10);
  14743. /**
  14744. * @public
  14745. * @param {string} type
  14746. * @return {string}
  14747. */
  14748. function getUID(type) {
  14749. // Considering the case of crossing js context,
  14750. // use Math.random to make id as unique as possible.
  14751. return [type || '', base++].join('_');
  14752. }
  14753. /**
  14754. * Implements `SubTypeDefaulterManager` for `target`.
  14755. */
  14756. function enableSubTypeDefaulter(target) {
  14757. var subTypeDefaulters = {};
  14758. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  14759. var componentTypeInfo = parseClassType(componentType);
  14760. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  14761. };
  14762. target.determineSubType = function (componentType, option) {
  14763. var type = option.type;
  14764. if (!type) {
  14765. var componentTypeMain = parseClassType(componentType).main;
  14766. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14767. type = subTypeDefaulters[componentTypeMain](option);
  14768. }
  14769. }
  14770. return type;
  14771. };
  14772. }
  14773. /**
  14774. * Implements `TopologicalTravelable<any>` for `entity`.
  14775. *
  14776. * Topological travel on Activity Network (Activity On Vertices).
  14777. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14778. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14779. * If there is circle dependencey, Error will be thrown.
  14780. */
  14781. function enableTopologicalTravel(entity, dependencyGetter) {
  14782. /**
  14783. * @param targetNameList Target Component type list.
  14784. * Can be ['aa', 'bb', 'aa.xx']
  14785. * @param fullNameList By which we can build dependency graph.
  14786. * @param callback Params: componentType, dependencies.
  14787. * @param context Scope of callback.
  14788. */
  14789. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14790. if (!targetNameList.length) {
  14791. return;
  14792. }
  14793. var result = makeDepndencyGraph(fullNameList);
  14794. var graph = result.graph;
  14795. var noEntryList = result.noEntryList;
  14796. var targetNameSet = {};
  14797. each(targetNameList, function (name) {
  14798. targetNameSet[name] = true;
  14799. });
  14800. while (noEntryList.length) {
  14801. var currComponentType = noEntryList.pop();
  14802. var currVertex = graph[currComponentType];
  14803. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14804. if (isInTargetNameSet) {
  14805. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14806. delete targetNameSet[currComponentType];
  14807. }
  14808. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  14809. }
  14810. each(targetNameSet, function () {
  14811. var errMsg = '';
  14812. if ("development" !== 'production') {
  14813. errMsg = makePrintable('Circle dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  14814. }
  14815. throw new Error(errMsg);
  14816. });
  14817. function removeEdge(succComponentType) {
  14818. graph[succComponentType].entryCount--;
  14819. if (graph[succComponentType].entryCount === 0) {
  14820. noEntryList.push(succComponentType);
  14821. }
  14822. } // Consider this case: legend depends on series, and we call
  14823. // chart.setOption({series: [...]}), where only series is in option.
  14824. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14825. // not be called, but only sereis.mergeOption is called. Thus legend
  14826. // have no chance to update its local record about series (like which
  14827. // name of series is available in legend).
  14828. function removeEdgeAndAdd(succComponentType) {
  14829. targetNameSet[succComponentType] = true;
  14830. removeEdge(succComponentType);
  14831. }
  14832. };
  14833. function makeDepndencyGraph(fullNameList) {
  14834. var graph = {};
  14835. var noEntryList = [];
  14836. each(fullNameList, function (name) {
  14837. var thisItem = createDependencyGraphItem(graph, name);
  14838. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14839. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14840. thisItem.entryCount = availableDeps.length;
  14841. if (thisItem.entryCount === 0) {
  14842. noEntryList.push(name);
  14843. }
  14844. each(availableDeps, function (dependentName) {
  14845. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14846. thisItem.predecessor.push(dependentName);
  14847. }
  14848. var thatItem = createDependencyGraphItem(graph, dependentName);
  14849. if (indexOf(thatItem.successor, dependentName) < 0) {
  14850. thatItem.successor.push(name);
  14851. }
  14852. });
  14853. });
  14854. return {
  14855. graph: graph,
  14856. noEntryList: noEntryList
  14857. };
  14858. }
  14859. function createDependencyGraphItem(graph, name) {
  14860. if (!graph[name]) {
  14861. graph[name] = {
  14862. predecessor: [],
  14863. successor: []
  14864. };
  14865. }
  14866. return graph[name];
  14867. }
  14868. function getAvailableDependencies(originalDeps, fullNameList) {
  14869. var availableDeps = [];
  14870. each(originalDeps, function (dep) {
  14871. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  14872. });
  14873. return availableDeps;
  14874. }
  14875. }
  14876. function inheritDefaultOption(superOption, subOption) {
  14877. // See also `model/Component.ts#getDefaultOption`
  14878. return merge(merge({}, superOption, true), subOption, true);
  14879. }
  14880. /*
  14881. * Licensed to the Apache Software Foundation (ASF) under one
  14882. * or more contributor license agreements. See the NOTICE file
  14883. * distributed with this work for additional information
  14884. * regarding copyright ownership. The ASF licenses this file
  14885. * to you under the Apache License, Version 2.0 (the
  14886. * "License"); you may not use this file except in compliance
  14887. * with the License. You may obtain a copy of the License at
  14888. *
  14889. * http://www.apache.org/licenses/LICENSE-2.0
  14890. *
  14891. * Unless required by applicable law or agreed to in writing,
  14892. * software distributed under the License is distributed on an
  14893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14894. * KIND, either express or implied. See the License for the
  14895. * specific language governing permissions and limitations
  14896. * under the License.
  14897. */
  14898. /**
  14899. * AUTO-GENERATED FILE. DO NOT MODIFY.
  14900. */
  14901. /*
  14902. * Licensed to the Apache Software Foundation (ASF) under one
  14903. * or more contributor license agreements. See the NOTICE file
  14904. * distributed with this work for additional information
  14905. * regarding copyright ownership. The ASF licenses this file
  14906. * to you under the Apache License, Version 2.0 (the
  14907. * "License"); you may not use this file except in compliance
  14908. * with the License. You may obtain a copy of the License at
  14909. *
  14910. * http://www.apache.org/licenses/LICENSE-2.0
  14911. *
  14912. * Unless required by applicable law or agreed to in writing,
  14913. * software distributed under the License is distributed on an
  14914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14915. * KIND, either express or implied. See the License for the
  14916. * specific language governing permissions and limitations
  14917. * under the License.
  14918. */
  14919. /**
  14920. * Language: English.
  14921. */
  14922. var langEN = {
  14923. time: {
  14924. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  14925. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  14926. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  14927. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  14928. },
  14929. legend: {
  14930. selector: {
  14931. all: 'All',
  14932. inverse: 'Inv'
  14933. }
  14934. },
  14935. toolbox: {
  14936. brush: {
  14937. title: {
  14938. rect: 'Box Select',
  14939. polygon: 'Lasso Select',
  14940. lineX: 'Horizontally Select',
  14941. lineY: 'Vertically Select',
  14942. keep: 'Keep Selections',
  14943. clear: 'Clear Selections'
  14944. }
  14945. },
  14946. dataView: {
  14947. title: 'Data View',
  14948. lang: ['Data View', 'Close', 'Refresh']
  14949. },
  14950. dataZoom: {
  14951. title: {
  14952. zoom: 'Zoom',
  14953. back: 'Zoom Reset'
  14954. }
  14955. },
  14956. magicType: {
  14957. title: {
  14958. line: 'Switch to Line Chart',
  14959. bar: 'Switch to Bar Chart',
  14960. stack: 'Stack',
  14961. tiled: 'Tile'
  14962. }
  14963. },
  14964. restore: {
  14965. title: 'Restore'
  14966. },
  14967. saveAsImage: {
  14968. title: 'Save as Image',
  14969. lang: ['Right Click to Save Image']
  14970. }
  14971. },
  14972. series: {
  14973. typeNames: {
  14974. pie: 'Pie chart',
  14975. bar: 'Bar chart',
  14976. line: 'Line chart',
  14977. scatter: 'Scatter plot',
  14978. effectScatter: 'Ripple scatter plot',
  14979. radar: 'Radar chart',
  14980. tree: 'Tree',
  14981. treemap: 'Treemap',
  14982. boxplot: 'Boxplot',
  14983. candlestick: 'Candlestick',
  14984. k: 'K line chart',
  14985. heatmap: 'Heat map',
  14986. map: 'Map',
  14987. parallel: 'Parallel coordinate map',
  14988. lines: 'Line graph',
  14989. graph: 'Relationship graph',
  14990. sankey: 'Sankey diagram',
  14991. funnel: 'Funnel chart',
  14992. gauge: 'Guage',
  14993. pictorialBar: 'Pictorial bar',
  14994. themeRiver: 'Theme River Map',
  14995. sunburst: 'Sunburst'
  14996. }
  14997. },
  14998. aria: {
  14999. general: {
  15000. withTitle: 'This is a chart about "{title}"',
  15001. withoutTitle: 'This is a chart'
  15002. },
  15003. series: {
  15004. single: {
  15005. prefix: '',
  15006. withName: ' with type {seriesType} named {seriesName}.',
  15007. withoutName: ' with type {seriesType}.'
  15008. },
  15009. multiple: {
  15010. prefix: '. It consists of {seriesCount} series count.',
  15011. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15012. withoutName: ' The {seriesId} series is a {seriesType}.',
  15013. separator: {
  15014. middle: '',
  15015. end: ''
  15016. }
  15017. }
  15018. },
  15019. data: {
  15020. allData: 'The data is as follows: ',
  15021. partialData: 'The first {displayCnt} items are: ',
  15022. withName: 'the data for {name} is {value}',
  15023. withoutName: '{value}',
  15024. separator: {
  15025. middle: ', ',
  15026. end: '. '
  15027. }
  15028. }
  15029. }
  15030. };
  15031. /*
  15032. * Licensed to the Apache Software Foundation (ASF) under one
  15033. * or more contributor license agreements. See the NOTICE file
  15034. * distributed with this work for additional information
  15035. * regarding copyright ownership. The ASF licenses this file
  15036. * to you under the Apache License, Version 2.0 (the
  15037. * "License"); you may not use this file except in compliance
  15038. * with the License. You may obtain a copy of the License at
  15039. *
  15040. * http://www.apache.org/licenses/LICENSE-2.0
  15041. *
  15042. * Unless required by applicable law or agreed to in writing,
  15043. * software distributed under the License is distributed on an
  15044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15045. * KIND, either express or implied. See the License for the
  15046. * specific language governing permissions and limitations
  15047. * under the License.
  15048. */
  15049. /**
  15050. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15051. */
  15052. /*
  15053. * Licensed to the Apache Software Foundation (ASF) under one
  15054. * or more contributor license agreements. See the NOTICE file
  15055. * distributed with this work for additional information
  15056. * regarding copyright ownership. The ASF licenses this file
  15057. * to you under the Apache License, Version 2.0 (the
  15058. * "License"); you may not use this file except in compliance
  15059. * with the License. You may obtain a copy of the License at
  15060. *
  15061. * http://www.apache.org/licenses/LICENSE-2.0
  15062. *
  15063. * Unless required by applicable law or agreed to in writing,
  15064. * software distributed under the License is distributed on an
  15065. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15066. * KIND, either express or implied. See the License for the
  15067. * specific language governing permissions and limitations
  15068. * under the License.
  15069. */
  15070. var langZH = {
  15071. time: {
  15072. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15073. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15074. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15075. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15076. },
  15077. legend: {
  15078. selector: {
  15079. all: '全选',
  15080. inverse: '反选'
  15081. }
  15082. },
  15083. toolbox: {
  15084. brush: {
  15085. title: {
  15086. rect: '矩形选择',
  15087. polygon: '圈选',
  15088. lineX: '横向选择',
  15089. lineY: '纵向选择',
  15090. keep: '保持选择',
  15091. clear: '清除选择'
  15092. }
  15093. },
  15094. dataView: {
  15095. title: '数据视图',
  15096. lang: ['数据视图', '关闭', '刷新']
  15097. },
  15098. dataZoom: {
  15099. title: {
  15100. zoom: '区域缩放',
  15101. back: '区域缩放还原'
  15102. }
  15103. },
  15104. magicType: {
  15105. title: {
  15106. line: '切换为折线图',
  15107. bar: '切换为柱状图',
  15108. stack: '切换为堆叠',
  15109. tiled: '切换为平铺'
  15110. }
  15111. },
  15112. restore: {
  15113. title: '还原'
  15114. },
  15115. saveAsImage: {
  15116. title: '保存为图片',
  15117. lang: ['右键另存为图片']
  15118. }
  15119. },
  15120. series: {
  15121. typeNames: {
  15122. pie: '饼图',
  15123. bar: '柱状图',
  15124. line: '折线图',
  15125. scatter: '散点图',
  15126. effectScatter: '涟漪散点图',
  15127. radar: '雷达图',
  15128. tree: '树图',
  15129. treemap: '矩形树图',
  15130. boxplot: '箱型图',
  15131. candlestick: 'K线图',
  15132. k: 'K线图',
  15133. heatmap: '热力图',
  15134. map: '地图',
  15135. parallel: '平行坐标图',
  15136. lines: '线图',
  15137. graph: '关系图',
  15138. sankey: '桑基图',
  15139. funnel: '漏斗图',
  15140. gauge: '仪表盘图',
  15141. pictorialBar: '象形柱图',
  15142. themeRiver: '主题河流图',
  15143. sunburst: '旭日图'
  15144. }
  15145. },
  15146. aria: {
  15147. general: {
  15148. withTitle: '这是一个关于“{title}”的图表。',
  15149. withoutTitle: '这是一个图表,'
  15150. },
  15151. series: {
  15152. single: {
  15153. prefix: '',
  15154. withName: '图表类型是{seriesType},表示{seriesName}。',
  15155. withoutName: '图表类型是{seriesType}。'
  15156. },
  15157. multiple: {
  15158. prefix: '它由{seriesCount}个图表系列组成。',
  15159. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15160. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15161. separator: {
  15162. middle: ';',
  15163. end: '。'
  15164. }
  15165. }
  15166. },
  15167. data: {
  15168. allData: '其数据是——',
  15169. partialData: '其中,前{displayCnt}项是——',
  15170. withName: '{name}的数据是{value}',
  15171. withoutName: '{value}',
  15172. separator: {
  15173. middle: ',',
  15174. end: ''
  15175. }
  15176. }
  15177. }
  15178. };
  15179. var LOCALE_ZH = 'ZH';
  15180. var LOCALE_EN = 'EN';
  15181. var DEFAULT_LOCALE = LOCALE_EN;
  15182. var localeStorage = {};
  15183. var localeModels = {};
  15184. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15185. var langStr = (
  15186. /* eslint-disable-next-line */
  15187. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15188. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15189. }();
  15190. function registerLocale(locale, localeObj) {
  15191. locale = locale.toUpperCase();
  15192. localeModels[locale] = new Model(localeObj);
  15193. localeStorage[locale] = localeObj;
  15194. } // export function getLocale(locale: string) {
  15195. // return localeStorage[locale];
  15196. // }
  15197. function createLocaleObject(locale) {
  15198. if (isString(locale)) {
  15199. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15200. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15201. return clone(localeObj);
  15202. } else {
  15203. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15204. }
  15205. } else {
  15206. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15207. }
  15208. }
  15209. function getLocaleModel(lang) {
  15210. return localeModels[lang];
  15211. }
  15212. function getDefaultLocaleModel() {
  15213. return localeModels[DEFAULT_LOCALE];
  15214. } // Default locale
  15215. registerLocale(LOCALE_EN, langEN);
  15216. registerLocale(LOCALE_ZH, langZH);
  15217. var ONE_SECOND = 1000;
  15218. var ONE_MINUTE = ONE_SECOND * 60;
  15219. var ONE_HOUR = ONE_MINUTE * 60;
  15220. var ONE_DAY = ONE_HOUR * 24;
  15221. var ONE_YEAR = ONE_DAY * 365;
  15222. var defaultLeveledFormatter = {
  15223. year: '{yyyy}',
  15224. month: '{MMM}',
  15225. day: '{d}',
  15226. hour: '{HH}:{mm}',
  15227. minute: '{HH}:{mm}',
  15228. second: '{HH}:{mm}:{ss}',
  15229. millisecond: '{hh}:{mm}:{ss} {SSS}',
  15230. none: '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss} {SSS}'
  15231. };
  15232. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15233. var fullLeveledFormatter = {
  15234. year: '{yyyy}',
  15235. month: '{yyyy}-{MM}',
  15236. day: fullDayFormatter,
  15237. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15238. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15239. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15240. millisecond: defaultLeveledFormatter.none
  15241. };
  15242. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15243. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15244. function pad(str, len) {
  15245. str += '';
  15246. return '0000'.substr(0, len - str.length) + str;
  15247. }
  15248. function getPrimaryTimeUnit(timeUnit) {
  15249. switch (timeUnit) {
  15250. case 'half-year':
  15251. case 'quarter':
  15252. return 'month';
  15253. case 'week':
  15254. case 'half-week':
  15255. return 'day';
  15256. case 'half-day':
  15257. case 'quarter-day':
  15258. return 'hour';
  15259. default:
  15260. // year, minutes, second, milliseconds
  15261. return timeUnit;
  15262. }
  15263. }
  15264. function isPrimaryTimeUnit(timeUnit) {
  15265. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15266. }
  15267. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15268. switch (timeUnit) {
  15269. case 'year':
  15270. case 'month':
  15271. return 'day';
  15272. case 'millisecond':
  15273. return 'millisecond';
  15274. default:
  15275. // Also for day, hour, minute, second
  15276. return 'second';
  15277. }
  15278. }
  15279. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15280. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15281. time, template, isUTC, lang) {
  15282. var date = parseDate(time);
  15283. var y = date[fullYearGetterName(isUTC)]();
  15284. var M = date[monthGetterName(isUTC)]() + 1;
  15285. var q = Math.floor((M - 1) / 4) + 1;
  15286. var d = date[dateGetterName(isUTC)]();
  15287. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15288. var H = date[hoursGetterName(isUTC)]();
  15289. var h = (H - 1) % 12 + 1;
  15290. var m = date[minutesGetterName(isUTC)]();
  15291. var s = date[secondsGetterName(isUTC)]();
  15292. var S = date[millisecondsGetterName(isUTC)]();
  15293. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15294. var timeModel = localeModel.getModel('time');
  15295. var month = timeModel.get('month');
  15296. var monthAbbr = timeModel.get('monthAbbr');
  15297. var dayOfWeek = timeModel.get('dayOfWeek');
  15298. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15299. 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 + '');
  15300. }
  15301. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15302. var template = null;
  15303. if (typeof formatter === 'string') {
  15304. // Single formatter for all units at all levels
  15305. template = formatter;
  15306. } else if (typeof formatter === 'function') {
  15307. // Callback formatter
  15308. template = formatter(tick.value, idx, {
  15309. level: tick.level
  15310. });
  15311. } else {
  15312. var defaults$1 = extend({}, defaultLeveledFormatter);
  15313. if (tick.level > 0) {
  15314. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15315. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15316. }
  15317. }
  15318. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15319. : defaults(formatter, defaults$1) : defaults$1;
  15320. var unit = getUnitFromValue(tick.value, isUTC);
  15321. if (mergedFormatter[unit]) {
  15322. template = mergedFormatter[unit];
  15323. } else if (mergedFormatter.inherit) {
  15324. // Unit formatter is not defined and should inherit from bigger units
  15325. var targetId = timeUnits.indexOf(unit);
  15326. for (var i = targetId - 1; i >= 0; --i) {
  15327. if (mergedFormatter[unit]) {
  15328. template = mergedFormatter[unit];
  15329. break;
  15330. }
  15331. }
  15332. template = template || defaults$1.none;
  15333. }
  15334. if (isArray(template)) {
  15335. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15336. levelId = Math.min(levelId, template.length - 1);
  15337. template = template[levelId];
  15338. }
  15339. }
  15340. return format(new Date(tick.value), template, isUTC, lang);
  15341. }
  15342. function getUnitFromValue(value, isUTC) {
  15343. var date = parseDate(value);
  15344. var M = date[monthGetterName(isUTC)]() + 1;
  15345. var d = date[dateGetterName(isUTC)]();
  15346. var h = date[hoursGetterName(isUTC)]();
  15347. var m = date[minutesGetterName(isUTC)]();
  15348. var s = date[secondsGetterName(isUTC)]();
  15349. var S = date[millisecondsGetterName(isUTC)]();
  15350. var isSecond = S === 0;
  15351. var isMinute = isSecond && s === 0;
  15352. var isHour = isMinute && m === 0;
  15353. var isDay = isHour && h === 0;
  15354. var isMonth = isDay && d === 1;
  15355. var isYear = isMonth && M === 1;
  15356. if (isYear) {
  15357. return 'year';
  15358. } else if (isMonth) {
  15359. return 'month';
  15360. } else if (isDay) {
  15361. return 'day';
  15362. } else if (isHour) {
  15363. return 'hour';
  15364. } else if (isMinute) {
  15365. return 'minute';
  15366. } else if (isSecond) {
  15367. return 'second';
  15368. } else {
  15369. return 'millisecond';
  15370. }
  15371. }
  15372. function getUnitValue(value, unit, isUTC) {
  15373. var date = typeof value === 'number' ? parseDate(value) : value;
  15374. unit = unit || getUnitFromValue(value, isUTC);
  15375. switch (unit) {
  15376. case 'year':
  15377. return date[fullYearGetterName(isUTC)]();
  15378. case 'half-year':
  15379. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15380. case 'quarter':
  15381. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15382. case 'month':
  15383. return date[monthGetterName(isUTC)]();
  15384. case 'day':
  15385. return date[dateGetterName(isUTC)]();
  15386. case 'half-day':
  15387. return date[hoursGetterName(isUTC)]() / 24;
  15388. case 'hour':
  15389. return date[hoursGetterName(isUTC)]();
  15390. case 'minute':
  15391. return date[minutesGetterName(isUTC)]();
  15392. case 'second':
  15393. return date[secondsGetterName(isUTC)]();
  15394. case 'millisecond':
  15395. return date[millisecondsGetterName(isUTC)]();
  15396. }
  15397. }
  15398. function fullYearGetterName(isUTC) {
  15399. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15400. }
  15401. function monthGetterName(isUTC) {
  15402. return isUTC ? 'getUTCMonth' : 'getMonth';
  15403. }
  15404. function dateGetterName(isUTC) {
  15405. return isUTC ? 'getUTCDate' : 'getDate';
  15406. }
  15407. function hoursGetterName(isUTC) {
  15408. return isUTC ? 'getUTCHours' : 'getHours';
  15409. }
  15410. function minutesGetterName(isUTC) {
  15411. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15412. }
  15413. function secondsGetterName(isUTC) {
  15414. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15415. }
  15416. function millisecondsGetterName(isUTC) {
  15417. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15418. }
  15419. function fullYearSetterName(isUTC) {
  15420. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15421. }
  15422. function monthSetterName(isUTC) {
  15423. return isUTC ? 'setUTCMonth' : 'setMonth';
  15424. }
  15425. function dateSetterName(isUTC) {
  15426. return isUTC ? 'setUTCDate' : 'setDate';
  15427. }
  15428. function hoursSetterName(isUTC) {
  15429. return isUTC ? 'setUTCHours' : 'setHours';
  15430. }
  15431. function minutesSetterName(isUTC) {
  15432. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15433. }
  15434. function secondsSetterName(isUTC) {
  15435. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15436. }
  15437. function millisecondsSetterName(isUTC) {
  15438. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15439. }
  15440. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15441. deprecateLog('getTextRect is deprecated.');
  15442. var textEl = new ZRText({
  15443. style: {
  15444. text: text,
  15445. font: font,
  15446. align: align,
  15447. verticalAlign: verticalAlign,
  15448. padding: padding,
  15449. rich: rich,
  15450. overflow: truncate ? 'truncate' : null,
  15451. lineHeight: lineHeight
  15452. }
  15453. });
  15454. return textEl.getBoundingRect();
  15455. }
  15456. /**
  15457. * Add a comma each three digit.
  15458. */
  15459. function addCommas(x) {
  15460. if (!isNumeric(x)) {
  15461. return isString(x) ? x : '-';
  15462. }
  15463. var parts = (x + '').split('.');
  15464. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15465. }
  15466. function toCamelCase(str, upperCaseFirst) {
  15467. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15468. return group1.toUpperCase();
  15469. });
  15470. if (upperCaseFirst && str) {
  15471. str = str.charAt(0).toUpperCase() + str.slice(1);
  15472. }
  15473. return str;
  15474. }
  15475. var normalizeCssArray$1 = normalizeCssArray;
  15476. var replaceReg = /([&<>"'])/g;
  15477. var replaceMap = {
  15478. '&': '&amp;',
  15479. '<': '&lt;',
  15480. '>': '&gt;',
  15481. '"': '&quot;',
  15482. '\'': '&#39;'
  15483. };
  15484. function encodeHTML(source) {
  15485. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  15486. return replaceMap[c];
  15487. });
  15488. }
  15489. /**
  15490. * Make value user readable for tooltip and label.
  15491. * "User readable":
  15492. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  15493. * Avoid to display an empty string, which users can not recognize there is
  15494. * a value and it might look like a bug.
  15495. */
  15496. function makeValueReadable(value, valueType, useUTC) {
  15497. var USER_READABLE_DEFUALT_TIME_PATTERN = 'yyyy-MM-dd hh:mm:ss';
  15498. function stringToUserReadable(str) {
  15499. return str && trim(str) ? str : '-';
  15500. }
  15501. function isNumberUserReadable(num) {
  15502. return !!(num != null && !isNaN(num) && isFinite(num));
  15503. }
  15504. var isTypeTime = valueType === 'time';
  15505. var isValueDate = value instanceof Date;
  15506. if (isTypeTime || isValueDate) {
  15507. var date = isTypeTime ? parseDate(value) : value;
  15508. if (!isNaN(+date)) {
  15509. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  15510. } else if (isValueDate) {
  15511. return '-';
  15512. } // In other cases, continue to try to display the value in the following code.
  15513. }
  15514. if (valueType === 'ordinal') {
  15515. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  15516. } // By default.
  15517. var numericResult = numericToNumber(value);
  15518. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : '-';
  15519. }
  15520. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15521. var wrapVar = function (varName, seriesIdx) {
  15522. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15523. };
  15524. /**
  15525. * Template formatter
  15526. * @param {Array.<Object>|Object} paramsList
  15527. */
  15528. function formatTpl(tpl, paramsList, encode) {
  15529. if (!isArray(paramsList)) {
  15530. paramsList = [paramsList];
  15531. }
  15532. var seriesLen = paramsList.length;
  15533. if (!seriesLen) {
  15534. return '';
  15535. }
  15536. var $vars = paramsList[0].$vars || [];
  15537. for (var i = 0; i < $vars.length; i++) {
  15538. var alias = TPL_VAR_ALIAS[i];
  15539. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15540. }
  15541. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15542. for (var k = 0; k < $vars.length; k++) {
  15543. var val = paramsList[seriesIdx][$vars[k]];
  15544. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  15545. }
  15546. }
  15547. return tpl;
  15548. }
  15549. function getTooltipMarker(inOpt, extraCssText) {
  15550. var opt = isString(inOpt) ? {
  15551. color: inOpt,
  15552. extraCssText: extraCssText
  15553. } : inOpt || {};
  15554. var color = opt.color;
  15555. var type = opt.type;
  15556. extraCssText = opt.extraCssText;
  15557. var renderMode = opt.renderMode || 'html';
  15558. if (!color) {
  15559. return '';
  15560. }
  15561. if (renderMode === 'html') {
  15562. 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
  15563. + 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>';
  15564. } else {
  15565. // Should better not to auto generate style name by auto-increment number here.
  15566. // Because this util is usually called in tooltip formatter, which is probably
  15567. // called repeatly when mouse move and the auto-increment number increases fast.
  15568. // Users can make their own style name by theirselves, make it unique and readable.
  15569. var markerId = opt.markerId || 'markerX';
  15570. return {
  15571. renderMode: renderMode,
  15572. content: '{' + markerId + '|} ',
  15573. style: type === 'subItem' ? {
  15574. width: 4,
  15575. height: 4,
  15576. borderRadius: 2,
  15577. backgroundColor: color
  15578. } : {
  15579. width: 10,
  15580. height: 10,
  15581. borderRadius: 5,
  15582. backgroundColor: color
  15583. }
  15584. };
  15585. }
  15586. }
  15587. /**
  15588. * @deprecated Use `time/format` instead.
  15589. * ISO Date format
  15590. * @param {string} tpl
  15591. * @param {number} value
  15592. * @param {boolean} [isUTC=false] Default in local time.
  15593. * see `module:echarts/scale/Time`
  15594. * and `module:echarts/util/number#parseDate`.
  15595. * @inner
  15596. */
  15597. function formatTime(tpl, value, isUTC) {
  15598. if ("development" !== 'production') {
  15599. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  15600. }
  15601. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  15602. tpl = 'MM-dd\nyyyy';
  15603. }
  15604. var date = parseDate(value);
  15605. var utc = isUTC ? 'UTC' : '';
  15606. var y = date['get' + utc + 'FullYear']();
  15607. var M = date['get' + utc + 'Month']() + 1;
  15608. var d = date['get' + utc + 'Date']();
  15609. var h = date['get' + utc + 'Hours']();
  15610. var m = date['get' + utc + 'Minutes']();
  15611. var s = date['get' + utc + 'Seconds']();
  15612. var S = date['get' + utc + 'Milliseconds']();
  15613. 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));
  15614. return tpl;
  15615. }
  15616. /**
  15617. * Capital first
  15618. * @param {string} str
  15619. * @return {string}
  15620. */
  15621. function capitalFirst(str) {
  15622. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15623. }
  15624. /**
  15625. * @return Never be null/undefined.
  15626. */
  15627. function convertToColorString(color, defaultColor) {
  15628. defaultColor = defaultColor || 'transparent';
  15629. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  15630. }
  15631. /**
  15632. * open new tab
  15633. * @param link url
  15634. * @param target blank or self
  15635. */
  15636. function windowOpen(link, target) {
  15637. /* global window */
  15638. if (target === '_blank' || target === 'blank') {
  15639. var blank = window.open();
  15640. blank.opener = null;
  15641. blank.location.href = link;
  15642. } else {
  15643. window.open(link, target);
  15644. }
  15645. }
  15646. var each$1 = each;
  15647. /**
  15648. * @public
  15649. */
  15650. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  15651. /**
  15652. * @public
  15653. */
  15654. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  15655. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15656. var x = 0;
  15657. var y = 0;
  15658. if (maxWidth == null) {
  15659. maxWidth = Infinity;
  15660. }
  15661. if (maxHeight == null) {
  15662. maxHeight = Infinity;
  15663. }
  15664. var currentLineMaxSize = 0;
  15665. group.eachChild(function (child, idx) {
  15666. var rect = child.getBoundingRect();
  15667. var nextChild = group.childAt(idx + 1);
  15668. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15669. var nextX;
  15670. var nextY;
  15671. if (orient === 'horizontal') {
  15672. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  15673. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  15674. // FIXME compare before adding gap?
  15675. if (nextX > maxWidth || child.newline) {
  15676. x = 0;
  15677. nextX = moveX;
  15678. y += currentLineMaxSize + gap;
  15679. currentLineMaxSize = rect.height;
  15680. } else {
  15681. // FIXME: consider rect.y is not `0`?
  15682. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15683. }
  15684. } else {
  15685. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  15686. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  15687. if (nextY > maxHeight || child.newline) {
  15688. x += currentLineMaxSize + gap;
  15689. y = 0;
  15690. nextY = moveY;
  15691. currentLineMaxSize = rect.width;
  15692. } else {
  15693. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15694. }
  15695. }
  15696. if (child.newline) {
  15697. return;
  15698. }
  15699. child.x = x;
  15700. child.y = y;
  15701. child.markRedraw();
  15702. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  15703. });
  15704. }
  15705. /**
  15706. * VBox or HBox layouting
  15707. * @param {string} orient
  15708. * @param {module:zrender/graphic/Group} group
  15709. * @param {number} gap
  15710. * @param {number} [width=Infinity]
  15711. * @param {number} [height=Infinity]
  15712. */
  15713. var box = boxLayout;
  15714. /**
  15715. * VBox layouting
  15716. * @param {module:zrender/graphic/Group} group
  15717. * @param {number} gap
  15718. * @param {number} [width=Infinity]
  15719. * @param {number} [height=Infinity]
  15720. */
  15721. var vbox = curry(boxLayout, 'vertical');
  15722. /**
  15723. * HBox layouting
  15724. * @param {module:zrender/graphic/Group} group
  15725. * @param {number} gap
  15726. * @param {number} [width=Infinity]
  15727. * @param {number} [height=Infinity]
  15728. */
  15729. var hbox = curry(boxLayout, 'horizontal');
  15730. /**
  15731. * Parse position info.
  15732. */
  15733. function getLayoutRect(positionInfo, containerRect, margin) {
  15734. margin = normalizeCssArray$1(margin || 0);
  15735. var containerWidth = containerRect.width;
  15736. var containerHeight = containerRect.height;
  15737. var left = parsePercent$1(positionInfo.left, containerWidth);
  15738. var top = parsePercent$1(positionInfo.top, containerHeight);
  15739. var right = parsePercent$1(positionInfo.right, containerWidth);
  15740. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15741. var width = parsePercent$1(positionInfo.width, containerWidth);
  15742. var height = parsePercent$1(positionInfo.height, containerHeight);
  15743. var verticalMargin = margin[2] + margin[0];
  15744. var horizontalMargin = margin[1] + margin[3];
  15745. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  15746. if (isNaN(width)) {
  15747. width = containerWidth - right - horizontalMargin - left;
  15748. }
  15749. if (isNaN(height)) {
  15750. height = containerHeight - bottom - verticalMargin - top;
  15751. }
  15752. if (aspect != null) {
  15753. // If width and height are not given
  15754. // 1. Graph should not exceeds the container
  15755. // 2. Aspect must be keeped
  15756. // 3. Graph should take the space as more as possible
  15757. // FIXME
  15758. // Margin is not considered, because there is no case that both
  15759. // using margin and aspect so far.
  15760. if (isNaN(width) && isNaN(height)) {
  15761. if (aspect > containerWidth / containerHeight) {
  15762. width = containerWidth * 0.8;
  15763. } else {
  15764. height = containerHeight * 0.8;
  15765. }
  15766. } // Calculate width or height with given aspect
  15767. if (isNaN(width)) {
  15768. width = aspect * height;
  15769. }
  15770. if (isNaN(height)) {
  15771. height = width / aspect;
  15772. }
  15773. } // If left is not specified, calculate left from right and width
  15774. if (isNaN(left)) {
  15775. left = containerWidth - right - width - horizontalMargin;
  15776. }
  15777. if (isNaN(top)) {
  15778. top = containerHeight - bottom - height - verticalMargin;
  15779. } // Align left and top
  15780. switch (positionInfo.left || positionInfo.right) {
  15781. case 'center':
  15782. left = containerWidth / 2 - width / 2 - margin[3];
  15783. break;
  15784. case 'right':
  15785. left = containerWidth - width - horizontalMargin;
  15786. break;
  15787. }
  15788. switch (positionInfo.top || positionInfo.bottom) {
  15789. case 'middle':
  15790. case 'center':
  15791. top = containerHeight / 2 - height / 2 - margin[0];
  15792. break;
  15793. case 'bottom':
  15794. top = containerHeight - height - verticalMargin;
  15795. break;
  15796. } // If something is wrong and left, top, width, height are calculated as NaN
  15797. left = left || 0;
  15798. top = top || 0;
  15799. if (isNaN(width)) {
  15800. // Width may be NaN if only one value is given except width
  15801. width = containerWidth - horizontalMargin - left - (right || 0);
  15802. }
  15803. if (isNaN(height)) {
  15804. // Height may be NaN if only one value is given except height
  15805. height = containerHeight - verticalMargin - top - (bottom || 0);
  15806. }
  15807. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15808. rect.margin = margin;
  15809. return rect;
  15810. }
  15811. /**
  15812. * Position a zr element in viewport
  15813. * Group position is specified by either
  15814. * {left, top}, {right, bottom}
  15815. * If all properties exists, right and bottom will be igonred.
  15816. *
  15817. * Logic:
  15818. * 1. Scale (against origin point in parent coord)
  15819. * 2. Rotate (against origin point in parent coord)
  15820. * 3. Traslate (with el.position by this method)
  15821. * So this method only fixes the last step 'Traslate', which does not affect
  15822. * scaling and rotating.
  15823. *
  15824. * If be called repeatly with the same input el, the same result will be gotten.
  15825. *
  15826. * @param el Should have `getBoundingRect` method.
  15827. * @param positionInfo
  15828. * @param positionInfo.left
  15829. * @param positionInfo.top
  15830. * @param positionInfo.right
  15831. * @param positionInfo.bottom
  15832. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  15833. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  15834. * @param containerRect
  15835. * @param margin
  15836. * @param opt
  15837. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  15838. * @param opt.boundingMode
  15839. * Specify how to calculate boundingRect when locating.
  15840. * 'all': Position the boundingRect that is transformed and uioned
  15841. * both itself and its descendants.
  15842. * This mode simplies confine the elements in the bounding
  15843. * of their container (e.g., using 'right: 0').
  15844. * 'raw': Position the boundingRect that is not transformed and only itself.
  15845. * This mode is useful when you want a element can overflow its
  15846. * container. (Consider a rotated circle needs to be located in a corner.)
  15847. * In this mode positionInfo.width/height can only be number.
  15848. */
  15849. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15850. var h = !opt || !opt.hv || opt.hv[0];
  15851. var v = !opt || !opt.hv || opt.hv[1];
  15852. var boundingMode = opt && opt.boundingMode || 'all';
  15853. if (!h && !v) {
  15854. return;
  15855. }
  15856. var rect;
  15857. if (boundingMode === 'raw') {
  15858. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  15859. } else {
  15860. rect = el.getBoundingRect();
  15861. if (el.needLocalTransform()) {
  15862. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  15863. // which should not be modified.
  15864. rect = rect.clone();
  15865. rect.applyTransform(transform);
  15866. }
  15867. } // The real width and height can not be specified but calculated by the given el.
  15868. var layoutRect = getLayoutRect(defaults({
  15869. width: rect.width,
  15870. height: rect.height
  15871. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  15872. // (see zrender/core/Transformable#getLocalTransform),
  15873. // we can just only modify el.position to get final result.
  15874. var dx = h ? layoutRect.x - rect.x : 0;
  15875. var dy = v ? layoutRect.y - rect.y : 0;
  15876. if (boundingMode === 'raw') {
  15877. el.x = dx;
  15878. el.y = dy;
  15879. } else {
  15880. el.x += dx;
  15881. el.y += dy;
  15882. }
  15883. el.markRedraw();
  15884. }
  15885. function fetchLayoutMode(ins) {
  15886. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  15887. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  15888. type: layoutMode
  15889. } : null;
  15890. }
  15891. /**
  15892. * Consider Case:
  15893. * When default option has {left: 0, width: 100}, and we set {right: 0}
  15894. * through setOption or media query, using normal zrUtil.merge will cause
  15895. * {right: 0} does not take effect.
  15896. *
  15897. * @example
  15898. * ComponentModel.extend({
  15899. * init: function () {
  15900. * ...
  15901. * let inputPositionParams = layout.getLayoutParams(option);
  15902. * this.mergeOption(inputPositionParams);
  15903. * },
  15904. * mergeOption: function (newOption) {
  15905. * newOption && zrUtil.merge(thisOption, newOption, true);
  15906. * layout.mergeLayoutParam(thisOption, newOption);
  15907. * }
  15908. * });
  15909. *
  15910. * @param targetOption
  15911. * @param newOption
  15912. * @param opt
  15913. */
  15914. function mergeLayoutParam(targetOption, newOption, opt) {
  15915. var ignoreSize = opt && opt.ignoreSize;
  15916. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15917. var hResult = merge(HV_NAMES[0], 0);
  15918. var vResult = merge(HV_NAMES[1], 1);
  15919. copy(HV_NAMES[0], targetOption, hResult);
  15920. copy(HV_NAMES[1], targetOption, vResult);
  15921. function merge(names, hvIdx) {
  15922. var newParams = {};
  15923. var newValueCount = 0;
  15924. var merged = {};
  15925. var mergedValueCount = 0;
  15926. var enoughParamNumber = 2;
  15927. each$1(names, function (name) {
  15928. merged[name] = targetOption[name];
  15929. });
  15930. each$1(names, function (name) {
  15931. // Consider case: newOption.width is null, which is
  15932. // set by user for removing width setting.
  15933. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15934. hasValue(newParams, name) && newValueCount++;
  15935. hasValue(merged, name) && mergedValueCount++;
  15936. });
  15937. if (ignoreSize[hvIdx]) {
  15938. // Only one of left/right is premitted to exist.
  15939. if (hasValue(newOption, names[1])) {
  15940. merged[names[2]] = null;
  15941. } else if (hasValue(newOption, names[2])) {
  15942. merged[names[1]] = null;
  15943. }
  15944. return merged;
  15945. } // Case: newOption: {width: ..., right: ...},
  15946. // or targetOption: {right: ...} and newOption: {width: ...},
  15947. // There is no conflict when merged only has params count
  15948. // little than enoughParamNumber.
  15949. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15950. return merged;
  15951. } // Case: newOption: {width: ..., right: ...},
  15952. // Than we can make sure user only want those two, and ignore
  15953. // all origin params in targetOption.
  15954. else if (newValueCount >= enoughParamNumber) {
  15955. return newParams;
  15956. } else {
  15957. // Chose another param from targetOption by priority.
  15958. for (var i = 0; i < names.length; i++) {
  15959. var name_1 = names[i];
  15960. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  15961. newParams[name_1] = targetOption[name_1];
  15962. break;
  15963. }
  15964. }
  15965. return newParams;
  15966. }
  15967. }
  15968. function hasProp(obj, name) {
  15969. return obj.hasOwnProperty(name);
  15970. }
  15971. function hasValue(obj, name) {
  15972. return obj[name] != null && obj[name] !== 'auto';
  15973. }
  15974. function copy(names, target, source) {
  15975. each$1(names, function (name) {
  15976. target[name] = source[name];
  15977. });
  15978. }
  15979. }
  15980. /**
  15981. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15982. */
  15983. function getLayoutParams(source) {
  15984. return copyLayoutParams({}, source);
  15985. }
  15986. /**
  15987. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15988. * @param {Object} source
  15989. * @return {Object} Result contains those props.
  15990. */
  15991. function copyLayoutParams(target, source) {
  15992. source && target && each$1(LOCATION_PARAMS, function (name) {
  15993. source.hasOwnProperty(name) && (target[name] = source[name]);
  15994. });
  15995. return target;
  15996. }
  15997. var inner = makeInner();
  15998. var ComponentModel =
  15999. /** @class */
  16000. function (_super) {
  16001. __extends(ComponentModel, _super);
  16002. function ComponentModel(option, parentModel, ecModel) {
  16003. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16004. _this.uid = getUID('ec_cpt_model');
  16005. return _this;
  16006. }
  16007. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16008. this.mergeDefaultAndTheme(option, ecModel);
  16009. };
  16010. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16011. var layoutMode = fetchLayoutMode(this);
  16012. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16013. var themeModel = ecModel.getTheme();
  16014. merge(option, themeModel.get(this.mainType));
  16015. merge(option, this.getDefaultOption());
  16016. if (layoutMode) {
  16017. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16018. }
  16019. };
  16020. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16021. merge(this.option, option, true);
  16022. var layoutMode = fetchLayoutMode(this);
  16023. if (layoutMode) {
  16024. mergeLayoutParam(this.option, option, layoutMode);
  16025. }
  16026. };
  16027. /**
  16028. * Called immediately after `init` or `mergeOption` of this instance called.
  16029. */
  16030. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16031. /**
  16032. * [How to declare defaultOption]:
  16033. *
  16034. * (A) If using class declaration in typescript (since echarts 5):
  16035. * ```ts
  16036. * import {ComponentOption} from '../model/option';
  16037. * export interface XxxOption extends ComponentOption {
  16038. * aaa: number
  16039. * }
  16040. * export class XxxModel extends Component {
  16041. * static type = 'xxx';
  16042. * static defaultOption: XxxOption = {
  16043. * aaa: 123
  16044. * }
  16045. * }
  16046. * Component.registerClass(XxxModel);
  16047. * ```
  16048. * ```ts
  16049. * import {inheritDefaultOption} from '../util/component';
  16050. * import {XxxModel, XxxOption} from './XxxModel';
  16051. * export interface XxxSubOption extends XxxOption {
  16052. * bbb: number
  16053. * }
  16054. * class XxxSubModel extends XxxModel {
  16055. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16056. * bbb: 456
  16057. * })
  16058. * fn() {
  16059. * let opt = this.getDefaultOption();
  16060. * // opt is {aaa: 123, bbb: 456}
  16061. * }
  16062. * }
  16063. * ```
  16064. *
  16065. * (B) If using class extend (previous approach in echarts 3 & 4):
  16066. * ```js
  16067. * let XxxComponent = Component.extend({
  16068. * defaultOption: {
  16069. * xx: 123
  16070. * }
  16071. * })
  16072. * ```
  16073. * ```js
  16074. * let XxxSubComponent = XxxComponent.extend({
  16075. * defaultOption: {
  16076. * yy: 456
  16077. * },
  16078. * fn: function () {
  16079. * let opt = this.getDefaultOption();
  16080. * // opt is {xx: 123, yy: 456}
  16081. * }
  16082. * })
  16083. * ```
  16084. */
  16085. ComponentModel.prototype.getDefaultOption = function () {
  16086. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16087. // in legacy env and auto merge defaultOption. So if using class
  16088. // declaration, defaultOption should be merged manually.
  16089. if (!isExtendedClass(ctor)) {
  16090. // When using ts class, defaultOption must be declared as static.
  16091. return ctor.defaultOption;
  16092. } // FIXME: remove this approach?
  16093. var fields = inner(this);
  16094. if (!fields.defaultOption) {
  16095. var optList = [];
  16096. var clz = ctor;
  16097. while (clz) {
  16098. var opt = clz.prototype.defaultOption;
  16099. opt && optList.push(opt);
  16100. clz = clz.superClass;
  16101. }
  16102. var defaultOption = {};
  16103. for (var i = optList.length - 1; i >= 0; i--) {
  16104. defaultOption = merge(defaultOption, optList[i], true);
  16105. }
  16106. fields.defaultOption = defaultOption;
  16107. }
  16108. return fields.defaultOption;
  16109. };
  16110. /**
  16111. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16112. * The same behavior as `modelUtil.parseFinder`.
  16113. *
  16114. * @param useDefault In many cases like series refer axis and axis refer grid,
  16115. * If axis index / axis id not specified, use the first target as default.
  16116. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16117. */
  16118. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16119. var indexKey = mainType + 'Index';
  16120. var idKey = mainType + 'Id';
  16121. return queryReferringComponents(this.ecModel, mainType, {
  16122. index: this.get(indexKey, true),
  16123. id: this.get(idKey, true)
  16124. }, opt);
  16125. };
  16126. ComponentModel.prototype.getBoxLayoutParams = function () {
  16127. // Consider itself having box layout configs.
  16128. var boxLayoutModel = this;
  16129. return {
  16130. left: boxLayoutModel.get('left'),
  16131. top: boxLayoutModel.get('top'),
  16132. right: boxLayoutModel.get('right'),
  16133. bottom: boxLayoutModel.get('bottom'),
  16134. width: boxLayoutModel.get('width'),
  16135. height: boxLayoutModel.get('height')
  16136. };
  16137. };
  16138. ComponentModel.protoInitialize = function () {
  16139. var proto = ComponentModel.prototype;
  16140. proto.type = 'component';
  16141. proto.id = '';
  16142. proto.name = '';
  16143. proto.mainType = '';
  16144. proto.subType = '';
  16145. proto.componentIndex = 0;
  16146. }();
  16147. return ComponentModel;
  16148. }(Model);
  16149. mountExtend(ComponentModel, Model);
  16150. enableClassManagement(ComponentModel);
  16151. enableSubTypeDefaulter(ComponentModel);
  16152. enableTopologicalTravel(ComponentModel, getDependencies);
  16153. function getDependencies(componentType) {
  16154. var deps = [];
  16155. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16156. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16157. }); // Ensure main type.
  16158. deps = map(deps, function (type) {
  16159. return parseClassType(type).main;
  16160. }); // Hack dataset for convenience.
  16161. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16162. deps.unshift('dataset');
  16163. }
  16164. return deps;
  16165. }
  16166. /*
  16167. * Licensed to the Apache Software Foundation (ASF) under one
  16168. * or more contributor license agreements. See the NOTICE file
  16169. * distributed with this work for additional information
  16170. * regarding copyright ownership. The ASF licenses this file
  16171. * to you under the Apache License, Version 2.0 (the
  16172. * "License"); you may not use this file except in compliance
  16173. * with the License. You may obtain a copy of the License at
  16174. *
  16175. * http://www.apache.org/licenses/LICENSE-2.0
  16176. *
  16177. * Unless required by applicable law or agreed to in writing,
  16178. * software distributed under the License is distributed on an
  16179. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16180. * KIND, either express or implied. See the License for the
  16181. * specific language governing permissions and limitations
  16182. * under the License.
  16183. */
  16184. /**
  16185. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16186. */
  16187. /*
  16188. * Licensed to the Apache Software Foundation (ASF) under one
  16189. * or more contributor license agreements. See the NOTICE file
  16190. * distributed with this work for additional information
  16191. * regarding copyright ownership. The ASF licenses this file
  16192. * to you under the Apache License, Version 2.0 (the
  16193. * "License"); you may not use this file except in compliance
  16194. * with the License. You may obtain a copy of the License at
  16195. *
  16196. * http://www.apache.org/licenses/LICENSE-2.0
  16197. *
  16198. * Unless required by applicable law or agreed to in writing,
  16199. * software distributed under the License is distributed on an
  16200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16201. * KIND, either express or implied. See the License for the
  16202. * specific language governing permissions and limitations
  16203. * under the License.
  16204. */
  16205. var platform = ''; // Navigator not exists in node
  16206. if (typeof navigator !== 'undefined') {
  16207. /* global navigator */
  16208. platform = navigator.platform || '';
  16209. }
  16210. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16211. var globalDefault = {
  16212. darkMode: 'auto',
  16213. // backgroundColor: 'rgba(0,0,0,0)',
  16214. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16215. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16216. // Light colors:
  16217. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16218. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16219. // Dark colors:
  16220. // color: [
  16221. // '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  16222. // '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  16223. // ],
  16224. color: [// '#51689b', '#ce5c5c', '#fbc357', '#8fbf8f', '#659d84', '#fb8e6a', '#c77288', '#786090', '#91c4c5', '#6890ba'
  16225. '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16226. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16227. aria: {
  16228. decal: {
  16229. decals: [{
  16230. color: decalColor,
  16231. dashArrayX: [1, 0],
  16232. dashArrayY: [2, 5],
  16233. symbolSize: 1,
  16234. rotation: Math.PI / 6
  16235. }, {
  16236. color: decalColor,
  16237. symbol: 'circle',
  16238. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16239. dashArrayY: [6, 0],
  16240. symbolSize: 0.8
  16241. }, {
  16242. color: decalColor,
  16243. dashArrayX: [1, 0],
  16244. dashArrayY: [4, 3],
  16245. rotation: -Math.PI / 4
  16246. }, {
  16247. color: decalColor,
  16248. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16249. dashArrayY: [6, 0]
  16250. }, {
  16251. color: decalColor,
  16252. dashArrayX: [[1, 0], [1, 6]],
  16253. dashArrayY: [1, 0, 6, 0],
  16254. rotation: Math.PI / 4
  16255. }, {
  16256. color: decalColor,
  16257. symbol: 'triangle',
  16258. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16259. dashArrayY: [7, 2],
  16260. symbolSize: 0.75
  16261. }]
  16262. }
  16263. },
  16264. // If xAxis and yAxis declared, grid is created by default.
  16265. // grid: {},
  16266. textStyle: {
  16267. // color: '#000',
  16268. // decoration: 'none',
  16269. // PENDING
  16270. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16271. // fontFamily: 'Arial, Verdana, sans-serif',
  16272. fontSize: 12,
  16273. fontStyle: 'normal',
  16274. fontWeight: 'normal'
  16275. },
  16276. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16277. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16278. // Default is source-over
  16279. blendMode: null,
  16280. stateAnimation: {
  16281. duration: 300,
  16282. easing: 'cubicOut'
  16283. },
  16284. animation: 'auto',
  16285. animationDuration: 1000,
  16286. animationDurationUpdate: 500,
  16287. animationEasing: 'cubicInOut',
  16288. animationEasingUpdate: 'cubicInOut',
  16289. animationThreshold: 2000,
  16290. // Configuration for progressive/incremental rendering
  16291. progressiveThreshold: 3000,
  16292. progressive: 400,
  16293. // Threshold of if use single hover layer to optimize.
  16294. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16295. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16296. // which is unexpected.
  16297. // see example <echarts/test/heatmap-large.html>.
  16298. hoverLayerThreshold: 3000,
  16299. // See: module:echarts/scale/Time
  16300. useUTC: false
  16301. };
  16302. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'seriesName']);
  16303. var SOURCE_FORMAT_ORIGINAL = 'original';
  16304. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16305. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16306. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16307. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16308. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16309. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16310. var SERIES_LAYOUT_BY_ROW = 'row';
  16311. var BE_ORDINAL = {
  16312. Must: 1,
  16313. Might: 2,
  16314. Not: 3 // Other cases
  16315. };
  16316. var innerGlobalModel = makeInner();
  16317. /**
  16318. * MUST be called before mergeOption of all series.
  16319. */
  16320. function resetSourceDefaulter(ecModel) {
  16321. // `datasetMap` is used to make default encode.
  16322. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16323. }
  16324. /**
  16325. * [The strategy of the arrengment of data dimensions for dataset]:
  16326. * "value way": all axes are non-category axes. So series one by one take
  16327. * several (the number is coordSysDims.length) dimensions from dataset.
  16328. * The result of data arrengment of data dimensions like:
  16329. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16330. * "category way": at least one axis is category axis. So the the first data
  16331. * dimension is always mapped to the first category axis and shared by
  16332. * all of the series. The other data dimensions are taken by series like
  16333. * "value way" does.
  16334. * The result of data arrengment of data dimensions like:
  16335. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16336. *
  16337. * @return encode Never be `null/undefined`.
  16338. */
  16339. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16340. var encode = {};
  16341. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16342. if (!datasetModel || !coordDimensions) {
  16343. return encode;
  16344. }
  16345. var encodeItemName = [];
  16346. var encodeSeriesName = [];
  16347. var ecModel = seriesModel.ecModel;
  16348. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16349. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16350. var baseCategoryDimIndex;
  16351. var categoryWayValueDimStart;
  16352. coordDimensions = coordDimensions.slice();
  16353. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16354. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16355. name: coordDimInfoLoose
  16356. };
  16357. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16358. baseCategoryDimIndex = coordDimIdx;
  16359. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16360. }
  16361. encode[coordDimInfo.name] = [];
  16362. });
  16363. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16364. categoryWayDim: categoryWayValueDimStart,
  16365. valueWayDim: 0
  16366. }); // TODO
  16367. // Auto detect first time axis and do arrangement.
  16368. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16369. var coordDimName = coordDimInfo.name;
  16370. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  16371. if (baseCategoryDimIndex == null) {
  16372. var start = datasetRecord.valueWayDim;
  16373. pushDim(encode[coordDimName], start, count);
  16374. pushDim(encodeSeriesName, start, count);
  16375. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  16376. // especially when encode x y specified.
  16377. // consider: when mutiple series share one dimension
  16378. // category axis, series name should better use
  16379. // the other dimsion name. On the other hand, use
  16380. // both dimensions name.
  16381. } // In category way, the first category axis.
  16382. else if (baseCategoryDimIndex === coordDimIdx) {
  16383. pushDim(encode[coordDimName], 0, count);
  16384. pushDim(encodeItemName, 0, count);
  16385. } // In category way, the other axis.
  16386. else {
  16387. var start = datasetRecord.categoryWayDim;
  16388. pushDim(encode[coordDimName], start, count);
  16389. pushDim(encodeSeriesName, start, count);
  16390. datasetRecord.categoryWayDim += count;
  16391. }
  16392. });
  16393. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16394. for (var i = 0; i < idxCount; i++) {
  16395. dimIdxArr.push(idxFrom + i);
  16396. }
  16397. }
  16398. function getDataDimCountOnCoordDim(coordDimInfo) {
  16399. var dimsDef = coordDimInfo.dimsDef;
  16400. return dimsDef ? dimsDef.length : 1;
  16401. }
  16402. encodeItemName.length && (encode.itemName = encodeItemName);
  16403. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16404. return encode;
  16405. }
  16406. /**
  16407. * Work for data like [{name: ..., value: ...}, ...].
  16408. *
  16409. * @return encode Never be `null/undefined`.
  16410. */
  16411. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16412. var encode = {};
  16413. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16414. if (!datasetModel) {
  16415. return encode;
  16416. }
  16417. var sourceFormat = source.sourceFormat;
  16418. var dimensionsDefine = source.dimensionsDefine;
  16419. var potentialNameDimIndex;
  16420. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16421. each(dimensionsDefine, function (dim, idx) {
  16422. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16423. potentialNameDimIndex = idx;
  16424. }
  16425. });
  16426. }
  16427. var idxResult = function () {
  16428. var idxRes0 = {};
  16429. var idxRes1 = {};
  16430. var guessRecords = []; // 5 is an experience value.
  16431. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16432. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16433. guessRecords.push(guessResult);
  16434. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16435. // and then find a name dim with the priority:
  16436. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16437. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16438. idxRes0.v = i;
  16439. }
  16440. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16441. idxRes0.n = i;
  16442. }
  16443. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16444. return idxRes0;
  16445. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16446. // find the first BE_ORDINAL.Might as the value dim,
  16447. // and then find a name dim with the priority:
  16448. // "other dim" > "the value dim itself".
  16449. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16450. // treated as number.
  16451. if (!isPureNumber) {
  16452. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16453. idxRes1.v = i;
  16454. }
  16455. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16456. idxRes1.n = i;
  16457. }
  16458. }
  16459. }
  16460. function fulfilled(idxResult) {
  16461. return idxResult.v != null && idxResult.n != null;
  16462. }
  16463. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16464. }();
  16465. if (idxResult) {
  16466. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  16467. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  16468. // So we dont set encodeLabel here.
  16469. encode.itemName = [nameDimIndex];
  16470. encode.seriesName = [nameDimIndex];
  16471. }
  16472. return encode;
  16473. }
  16474. /**
  16475. * @return If return null/undefined, indicate that should not use datasetModel.
  16476. */
  16477. function querySeriesUpstreamDatasetModel(seriesModel) {
  16478. // Caution: consider the scenario:
  16479. // A dataset is declared and a series is not expected to use the dataset,
  16480. // and at the beginning `setOption({series: { noData })` (just prepare other
  16481. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16482. // the user should set an empty array to avoid that dataset is used by default.
  16483. var thisData = seriesModel.get('data', true);
  16484. if (!thisData) {
  16485. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16486. index: seriesModel.get('datasetIndex', true),
  16487. id: seriesModel.get('datasetId', true)
  16488. }, SINGLE_REFERRING).models[0];
  16489. }
  16490. }
  16491. /**
  16492. * @return Always return an array event empty.
  16493. */
  16494. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16495. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  16496. // Otherwise, no reference.
  16497. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16498. return [];
  16499. }
  16500. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16501. index: datasetModel.get('fromDatasetIndex', true),
  16502. id: datasetModel.get('fromDatasetId', true)
  16503. }, SINGLE_REFERRING).models;
  16504. }
  16505. /**
  16506. * The rule should not be complex, otherwise user might not
  16507. * be able to known where the data is wrong.
  16508. * The code is ugly, but how to make it neat?
  16509. */
  16510. function guessOrdinal(source, dimIndex) {
  16511. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  16512. } // dimIndex may be overflow source data.
  16513. // return {BE_ORDINAL}
  16514. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  16515. var result; // Experience value.
  16516. var maxLoop = 5;
  16517. if (isTypedArray(data)) {
  16518. return BE_ORDINAL.Not;
  16519. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16520. // always exists in source.
  16521. var dimName;
  16522. var dimType;
  16523. if (dimensionsDefine) {
  16524. var dimDefItem = dimensionsDefine[dimIndex];
  16525. if (isObject(dimDefItem)) {
  16526. dimName = dimDefItem.name;
  16527. dimType = dimDefItem.type;
  16528. } else if (isString(dimDefItem)) {
  16529. dimName = dimDefItem;
  16530. }
  16531. }
  16532. if (dimType != null) {
  16533. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  16534. }
  16535. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16536. var dataArrayRows = data;
  16537. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16538. var sample = dataArrayRows[dimIndex];
  16539. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16540. if ((result = detectValue(sample[startIndex + i])) != null) {
  16541. return result;
  16542. }
  16543. }
  16544. } else {
  16545. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  16546. var row = dataArrayRows[startIndex + i];
  16547. if (row && (result = detectValue(row[dimIndex])) != null) {
  16548. return result;
  16549. }
  16550. }
  16551. }
  16552. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16553. var dataObjectRows = data;
  16554. if (!dimName) {
  16555. return BE_ORDINAL.Not;
  16556. }
  16557. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  16558. var item = dataObjectRows[i];
  16559. if (item && (result = detectValue(item[dimName])) != null) {
  16560. return result;
  16561. }
  16562. }
  16563. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16564. var dataKeyedColumns = data;
  16565. if (!dimName) {
  16566. return BE_ORDINAL.Not;
  16567. }
  16568. var sample = dataKeyedColumns[dimName];
  16569. if (!sample || isTypedArray(sample)) {
  16570. return BE_ORDINAL.Not;
  16571. }
  16572. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16573. if ((result = detectValue(sample[i])) != null) {
  16574. return result;
  16575. }
  16576. }
  16577. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16578. var dataOriginal = data;
  16579. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  16580. var item = dataOriginal[i];
  16581. var val = getDataItemValue(item);
  16582. if (!isArray(val)) {
  16583. return BE_ORDINAL.Not;
  16584. }
  16585. if ((result = detectValue(val[dimIndex])) != null) {
  16586. return result;
  16587. }
  16588. }
  16589. }
  16590. function detectValue(val) {
  16591. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  16592. // `isFinit('')` get `true`.
  16593. if (val != null && isFinite(val) && val !== '') {
  16594. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  16595. } else if (beStr && val !== '-') {
  16596. return BE_ORDINAL.Must;
  16597. }
  16598. }
  16599. return BE_ORDINAL.Not;
  16600. }
  16601. var internalOptionCreatorMap = createHashMap();
  16602. function registerInternalOptionCreator(mainType, creator) {
  16603. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  16604. internalOptionCreatorMap.set(mainType, creator);
  16605. }
  16606. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  16607. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  16608. if (!internalOptionCreator) {
  16609. return newCmptOptionList;
  16610. }
  16611. var internalOptions = internalOptionCreator(ecModel);
  16612. if (!internalOptions) {
  16613. return newCmptOptionList;
  16614. }
  16615. if ("development" !== 'production') {
  16616. for (var i = 0; i < internalOptions.length; i++) {
  16617. assert(isComponentIdInternal(internalOptions[i]));
  16618. }
  16619. }
  16620. return newCmptOptionList.concat(internalOptions);
  16621. }
  16622. var innerColor = makeInner();
  16623. var innerDecal = makeInner();
  16624. var PaletteMixin =
  16625. /** @class */
  16626. function () {
  16627. function PaletteMixin() {}
  16628. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  16629. var defaultPalette = normalizeToArray(this.get('color', true));
  16630. var layeredPalette = this.get('colorLayer', true);
  16631. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  16632. };
  16633. PaletteMixin.prototype.clearColorPalette = function () {
  16634. clearPalette(this, innerColor);
  16635. };
  16636. return PaletteMixin;
  16637. }();
  16638. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  16639. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  16640. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  16641. }
  16642. function getNearestPalette(palettes, requestColorNum) {
  16643. var paletteNum = palettes.length; // TODO palettes must be in order
  16644. for (var i = 0; i < paletteNum; i++) {
  16645. if (palettes[i].length > requestColorNum) {
  16646. return palettes[i];
  16647. }
  16648. }
  16649. return palettes[paletteNum - 1];
  16650. }
  16651. /**
  16652. * @param name MUST NOT be null/undefined. Otherwise call this function
  16653. * twise with the same parameters will get different result.
  16654. * @param scope default this.
  16655. * @return Can be null/undefined
  16656. */
  16657. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  16658. scope = scope || that;
  16659. var scopeFields = inner(scope);
  16660. var paletteIdx = scopeFields.paletteIdx || 0;
  16661. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16662. if (paletteNameMap.hasOwnProperty(name)) {
  16663. return paletteNameMap[name];
  16664. }
  16665. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  16666. palette = palette || defaultPalette;
  16667. if (!palette || !palette.length) {
  16668. return;
  16669. }
  16670. var pickedPaletteItem = palette[paletteIdx];
  16671. if (name) {
  16672. paletteNameMap[name] = pickedPaletteItem;
  16673. }
  16674. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  16675. return pickedPaletteItem;
  16676. }
  16677. function clearPalette(that, inner) {
  16678. inner(that).paletteIdx = 0;
  16679. inner(that).paletteNameMap = {};
  16680. }
  16681. // Internal method names:
  16682. // -----------------------
  16683. var reCreateSeriesIndices;
  16684. var assertSeriesInitialized;
  16685. var initBase;
  16686. var OPTION_INNER_KEY = '\0_ec_inner';
  16687. var OPTION_INNER_VALUE = 1;
  16688. var GlobalModel =
  16689. /** @class */
  16690. function (_super) {
  16691. __extends(GlobalModel, _super);
  16692. function GlobalModel() {
  16693. return _super !== null && _super.apply(this, arguments) || this;
  16694. }
  16695. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  16696. theme = theme || {};
  16697. this.option = null; // Mark as not initialized.
  16698. this._theme = new Model(theme);
  16699. this._locale = new Model(locale);
  16700. this._optionManager = optionManager;
  16701. };
  16702. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  16703. if ("development" !== 'production') {
  16704. assert(option != null, 'option is null/undefined');
  16705. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  16706. }
  16707. var innerOpt = normalizeSetOptionInput(opts);
  16708. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  16709. this._resetOption(null, innerOpt);
  16710. };
  16711. /**
  16712. * @param type null/undefined: reset all.
  16713. * 'recreate': force recreate all.
  16714. * 'timeline': only reset timeline option
  16715. * 'media': only reset media query option
  16716. * @return Whether option changed.
  16717. */
  16718. GlobalModel.prototype.resetOption = function (type, opt) {
  16719. return this._resetOption(type, normalizeSetOptionInput(opt));
  16720. };
  16721. GlobalModel.prototype._resetOption = function (type, opt) {
  16722. var optionChanged = false;
  16723. var optionManager = this._optionManager;
  16724. if (!type || type === 'recreate') {
  16725. var baseOption = optionManager.mountOption(type === 'recreate');
  16726. if (!this.option || type === 'recreate') {
  16727. initBase(this, baseOption);
  16728. } else {
  16729. this.restoreData();
  16730. this._mergeOption(baseOption, opt);
  16731. }
  16732. optionChanged = true;
  16733. }
  16734. if (type === 'timeline' || type === 'media') {
  16735. this.restoreData();
  16736. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  16737. // it should better not have the same props with `MediaUnit['option']`.
  16738. // Becuase either `option2` or `MediaUnit['option']` will be always merged to "current option"
  16739. // rather than original "baseOption". If they both override a prop, the result might be
  16740. // unexpected when media state changed after `setOption` called.
  16741. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  16742. // (`{baseOption, media}`) in `setOption`.
  16743. // For `timeline`, the case is the same.
  16744. if (!type || type === 'recreate' || type === 'timeline') {
  16745. var timelineOption = optionManager.getTimelineOption(this);
  16746. if (timelineOption) {
  16747. optionChanged = true;
  16748. this._mergeOption(timelineOption, opt);
  16749. }
  16750. }
  16751. if (!type || type === 'recreate' || type === 'media') {
  16752. var mediaOptions = optionManager.getMediaOption(this);
  16753. if (mediaOptions.length) {
  16754. each(mediaOptions, function (mediaOption) {
  16755. optionChanged = true;
  16756. this._mergeOption(mediaOption, opt);
  16757. }, this);
  16758. }
  16759. }
  16760. return optionChanged;
  16761. };
  16762. GlobalModel.prototype.mergeOption = function (option) {
  16763. this._mergeOption(option, null);
  16764. };
  16765. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  16766. var option = this.option;
  16767. var componentsMap = this._componentsMap;
  16768. var componentsCount = this._componentsCount;
  16769. var newCmptTypes = [];
  16770. var newCmptTypeMap = createHashMap();
  16771. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  16772. resetSourceDefaulter(this); // If no component class, merge directly.
  16773. // For example: color, animaiton options, etc.
  16774. each(newOption, function (componentOption, mainType) {
  16775. if (componentOption == null) {
  16776. return;
  16777. }
  16778. if (!ComponentModel.hasClass(mainType)) {
  16779. // globalSettingTask.dirty();
  16780. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  16781. } else if (mainType) {
  16782. newCmptTypes.push(mainType);
  16783. newCmptTypeMap.set(mainType, true);
  16784. }
  16785. });
  16786. if (replaceMergeMainTypeMap) {
  16787. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  16788. // we trade it as it is declared in option as `{xxx: []}`. Because:
  16789. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  16790. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  16791. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  16792. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  16793. newCmptTypes.push(mainTypeInReplaceMerge);
  16794. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  16795. }
  16796. });
  16797. }
  16798. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  16799. function visitComponent(mainType) {
  16800. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  16801. var oldCmptList = componentsMap.get(mainType);
  16802. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  16803. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  16804. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  16805. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  16806. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  16807. // components, which is probably incorrect logic.
  16808. option[mainType] = null;
  16809. componentsMap.set(mainType, null);
  16810. componentsCount.set(mainType, 0);
  16811. var optionsByMainType = [];
  16812. var cmptsByMainType = [];
  16813. var cmptsCountByMainType = 0;
  16814. each(mappingResult, function (resultItem, index) {
  16815. var componentModel = resultItem.existing;
  16816. var newCmptOption = resultItem.newOption;
  16817. if (!newCmptOption) {
  16818. if (componentModel) {
  16819. // Consider where is no new option and should be merged using {},
  16820. // see removeEdgeAndAdd in topologicalTravel and
  16821. // ComponentModel.getAllClassMainTypes.
  16822. componentModel.mergeOption({}, this);
  16823. componentModel.optionUpdated({}, false);
  16824. } // If no both `resultItem.exist` and `resultItem.option`,
  16825. // either it is in `replaceMerge` and not matched by any id,
  16826. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  16827. } else {
  16828. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, true);
  16829. if (componentModel && componentModel.constructor === ComponentModelClass) {
  16830. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  16831. componentModel.mergeOption(newCmptOption, this);
  16832. componentModel.optionUpdated(newCmptOption, false);
  16833. } else {
  16834. // PENDING Global as parent ?
  16835. var extraOpt = extend({
  16836. componentIndex: index
  16837. }, resultItem.keyInfo);
  16838. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  16839. extend(componentModel, extraOpt);
  16840. if (resultItem.brandNew) {
  16841. componentModel.__requireNewView = true;
  16842. }
  16843. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  16844. // newCmptOption has been used as componentModel.option
  16845. // and may be merged with theme and default, so pass null
  16846. // to avoid confusion.
  16847. componentModel.optionUpdated(null, true);
  16848. }
  16849. }
  16850. if (componentModel) {
  16851. optionsByMainType.push(componentModel.option);
  16852. cmptsByMainType.push(componentModel);
  16853. cmptsCountByMainType++;
  16854. } else {
  16855. // Always do assign to avoid elided item in array.
  16856. optionsByMainType.push(void 0);
  16857. cmptsByMainType.push(void 0);
  16858. }
  16859. }, this);
  16860. option[mainType] = optionsByMainType;
  16861. componentsMap.set(mainType, cmptsByMainType);
  16862. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  16863. if (mainType === 'series') {
  16864. reCreateSeriesIndices(this);
  16865. }
  16866. } // If no series declared, ensure `_seriesIndices` initialized.
  16867. if (!this._seriesIndices) {
  16868. reCreateSeriesIndices(this);
  16869. }
  16870. };
  16871. /**
  16872. * Get option for output (cloned option and inner info removed)
  16873. */
  16874. GlobalModel.prototype.getOption = function () {
  16875. var option = clone(this.option);
  16876. each(option, function (optInMainType, mainType) {
  16877. if (ComponentModel.hasClass(mainType)) {
  16878. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  16879. // Inner cmpts might not be at last since ec5.0, but still
  16880. // compatible for users: if inner cmpt at last, splice the returned array.
  16881. var realLen = opts.length;
  16882. var metNonInner = false;
  16883. for (var i = realLen - 1; i >= 0; i--) {
  16884. // Remove options with inner id.
  16885. if (opts[i] && !isComponentIdInternal(opts[i])) {
  16886. metNonInner = true;
  16887. } else {
  16888. opts[i] = null;
  16889. !metNonInner && realLen--;
  16890. }
  16891. }
  16892. opts.length = realLen;
  16893. option[mainType] = opts;
  16894. }
  16895. });
  16896. delete option[OPTION_INNER_KEY];
  16897. return option;
  16898. };
  16899. GlobalModel.prototype.getTheme = function () {
  16900. return this._theme;
  16901. };
  16902. GlobalModel.prototype.getLocaleModel = function () {
  16903. return this._locale;
  16904. };
  16905. GlobalModel.prototype.getLocale = function (localePosition) {
  16906. var locale = this.getLocaleModel();
  16907. return locale.get(localePosition);
  16908. };
  16909. GlobalModel.prototype.setUpdatePayload = function (payload) {
  16910. this._payload = payload;
  16911. };
  16912. GlobalModel.prototype.getUpdatePayload = function () {
  16913. return this._payload;
  16914. };
  16915. /**
  16916. * @param idx If not specified, return the first one.
  16917. */
  16918. GlobalModel.prototype.getComponent = function (mainType, idx) {
  16919. var list = this._componentsMap.get(mainType);
  16920. if (list) {
  16921. var cmpt = list[idx || 0];
  16922. if (cmpt) {
  16923. return cmpt;
  16924. } else if (idx == null) {
  16925. for (var i = 0; i < list.length; i++) {
  16926. if (list[i]) {
  16927. return list[i];
  16928. }
  16929. }
  16930. }
  16931. }
  16932. };
  16933. /**
  16934. * @return Never be null/undefined.
  16935. */
  16936. GlobalModel.prototype.queryComponents = function (condition) {
  16937. var mainType = condition.mainType;
  16938. if (!mainType) {
  16939. return [];
  16940. }
  16941. var index = condition.index;
  16942. var id = condition.id;
  16943. var name = condition.name;
  16944. var cmpts = this._componentsMap.get(mainType);
  16945. if (!cmpts || !cmpts.length) {
  16946. return [];
  16947. }
  16948. var result;
  16949. if (index != null) {
  16950. result = [];
  16951. each(normalizeToArray(index), function (idx) {
  16952. cmpts[idx] && result.push(cmpts[idx]);
  16953. });
  16954. } else if (id != null) {
  16955. result = queryByIdOrName('id', id, cmpts);
  16956. } else if (name != null) {
  16957. result = queryByIdOrName('name', name, cmpts);
  16958. } else {
  16959. // Return all non-empty components in that mainType
  16960. result = filter(cmpts, function (cmpt) {
  16961. return !!cmpt;
  16962. });
  16963. }
  16964. return filterBySubType(result, condition);
  16965. };
  16966. /**
  16967. * The interface is different from queryComponents,
  16968. * which is convenient for inner usage.
  16969. *
  16970. * @usage
  16971. * let result = findComponents(
  16972. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  16973. * );
  16974. * let result = findComponents(
  16975. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  16976. * );
  16977. * let result = findComponents(
  16978. * {mainType: 'series',
  16979. * filter: function (model, index) {...}}
  16980. * );
  16981. * // result like [component0, componnet1, ...]
  16982. */
  16983. GlobalModel.prototype.findComponents = function (condition) {
  16984. var query = condition.query;
  16985. var mainType = condition.mainType;
  16986. var queryCond = getQueryCond(query);
  16987. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  16988. : filter(this._componentsMap.get(mainType), function (cmpt) {
  16989. return !!cmpt;
  16990. });
  16991. return doFilter(filterBySubType(result, condition));
  16992. function getQueryCond(q) {
  16993. var indexAttr = mainType + 'Index';
  16994. var idAttr = mainType + 'Id';
  16995. var nameAttr = mainType + 'Name';
  16996. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  16997. mainType: mainType,
  16998. // subType will be filtered finally.
  16999. index: q[indexAttr],
  17000. id: q[idAttr],
  17001. name: q[nameAttr]
  17002. } : null;
  17003. }
  17004. function doFilter(res) {
  17005. return condition.filter ? filter(res, condition.filter) : res;
  17006. }
  17007. };
  17008. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17009. var componentsMap = this._componentsMap;
  17010. if (isFunction(mainType)) {
  17011. var ctxForAll_1 = cb;
  17012. var cbForAll_1 = mainType;
  17013. componentsMap.each(function (cmpts, componentType) {
  17014. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17015. var cmpt = cmpts[i];
  17016. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17017. }
  17018. });
  17019. } else {
  17020. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17021. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17022. var cmpt = cmpts[i];
  17023. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17024. }
  17025. }
  17026. };
  17027. /**
  17028. * Get series list before filtered by name.
  17029. */
  17030. GlobalModel.prototype.getSeriesByName = function (name) {
  17031. var nameStr = convertOptionIdName(name, null);
  17032. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17033. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17034. });
  17035. };
  17036. /**
  17037. * Get series list before filtered by index.
  17038. */
  17039. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17040. return this._componentsMap.get('series')[seriesIndex];
  17041. };
  17042. /**
  17043. * Get series list before filtered by type.
  17044. * FIXME: rename to getRawSeriesByType?
  17045. */
  17046. GlobalModel.prototype.getSeriesByType = function (subType) {
  17047. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17048. return !!oneSeries && oneSeries.subType === subType;
  17049. });
  17050. };
  17051. /**
  17052. * Get all series before filtered.
  17053. */
  17054. GlobalModel.prototype.getSeries = function () {
  17055. return filter(this._componentsMap.get('series').slice(), function (oneSeries) {
  17056. return !!oneSeries;
  17057. });
  17058. };
  17059. /**
  17060. * Count series before filtered.
  17061. */
  17062. GlobalModel.prototype.getSeriesCount = function () {
  17063. return this._componentsCount.get('series');
  17064. };
  17065. /**
  17066. * After filtering, series may be different
  17067. * frome raw series.
  17068. */
  17069. GlobalModel.prototype.eachSeries = function (cb, context) {
  17070. assertSeriesInitialized(this);
  17071. each(this._seriesIndices, function (rawSeriesIndex) {
  17072. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17073. cb.call(context, series, rawSeriesIndex);
  17074. }, this);
  17075. };
  17076. /**
  17077. * Iterate raw series before filtered.
  17078. *
  17079. * @param {Function} cb
  17080. * @param {*} context
  17081. */
  17082. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17083. each(this._componentsMap.get('series'), function (series) {
  17084. series && cb.call(context, series, series.componentIndex);
  17085. });
  17086. };
  17087. /**
  17088. * After filtering, series may be different.
  17089. * frome raw series.
  17090. */
  17091. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17092. assertSeriesInitialized(this);
  17093. each(this._seriesIndices, function (rawSeriesIndex) {
  17094. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17095. if (series.subType === subType) {
  17096. cb.call(context, series, rawSeriesIndex);
  17097. }
  17098. }, this);
  17099. };
  17100. /**
  17101. * Iterate raw series before filtered of given type.
  17102. */
  17103. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17104. return each(this.getSeriesByType(subType), cb, context);
  17105. };
  17106. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17107. assertSeriesInitialized(this);
  17108. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17109. };
  17110. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17111. return (this._seriesIndices || []).slice();
  17112. };
  17113. GlobalModel.prototype.filterSeries = function (cb, context) {
  17114. assertSeriesInitialized(this);
  17115. var newSeriesIndices = [];
  17116. each(this._seriesIndices, function (seriesRawIdx) {
  17117. var series = this._componentsMap.get('series')[seriesRawIdx];
  17118. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17119. }, this);
  17120. this._seriesIndices = newSeriesIndices;
  17121. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17122. };
  17123. GlobalModel.prototype.restoreData = function (payload) {
  17124. reCreateSeriesIndices(this);
  17125. var componentsMap = this._componentsMap;
  17126. var componentTypes = [];
  17127. componentsMap.each(function (components, componentType) {
  17128. if (ComponentModel.hasClass(componentType)) {
  17129. componentTypes.push(componentType);
  17130. }
  17131. });
  17132. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17133. each(componentsMap.get(componentType), function (component) {
  17134. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17135. component.restoreData();
  17136. }
  17137. });
  17138. });
  17139. };
  17140. GlobalModel.internalField = function () {
  17141. reCreateSeriesIndices = function (ecModel) {
  17142. var seriesIndices = ecModel._seriesIndices = [];
  17143. each(ecModel._componentsMap.get('series'), function (series) {
  17144. // series may have been removed by `replaceMerge`.
  17145. series && seriesIndices.push(series.componentIndex);
  17146. });
  17147. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17148. };
  17149. assertSeriesInitialized = function (ecModel) {
  17150. // Components that use _seriesIndices should depends on series component,
  17151. // which make sure that their initialization is after series.
  17152. if ("development" !== 'production') {
  17153. if (!ecModel._seriesIndices) {
  17154. throw new Error('Option should contains series.');
  17155. }
  17156. }
  17157. };
  17158. initBase = function (ecModel, baseOption) {
  17159. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17160. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17161. ecModel.option = {};
  17162. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17163. // before series initialized.
  17164. ecModel._componentsMap = createHashMap({
  17165. series: []
  17166. });
  17167. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17168. // performed before theme and globalDefault merge.
  17169. var airaOption = baseOption.aria;
  17170. if (isObject(airaOption) && airaOption.enabled == null) {
  17171. airaOption.enabled = true;
  17172. }
  17173. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17174. merge(baseOption, globalDefault, false);
  17175. ecModel._mergeOption(baseOption, null);
  17176. };
  17177. }();
  17178. return GlobalModel;
  17179. }(Model);
  17180. function isNotTargetSeries(seriesModel, payload) {
  17181. if (payload) {
  17182. var index = payload.seriesIndex;
  17183. var id = payload.seriesId;
  17184. var name_1 = payload.seriesName;
  17185. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17186. }
  17187. }
  17188. function mergeTheme(option, theme) {
  17189. // PENDING
  17190. // NOT use `colorLayer` in theme if option has `color`
  17191. var notMergeColorLayer = option.color && !option.colorLayer;
  17192. each(theme, function (themeItem, name) {
  17193. if (name === 'colorLayer' && notMergeColorLayer) {
  17194. return;
  17195. } // If it is component model mainType, the model handles that merge later.
  17196. // otherwise, merge them here.
  17197. if (!ComponentModel.hasClass(name)) {
  17198. if (typeof themeItem === 'object') {
  17199. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17200. } else {
  17201. if (option[name] == null) {
  17202. option[name] = themeItem;
  17203. }
  17204. }
  17205. }
  17206. });
  17207. }
  17208. function queryByIdOrName(attr, idOrName, cmpts) {
  17209. // Here is a break from echarts4: string and number are
  17210. // treated as equal.
  17211. if (isArray(idOrName)) {
  17212. var keyMap_1 = createHashMap();
  17213. each(idOrName, function (idOrNameItem) {
  17214. if (idOrNameItem != null) {
  17215. var idName = convertOptionIdName(idOrNameItem, null);
  17216. idName != null && keyMap_1.set(idOrNameItem, true);
  17217. }
  17218. });
  17219. return filter(cmpts, function (cmpt) {
  17220. return cmpt && keyMap_1.get(cmpt[attr]);
  17221. });
  17222. } else {
  17223. var idName_1 = convertOptionIdName(idOrName, null);
  17224. return filter(cmpts, function (cmpt) {
  17225. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17226. });
  17227. }
  17228. }
  17229. function filterBySubType(components, condition) {
  17230. // Using hasOwnProperty for restrict. Consider
  17231. // subType is undefined in user payload.
  17232. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  17233. return cmpt && cmpt.subType === condition.subType;
  17234. }) : components;
  17235. }
  17236. function normalizeSetOptionInput(opts) {
  17237. var replaceMergeMainTypeMap = createHashMap();
  17238. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  17239. if ("development" !== 'production') {
  17240. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  17241. }
  17242. replaceMergeMainTypeMap.set(mainType, true);
  17243. });
  17244. return {
  17245. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  17246. };
  17247. }
  17248. mixin(GlobalModel, PaletteMixin);
  17249. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  17250. 'getOption', // 'getViewOfComponentModel',
  17251. // 'getViewOfSeriesModel',
  17252. 'getId', 'updateLabelLayout'];
  17253. var ExtensionAPI =
  17254. /** @class */
  17255. function () {
  17256. function ExtensionAPI(ecInstance) {
  17257. each(availableMethods, function (methodName) {
  17258. this[methodName] = bind(ecInstance[methodName], ecInstance);
  17259. }, this);
  17260. }
  17261. return ExtensionAPI;
  17262. }();
  17263. var coordinateSystemCreators = {};
  17264. var CoordinateSystemManager =
  17265. /** @class */
  17266. function () {
  17267. function CoordinateSystemManager() {
  17268. this._coordinateSystems = [];
  17269. }
  17270. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17271. var coordinateSystems = [];
  17272. each(coordinateSystemCreators, function (creater, type) {
  17273. var list = creater.create(ecModel, api);
  17274. coordinateSystems = coordinateSystems.concat(list || []);
  17275. });
  17276. this._coordinateSystems = coordinateSystems;
  17277. };
  17278. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17279. each(this._coordinateSystems, function (coordSys) {
  17280. coordSys.update && coordSys.update(ecModel, api);
  17281. });
  17282. };
  17283. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17284. return this._coordinateSystems.slice();
  17285. };
  17286. CoordinateSystemManager.register = function (type, creator) {
  17287. coordinateSystemCreators[type] = creator;
  17288. };
  17289. CoordinateSystemManager.get = function (type) {
  17290. return coordinateSystemCreators[type];
  17291. };
  17292. return CoordinateSystemManager;
  17293. }();
  17294. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  17295. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  17296. /**
  17297. * TERM EXPLANATIONS:
  17298. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  17299. */
  17300. var OptionManager =
  17301. /** @class */
  17302. function () {
  17303. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17304. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17305. // rawOption cloned and backuped when timeline changed, which does no
  17306. // good to performance. What's more, that both timeline and setOption
  17307. // method supply 'notMerge' brings complex and some problems.
  17308. // Consider this case:
  17309. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17310. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17311. function OptionManager(api) {
  17312. this._timelineOptions = [];
  17313. this._mediaList = [];
  17314. /**
  17315. * -1, means default.
  17316. * empty means no media.
  17317. */
  17318. this._currentMediaIndices = [];
  17319. this._api = api;
  17320. }
  17321. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17322. if (rawOption) {
  17323. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17324. each(normalizeToArray(rawOption.series), function (series) {
  17325. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17326. });
  17327. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17328. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17329. });
  17330. } // Caution: some series modify option data, if do not clone,
  17331. // it should ensure that the repeat modify correctly
  17332. // (create a new object when modify itself).
  17333. rawOption = clone(rawOption); // FIXME
  17334. // If some property is set in timeline options or media option but
  17335. // not set in baseOption, a warning should be given.
  17336. var optionBackup = this._optionBackup;
  17337. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17338. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  17339. if (optionBackup) {
  17340. // FIXME
  17341. // the restore merge solution is essentially incorrect.
  17342. // the mapping can not be 100% consistent with ecModel, which probably brings
  17343. // potential bug!
  17344. // The first merge is delayed, becuase in most cases, users do not call `setOption` twice.
  17345. // let fakeCmptsMap = this._fakeCmptsMap;
  17346. // if (!fakeCmptsMap) {
  17347. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17348. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17349. // }
  17350. // mergeToBackupOption(
  17351. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17352. // );
  17353. // For simplicity, timeline options and media options do not support merge,
  17354. // that is, if you `setOption` twice and both has timeline options, the latter
  17355. // timeline opitons will not be merged to the formers, but just substitude them.
  17356. if (newParsedOption.timelineOptions.length) {
  17357. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17358. }
  17359. if (newParsedOption.mediaList.length) {
  17360. optionBackup.mediaList = newParsedOption.mediaList;
  17361. }
  17362. if (newParsedOption.mediaDefault) {
  17363. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17364. }
  17365. } else {
  17366. this._optionBackup = newParsedOption;
  17367. }
  17368. };
  17369. OptionManager.prototype.mountOption = function (isRecreate) {
  17370. var optionBackup = this._optionBackup;
  17371. this._timelineOptions = optionBackup.timelineOptions;
  17372. this._mediaList = optionBackup.mediaList;
  17373. this._mediaDefault = optionBackup.mediaDefault;
  17374. this._currentMediaIndices = [];
  17375. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  17376. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17377. // each time `setOption` called, can be only used in `isRecreate`, because
  17378. // its reliability is under suspicion. In other cases option merge is
  17379. // performed by `model.mergeOption`.
  17380. ? optionBackup.baseOption : this._newBaseOption);
  17381. };
  17382. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17383. var option;
  17384. var timelineOptions = this._timelineOptions;
  17385. if (timelineOptions.length) {
  17386. // getTimelineOption can only be called after ecModel inited,
  17387. // so we can get currentIndex from timelineModel.
  17388. var timelineModel = ecModel.getComponent('timeline');
  17389. if (timelineModel) {
  17390. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  17391. timelineOptions[timelineModel.getCurrentIndex()]);
  17392. }
  17393. }
  17394. return option;
  17395. };
  17396. OptionManager.prototype.getMediaOption = function (ecModel) {
  17397. var ecWidth = this._api.getWidth();
  17398. var ecHeight = this._api.getHeight();
  17399. var mediaList = this._mediaList;
  17400. var mediaDefault = this._mediaDefault;
  17401. var indices = [];
  17402. var result = []; // No media defined.
  17403. if (!mediaList.length && !mediaDefault) {
  17404. return result;
  17405. } // Multi media may be applied, the latter defined media has higher priority.
  17406. for (var i = 0, len = mediaList.length; i < len; i++) {
  17407. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17408. indices.push(i);
  17409. }
  17410. } // FIXME
  17411. // Whether mediaDefault should force users to provide? Otherwise
  17412. // the change by media query can not be recorvered.
  17413. if (!indices.length && mediaDefault) {
  17414. indices = [-1];
  17415. }
  17416. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17417. result = map(indices, function (index) {
  17418. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  17419. });
  17420. } // Otherwise return nothing.
  17421. this._currentMediaIndices = indices;
  17422. return result;
  17423. };
  17424. return OptionManager;
  17425. }();
  17426. /**
  17427. * [RAW_OPTION_PATTERNS]
  17428. * (Note: "series: []" represents all other props in `ECUnitOption`)
  17429. *
  17430. * (1) No prop "baseOption" declared:
  17431. * Root option is used as "baseOption" (except prop "options" and "media").
  17432. * ```js
  17433. * option = {
  17434. * series: [],
  17435. * timeline: {},
  17436. * options: [],
  17437. * };
  17438. * option = {
  17439. * series: [],
  17440. * media: {},
  17441. * };
  17442. * option = {
  17443. * series: [],
  17444. * timeline: {},
  17445. * options: [],
  17446. * media: {},
  17447. * }
  17448. * ```
  17449. *
  17450. * (2) Prop "baseOption" declared:
  17451. * If "baseOption" declared, `ECUnitOption` props can only be declared
  17452. * inside "baseOption" except prop "timeline" (compat ec2).
  17453. * ```js
  17454. * option = {
  17455. * baseOption: {
  17456. * timeline: {},
  17457. * series: [],
  17458. * },
  17459. * options: []
  17460. * };
  17461. * option = {
  17462. * baseOption: {
  17463. * series: [],
  17464. * },
  17465. * media: []
  17466. * };
  17467. * option = {
  17468. * baseOption: {
  17469. * timeline: {},
  17470. * series: [],
  17471. * },
  17472. * options: []
  17473. * media: []
  17474. * };
  17475. * option = {
  17476. * // ec3 compat ec2: allow (only) `timeline` declared
  17477. * // outside baseOption. Keep this setting for compat.
  17478. * timeline: {},
  17479. * baseOption: {
  17480. * series: [],
  17481. * },
  17482. * options: [],
  17483. * media: []
  17484. * };
  17485. * ```
  17486. */
  17487. function parseRawOption( // `rawOption` May be modified
  17488. rawOption, optionPreprocessorFuncs, isNew) {
  17489. var mediaList = [];
  17490. var mediaDefault;
  17491. var baseOption;
  17492. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  17493. var timelineOnRoot = rawOption.timeline;
  17494. var timelineOptionsOnRoot = rawOption.options;
  17495. var mediaOnRoot = rawOption.media;
  17496. var hasMedia = !!rawOption.media;
  17497. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  17498. if (declaredBaseOption) {
  17499. baseOption = declaredBaseOption; // For merge option.
  17500. if (!baseOption.timeline) {
  17501. baseOption.timeline = timelineOnRoot;
  17502. }
  17503. } // For convenience, enable to use the root option as the `baseOption`:
  17504. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  17505. else {
  17506. if (hasTimeline || hasMedia) {
  17507. rawOption.options = rawOption.media = null;
  17508. }
  17509. baseOption = rawOption;
  17510. }
  17511. if (hasMedia) {
  17512. if (isArray(mediaOnRoot)) {
  17513. each(mediaOnRoot, function (singleMedia) {
  17514. if ("development" !== 'production') {
  17515. // Real case of wrong config.
  17516. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  17517. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  17518. }
  17519. }
  17520. if (singleMedia && singleMedia.option) {
  17521. if (singleMedia.query) {
  17522. mediaList.push(singleMedia);
  17523. } else if (!mediaDefault) {
  17524. // Use the first media default.
  17525. mediaDefault = singleMedia;
  17526. }
  17527. }
  17528. });
  17529. } else {
  17530. if ("development" !== 'production') {
  17531. // Real case of wrong config.
  17532. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  17533. }
  17534. }
  17535. }
  17536. doPreprocess(baseOption);
  17537. each(timelineOptionsOnRoot, function (option) {
  17538. return doPreprocess(option);
  17539. });
  17540. each(mediaList, function (media) {
  17541. return doPreprocess(media.option);
  17542. });
  17543. function doPreprocess(option) {
  17544. each(optionPreprocessorFuncs, function (preProcess) {
  17545. preProcess(option, isNew);
  17546. });
  17547. }
  17548. return {
  17549. baseOption: baseOption,
  17550. timelineOptions: timelineOptionsOnRoot || [],
  17551. mediaDefault: mediaDefault,
  17552. mediaList: mediaList
  17553. };
  17554. }
  17555. /**
  17556. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17557. * Support: width, height, aspectRatio
  17558. * Can use max or min as prefix.
  17559. */
  17560. function applyMediaQuery(query, ecWidth, ecHeight) {
  17561. var realMap = {
  17562. width: ecWidth,
  17563. height: ecHeight,
  17564. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17565. };
  17566. var applicatable = true;
  17567. each(query, function (value, attr) {
  17568. var matched = attr.match(QUERY_REG);
  17569. if (!matched || !matched[1] || !matched[2]) {
  17570. return;
  17571. }
  17572. var operator = matched[1];
  17573. var realAttr = matched[2].toLowerCase();
  17574. if (!compare(realMap[realAttr], value, operator)) {
  17575. applicatable = false;
  17576. }
  17577. });
  17578. return applicatable;
  17579. }
  17580. function compare(real, expect, operator) {
  17581. if (operator === 'min') {
  17582. return real >= expect;
  17583. } else if (operator === 'max') {
  17584. return real <= expect;
  17585. } else {
  17586. // Equals
  17587. return real === expect;
  17588. }
  17589. }
  17590. function indicesEquals(indices1, indices2) {
  17591. // indices is always order by asc and has only finite number.
  17592. return indices1.join(',') === indices2.join(',');
  17593. }
  17594. var each$2 = each;
  17595. var isObject$1 = isObject;
  17596. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  17597. function compatEC2ItemStyle(opt) {
  17598. var itemStyleOpt = opt && opt.itemStyle;
  17599. if (!itemStyleOpt) {
  17600. return;
  17601. }
  17602. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17603. var styleName = POSSIBLE_STYLES[i];
  17604. var normalItemStyleOpt = itemStyleOpt.normal;
  17605. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17606. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  17607. if ("development" !== 'production') {
  17608. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  17609. }
  17610. opt[styleName] = opt[styleName] || {};
  17611. if (!opt[styleName].normal) {
  17612. opt[styleName].normal = normalItemStyleOpt[styleName];
  17613. } else {
  17614. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  17615. }
  17616. normalItemStyleOpt[styleName] = null;
  17617. }
  17618. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  17619. if ("development" !== 'production') {
  17620. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  17621. }
  17622. opt[styleName] = opt[styleName] || {};
  17623. if (!opt[styleName].emphasis) {
  17624. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  17625. } else {
  17626. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  17627. }
  17628. emphasisItemStyleOpt[styleName] = null;
  17629. }
  17630. }
  17631. }
  17632. function convertNormalEmphasis(opt, optType, useExtend) {
  17633. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  17634. var normalOpt = opt[optType].normal;
  17635. var emphasisOpt = opt[optType].emphasis;
  17636. if (normalOpt) {
  17637. if ("development" !== 'production') {
  17638. // eslint-disable-next-line max-len
  17639. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  17640. } // Timeline controlStyle has other properties besides normal and emphasis
  17641. if (useExtend) {
  17642. opt[optType].normal = opt[optType].emphasis = null;
  17643. defaults(opt[optType], normalOpt);
  17644. } else {
  17645. opt[optType] = normalOpt;
  17646. }
  17647. }
  17648. if (emphasisOpt) {
  17649. if ("development" !== 'production') {
  17650. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  17651. }
  17652. opt.emphasis = opt.emphasis || {};
  17653. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  17654. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  17655. if (emphasisOpt.focus) {
  17656. opt.emphasis.focus = emphasisOpt.focus;
  17657. }
  17658. if (emphasisOpt.blurScope) {
  17659. opt.emphasis.blurScope = emphasisOpt.blurScope;
  17660. }
  17661. }
  17662. }
  17663. }
  17664. function removeEC3NormalStatus(opt) {
  17665. convertNormalEmphasis(opt, 'itemStyle');
  17666. convertNormalEmphasis(opt, 'lineStyle');
  17667. convertNormalEmphasis(opt, 'areaStyle');
  17668. convertNormalEmphasis(opt, 'label');
  17669. convertNormalEmphasis(opt, 'labelLine'); // treemap
  17670. convertNormalEmphasis(opt, 'upperLabel'); // graph
  17671. convertNormalEmphasis(opt, 'edgeLabel');
  17672. }
  17673. function compatTextStyle(opt, propName) {
  17674. // Check whether is not object (string\null\undefined ...)
  17675. var labelOptSingle = isObject$1(opt) && opt[propName];
  17676. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  17677. if (textStyle) {
  17678. if ("development" !== 'production') {
  17679. // eslint-disable-next-line max-len
  17680. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  17681. }
  17682. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  17683. var textPropName = TEXT_STYLE_OPTIONS[i];
  17684. if (textStyle.hasOwnProperty(textPropName)) {
  17685. labelOptSingle[textPropName] = textStyle[textPropName];
  17686. }
  17687. }
  17688. }
  17689. }
  17690. function compatEC3CommonStyles(opt) {
  17691. if (opt) {
  17692. removeEC3NormalStatus(opt);
  17693. compatTextStyle(opt, 'label');
  17694. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  17695. }
  17696. }
  17697. function processSeries(seriesOpt) {
  17698. if (!isObject$1(seriesOpt)) {
  17699. return;
  17700. }
  17701. compatEC2ItemStyle(seriesOpt);
  17702. removeEC3NormalStatus(seriesOpt);
  17703. compatTextStyle(seriesOpt, 'label'); // treemap
  17704. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  17705. compatTextStyle(seriesOpt, 'edgeLabel');
  17706. if (seriesOpt.emphasis) {
  17707. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  17708. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  17709. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  17710. }
  17711. var markPoint = seriesOpt.markPoint;
  17712. if (markPoint) {
  17713. compatEC2ItemStyle(markPoint);
  17714. compatEC3CommonStyles(markPoint);
  17715. }
  17716. var markLine = seriesOpt.markLine;
  17717. if (markLine) {
  17718. compatEC2ItemStyle(markLine);
  17719. compatEC3CommonStyles(markLine);
  17720. }
  17721. var markArea = seriesOpt.markArea;
  17722. if (markArea) {
  17723. compatEC3CommonStyles(markArea);
  17724. }
  17725. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  17726. // then the backward compat based on option type will not be performed.
  17727. if (seriesOpt.type === 'graph') {
  17728. data = data || seriesOpt.nodes;
  17729. var edgeData = seriesOpt.links || seriesOpt.edges;
  17730. if (edgeData && !isTypedArray(edgeData)) {
  17731. for (var i = 0; i < edgeData.length; i++) {
  17732. compatEC3CommonStyles(edgeData[i]);
  17733. }
  17734. }
  17735. each(seriesOpt.categories, function (opt) {
  17736. removeEC3NormalStatus(opt);
  17737. });
  17738. }
  17739. if (data && !isTypedArray(data)) {
  17740. for (var i = 0; i < data.length; i++) {
  17741. compatEC3CommonStyles(data[i]);
  17742. }
  17743. } // mark point data
  17744. markPoint = seriesOpt.markPoint;
  17745. if (markPoint && markPoint.data) {
  17746. var mpData = markPoint.data;
  17747. for (var i = 0; i < mpData.length; i++) {
  17748. compatEC3CommonStyles(mpData[i]);
  17749. }
  17750. } // mark line data
  17751. markLine = seriesOpt.markLine;
  17752. if (markLine && markLine.data) {
  17753. var mlData = markLine.data;
  17754. for (var i = 0; i < mlData.length; i++) {
  17755. if (isArray(mlData[i])) {
  17756. compatEC3CommonStyles(mlData[i][0]);
  17757. compatEC3CommonStyles(mlData[i][1]);
  17758. } else {
  17759. compatEC3CommonStyles(mlData[i]);
  17760. }
  17761. }
  17762. } // Series
  17763. if (seriesOpt.type === 'gauge') {
  17764. compatTextStyle(seriesOpt, 'axisLabel');
  17765. compatTextStyle(seriesOpt, 'title');
  17766. compatTextStyle(seriesOpt, 'detail');
  17767. } else if (seriesOpt.type === 'treemap') {
  17768. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  17769. each(seriesOpt.levels, function (opt) {
  17770. removeEC3NormalStatus(opt);
  17771. });
  17772. } else if (seriesOpt.type === 'tree') {
  17773. removeEC3NormalStatus(seriesOpt.leaves);
  17774. } // sunburst starts from ec4, so it does not need to compat levels.
  17775. }
  17776. function toArr(o) {
  17777. return isArray(o) ? o : o ? [o] : [];
  17778. }
  17779. function toObj(o) {
  17780. return (isArray(o) ? o[0] : o) || {};
  17781. }
  17782. function globalCompatStyle(option, isTheme) {
  17783. each$2(toArr(option.series), function (seriesOpt) {
  17784. isObject$1(seriesOpt) && processSeries(seriesOpt);
  17785. });
  17786. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  17787. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  17788. each$2(axes, function (axisName) {
  17789. each$2(toArr(option[axisName]), function (axisOpt) {
  17790. if (axisOpt) {
  17791. compatTextStyle(axisOpt, 'axisLabel');
  17792. compatTextStyle(axisOpt.axisPointer, 'label');
  17793. }
  17794. });
  17795. });
  17796. each$2(toArr(option.parallel), function (parallelOpt) {
  17797. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  17798. compatTextStyle(parallelAxisDefault, 'axisLabel');
  17799. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  17800. });
  17801. each$2(toArr(option.calendar), function (calendarOpt) {
  17802. convertNormalEmphasis(calendarOpt, 'itemStyle');
  17803. compatTextStyle(calendarOpt, 'dayLabel');
  17804. compatTextStyle(calendarOpt, 'monthLabel');
  17805. compatTextStyle(calendarOpt, 'yearLabel');
  17806. }); // radar.name.textStyle
  17807. each$2(toArr(option.radar), function (radarOpt) {
  17808. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  17809. if (radarOpt.name && radarOpt.axisName == null) {
  17810. radarOpt.axisName = radarOpt.name;
  17811. delete radarOpt.name;
  17812. if ("development" !== 'production') {
  17813. deprecateLog('name property in radar component has been changed to axisName');
  17814. }
  17815. }
  17816. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  17817. radarOpt.axisNameGap = radarOpt.nameGap;
  17818. delete radarOpt.nameGap;
  17819. if ("development" !== 'production') {
  17820. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  17821. }
  17822. }
  17823. });
  17824. each$2(toArr(option.geo), function (geoOpt) {
  17825. if (isObject$1(geoOpt)) {
  17826. compatEC3CommonStyles(geoOpt);
  17827. each$2(toArr(geoOpt.regions), function (regionObj) {
  17828. compatEC3CommonStyles(regionObj);
  17829. });
  17830. }
  17831. });
  17832. each$2(toArr(option.timeline), function (timelineOpt) {
  17833. compatEC3CommonStyles(timelineOpt);
  17834. convertNormalEmphasis(timelineOpt, 'label');
  17835. convertNormalEmphasis(timelineOpt, 'itemStyle');
  17836. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  17837. var data = timelineOpt.data;
  17838. isArray(data) && each(data, function (item) {
  17839. if (isObject(item)) {
  17840. convertNormalEmphasis(item, 'label');
  17841. convertNormalEmphasis(item, 'itemStyle');
  17842. }
  17843. });
  17844. });
  17845. each$2(toArr(option.toolbox), function (toolboxOpt) {
  17846. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  17847. each$2(toolboxOpt.feature, function (featureOpt) {
  17848. convertNormalEmphasis(featureOpt, 'iconStyle');
  17849. });
  17850. });
  17851. compatTextStyle(toObj(option.axisPointer), 'label');
  17852. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  17853. // storedLogs = {};
  17854. }
  17855. function get(opt, path) {
  17856. var pathArr = path.split(',');
  17857. var obj = opt;
  17858. for (var i = 0; i < pathArr.length; i++) {
  17859. obj = obj && obj[pathArr[i]];
  17860. if (obj == null) {
  17861. break;
  17862. }
  17863. }
  17864. return obj;
  17865. }
  17866. function set$1(opt, path, val, overwrite) {
  17867. var pathArr = path.split(',');
  17868. var obj = opt;
  17869. var key;
  17870. var i = 0;
  17871. for (; i < pathArr.length - 1; i++) {
  17872. key = pathArr[i];
  17873. if (obj[key] == null) {
  17874. obj[key] = {};
  17875. }
  17876. obj = obj[key];
  17877. }
  17878. if (overwrite || obj[pathArr[i]] == null) {
  17879. obj[pathArr[i]] = val;
  17880. }
  17881. }
  17882. function compatLayoutProperties(option) {
  17883. option && each(LAYOUT_PROPERTIES, function (prop) {
  17884. if (prop[0] in option && !(prop[1] in option)) {
  17885. option[prop[1]] = option[prop[0]];
  17886. }
  17887. });
  17888. }
  17889. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  17890. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  17891. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  17892. function compatBarItemStyle(option) {
  17893. var itemStyle = option && option.itemStyle;
  17894. if (itemStyle) {
  17895. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  17896. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  17897. var newName = BAR_ITEM_STYLE_MAP[i][0];
  17898. if (itemStyle[oldName] != null) {
  17899. itemStyle[newName] = itemStyle[oldName];
  17900. if ("development" !== 'production') {
  17901. deprecateReplaceLog(oldName, newName);
  17902. }
  17903. }
  17904. }
  17905. }
  17906. }
  17907. function compatPieLabel(option) {
  17908. if (!option) {
  17909. return;
  17910. }
  17911. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  17912. if ("development" !== 'production') {
  17913. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  17914. }
  17915. option.edgeDistance = option.margin;
  17916. }
  17917. }
  17918. function compatSunburstState(option) {
  17919. if (!option) {
  17920. return;
  17921. }
  17922. if (option.downplay && !option.blur) {
  17923. option.blur = option.downplay;
  17924. if ("development" !== 'production') {
  17925. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  17926. }
  17927. }
  17928. }
  17929. function compatGraphFocus(option) {
  17930. if (!option) {
  17931. return;
  17932. }
  17933. if (option.focusNodeAdjacency != null) {
  17934. option.emphasis = option.emphasis || {};
  17935. if (option.emphasis.focus == null) {
  17936. if ("development" !== 'production') {
  17937. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  17938. }
  17939. option.emphasis.focus = 'adjacency';
  17940. }
  17941. }
  17942. }
  17943. function traverseTree(data, cb) {
  17944. if (data) {
  17945. for (var i = 0; i < data.length; i++) {
  17946. cb(data[i]);
  17947. data[i] && traverseTree(data[i].children, cb);
  17948. }
  17949. }
  17950. }
  17951. function globalBackwardCompat(option, isTheme) {
  17952. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  17953. option.series = normalizeToArray(option.series);
  17954. each(option.series, function (seriesOpt) {
  17955. if (!isObject(seriesOpt)) {
  17956. return;
  17957. }
  17958. var seriesType = seriesOpt.type;
  17959. if (seriesType === 'line') {
  17960. if (seriesOpt.clipOverflow != null) {
  17961. seriesOpt.clip = seriesOpt.clipOverflow;
  17962. if ("development" !== 'production') {
  17963. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  17964. }
  17965. }
  17966. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  17967. if (seriesOpt.clockWise != null) {
  17968. seriesOpt.clockwise = seriesOpt.clockWise;
  17969. if ("development" !== 'production') {
  17970. deprecateReplaceLog('clockWise', 'clockwise');
  17971. }
  17972. }
  17973. compatPieLabel(seriesOpt.label);
  17974. var data = seriesOpt.data;
  17975. if (data && !isTypedArray(data)) {
  17976. for (var i = 0; i < data.length; i++) {
  17977. compatPieLabel(data[i]);
  17978. }
  17979. }
  17980. if (seriesOpt.hoverOffset != null) {
  17981. seriesOpt.emphasis = seriesOpt.emphasis || {};
  17982. if (seriesOpt.emphasis.scaleSize = null) {
  17983. if ("development" !== 'production') {
  17984. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  17985. }
  17986. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  17987. }
  17988. }
  17989. } else if (seriesType === 'gauge') {
  17990. var pointerColor = get(seriesOpt, 'pointer.color');
  17991. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  17992. } else if (seriesType === 'bar') {
  17993. compatBarItemStyle(seriesOpt);
  17994. compatBarItemStyle(seriesOpt.backgroundStyle);
  17995. compatBarItemStyle(seriesOpt.emphasis);
  17996. var data = seriesOpt.data;
  17997. if (data && !isTypedArray(data)) {
  17998. for (var i = 0; i < data.length; i++) {
  17999. if (typeof data[i] === 'object') {
  18000. compatBarItemStyle(data[i]);
  18001. compatBarItemStyle(data[i] && data[i].emphasis);
  18002. }
  18003. }
  18004. }
  18005. } else if (seriesType === 'sunburst') {
  18006. var highlightPolicy = seriesOpt.highlightPolicy;
  18007. if (highlightPolicy) {
  18008. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18009. if (!seriesOpt.emphasis.focus) {
  18010. seriesOpt.emphasis.focus = highlightPolicy;
  18011. if ("development" !== 'production') {
  18012. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18013. }
  18014. }
  18015. }
  18016. compatSunburstState(seriesOpt);
  18017. traverseTree(seriesOpt.data, compatSunburstState);
  18018. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18019. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18020. } else if (seriesType === 'map') {
  18021. if (seriesOpt.mapType && !seriesOpt.map) {
  18022. if ("development" !== 'production') {
  18023. deprecateReplaceLog('mapType', 'map', 'map');
  18024. }
  18025. seriesOpt.map = seriesOpt.mapType;
  18026. }
  18027. if (seriesOpt.mapLocation) {
  18028. if ("development" !== 'production') {
  18029. deprecateLog('`mapLocation` is not used anymore.');
  18030. }
  18031. defaults(seriesOpt, seriesOpt.mapLocation);
  18032. }
  18033. }
  18034. if (seriesOpt.hoverAnimation != null) {
  18035. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18036. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18037. if ("development" !== 'production') {
  18038. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18039. }
  18040. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18041. }
  18042. }
  18043. compatLayoutProperties(seriesOpt);
  18044. }); // dataRange has changed to visualMap
  18045. if (option.dataRange) {
  18046. option.visualMap = option.dataRange;
  18047. }
  18048. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18049. var options = option[componentName];
  18050. if (options) {
  18051. if (!isArray(options)) {
  18052. options = [options];
  18053. }
  18054. each(options, function (option) {
  18055. compatLayoutProperties(option);
  18056. });
  18057. }
  18058. });
  18059. }
  18060. // data processing stage is blocked in stream.
  18061. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18062. // (2) Only register once when import repeatly.
  18063. // Should be executed after series filtered and before stack calculation.
  18064. function dataStack(ecModel) {
  18065. var stackInfoMap = createHashMap();
  18066. ecModel.eachSeries(function (seriesModel) {
  18067. var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack.
  18068. if (stack) {
  18069. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18070. var data = seriesModel.getData();
  18071. var stackInfo = {
  18072. // Used for calculate axis extent automatically.
  18073. // TODO: Type getCalculationInfo return more specific type?
  18074. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18075. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18076. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18077. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18078. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18079. data: data,
  18080. seriesModel: seriesModel
  18081. }; // If stacked on axis that do not support data stack.
  18082. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18083. return;
  18084. }
  18085. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18086. stackInfoList.push(stackInfo);
  18087. }
  18088. });
  18089. stackInfoMap.each(calculateStack);
  18090. }
  18091. function calculateStack(stackInfoList) {
  18092. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18093. var resultVal = [];
  18094. var resultNaN = [NaN, NaN];
  18095. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18096. var targetData = targetStackInfo.data;
  18097. var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes
  18098. // depending on legend selection.
  18099. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  18100. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18101. // should also be NaN, to draw a appropriate belt area.
  18102. if (isNaN(sum)) {
  18103. return resultNaN;
  18104. }
  18105. var byValue;
  18106. var stackedDataRawIndex;
  18107. if (isStackedByIndex) {
  18108. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18109. } else {
  18110. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18111. } // If stackOver is NaN, chart view will render point on value start.
  18112. var stackedOver = NaN;
  18113. for (var j = idxInStack - 1; j >= 0; j--) {
  18114. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18115. if (!isStackedByIndex) {
  18116. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18117. }
  18118. if (stackedDataRawIndex >= 0) {
  18119. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18120. if (sum >= 0 && val > 0 || // Positive stack
  18121. sum <= 0 && val < 0 // Negative stack
  18122. ) {
  18123. sum += val;
  18124. stackedOver = val;
  18125. break;
  18126. }
  18127. }
  18128. }
  18129. resultVal[0] = sum;
  18130. resultVal[1] = stackedOver;
  18131. return resultVal;
  18132. });
  18133. targetData.hostModel.setData(newData); // Update for consequent calculation
  18134. targetStackInfo.data = newData;
  18135. });
  18136. }
  18137. var SourceImpl =
  18138. /** @class */
  18139. function () {
  18140. // readonly frozen: boolean;
  18141. function SourceImpl(fields) {
  18142. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18143. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18144. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18145. this.startIndex = fields.startIndex || 0;
  18146. this.dimensionsDefine = fields.dimensionsDefine;
  18147. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18148. this.encodeDefine = fields.encodeDefine;
  18149. this.metaRawOption = fields.metaRawOption;
  18150. }
  18151. return SourceImpl;
  18152. }();
  18153. function isSourceInstance(val) {
  18154. return val instanceof SourceImpl;
  18155. }
  18156. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18157. sourceFormat, encodeDefine // can be null
  18158. ) {
  18159. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18160. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18161. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18162. var source = new SourceImpl({
  18163. data: sourceData,
  18164. sourceFormat: sourceFormat,
  18165. seriesLayoutBy: seriesLayoutBy,
  18166. dimensionsDefine: determined.dimensionsDefine,
  18167. startIndex: determined.startIndex,
  18168. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18169. encodeDefine: makeEncodeDefine(encodeDefine),
  18170. metaRawOption: clone(thisMetaRawOption)
  18171. });
  18172. return source;
  18173. }
  18174. /**
  18175. * Wrap original series data for some compatibility cases.
  18176. */
  18177. function createSourceFromSeriesDataOption(data) {
  18178. return new SourceImpl({
  18179. data: data,
  18180. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18181. });
  18182. }
  18183. /**
  18184. * Clone source but excludes source data.
  18185. */
  18186. function cloneSourceShallow(source) {
  18187. return new SourceImpl({
  18188. data: source.data,
  18189. sourceFormat: source.sourceFormat,
  18190. seriesLayoutBy: source.seriesLayoutBy,
  18191. dimensionsDefine: clone(source.dimensionsDefine),
  18192. startIndex: source.startIndex,
  18193. dimensionsDetectedCount: source.dimensionsDetectedCount,
  18194. encodeDefine: makeEncodeDefine(source.encodeDefine)
  18195. });
  18196. }
  18197. function makeEncodeDefine(encodeDefine) {
  18198. // null means user not specify `series.encode`.
  18199. return encodeDefine ? createHashMap(encodeDefine) : null;
  18200. }
  18201. /**
  18202. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18203. */
  18204. function detectSourceFormat(data) {
  18205. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18206. if (isTypedArray(data)) {
  18207. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18208. } else if (isArray(data)) {
  18209. // FIXME Whether tolerate null in top level array?
  18210. if (data.length === 0) {
  18211. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18212. }
  18213. for (var i = 0, len = data.length; i < len; i++) {
  18214. var item = data[i];
  18215. if (item == null) {
  18216. continue;
  18217. } else if (isArray(item)) {
  18218. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18219. break;
  18220. } else if (isObject(item)) {
  18221. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18222. break;
  18223. }
  18224. }
  18225. } else if (isObject(data)) {
  18226. for (var key in data) {
  18227. if (hasOwn(data, key) && isArrayLike(data[key])) {
  18228. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18229. break;
  18230. }
  18231. }
  18232. }
  18233. return sourceFormat;
  18234. }
  18235. /**
  18236. * Determine the source definitions from data standalone dimensions definitions
  18237. * are not specified.
  18238. */
  18239. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  18240. // {
  18241. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  18242. // }
  18243. // in `dataset` or `series`
  18244. dimensionsDefine) {
  18245. var dimensionsDetectedCount;
  18246. var startIndex; // PEDING: could data be null/undefined here?
  18247. // currently, if `dataset.source` not specified, error thrown.
  18248. // if `series.data` not specified, nothing rendered without error thrown.
  18249. // Should test these cases.
  18250. if (!data) {
  18251. return {
  18252. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18253. startIndex: startIndex,
  18254. dimensionsDetectedCount: dimensionsDetectedCount
  18255. };
  18256. }
  18257. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18258. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  18259. // Caution: consider a line with 5 string and 1 number,
  18260. // it still can not be sure it is a head, because the
  18261. // 5 string may be 5 values of category columns.
  18262. if (sourceHeader === 'auto' || sourceHeader == null) {
  18263. arrayRowsTravelFirst(function (val) {
  18264. // '-' is regarded as null/undefined.
  18265. if (val != null && val !== '-') {
  18266. if (isString(val)) {
  18267. startIndex == null && (startIndex = 1);
  18268. } else {
  18269. startIndex = 0;
  18270. }
  18271. } // 10 is an experience number, avoid long loop.
  18272. }, seriesLayoutBy, dataArrayRows, 10);
  18273. } else {
  18274. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  18275. }
  18276. if (!dimensionsDefine && startIndex === 1) {
  18277. dimensionsDefine = [];
  18278. arrayRowsTravelFirst(function (val, index) {
  18279. dimensionsDefine[index] = val != null ? val + '' : '';
  18280. }, seriesLayoutBy, dataArrayRows, Infinity);
  18281. }
  18282. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  18283. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18284. if (!dimensionsDefine) {
  18285. dimensionsDefine = objectRowsCollectDimensions(data);
  18286. }
  18287. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18288. if (!dimensionsDefine) {
  18289. dimensionsDefine = [];
  18290. each(data, function (colArr, key) {
  18291. dimensionsDefine.push(key);
  18292. });
  18293. }
  18294. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18295. var value0 = getDataItemValue(data[0]);
  18296. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  18297. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18298. if ("development" !== 'production') {
  18299. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18300. }
  18301. }
  18302. return {
  18303. startIndex: startIndex,
  18304. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18305. dimensionsDetectedCount: dimensionsDetectedCount
  18306. };
  18307. }
  18308. function objectRowsCollectDimensions(data) {
  18309. var firstIndex = 0;
  18310. var obj;
  18311. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18312. if (obj) {
  18313. var dimensions_1 = [];
  18314. each(obj, function (value, key) {
  18315. dimensions_1.push(key);
  18316. });
  18317. return dimensions_1;
  18318. }
  18319. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18320. // which is reasonable. But dimension name is duplicated.
  18321. // Returns undefined or an array contains only object without null/undefiend or string.
  18322. function normalizeDimensionsOption(dimensionsDefine) {
  18323. if (!dimensionsDefine) {
  18324. // The meaning of null/undefined is different from empty array.
  18325. return;
  18326. }
  18327. var nameMap = createHashMap();
  18328. return map(dimensionsDefine, function (rawItem, index) {
  18329. rawItem = isObject(rawItem) ? rawItem : {
  18330. name: rawItem
  18331. }; // Other fields will be discarded.
  18332. var item = {
  18333. name: rawItem.name,
  18334. displayName: rawItem.displayName,
  18335. type: rawItem.type
  18336. }; // User can set null in dimensions.
  18337. // We dont auto specify name, othewise a given name may
  18338. // cause it be refered unexpectedly.
  18339. if (item.name == null) {
  18340. return item;
  18341. } // Also consider number form like 2012.
  18342. item.name += ''; // User may also specify displayName.
  18343. // displayName will always exists except user not
  18344. // specified or dim name is not specified or detected.
  18345. // (A auto generated dim name will not be used as
  18346. // displayName).
  18347. if (item.displayName == null) {
  18348. item.displayName = item.name;
  18349. }
  18350. var exist = nameMap.get(item.name);
  18351. if (!exist) {
  18352. nameMap.set(item.name, {
  18353. count: 1
  18354. });
  18355. } else {
  18356. item.name += '-' + exist.count++;
  18357. }
  18358. return item;
  18359. });
  18360. }
  18361. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18362. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18363. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18364. cb(data[i] ? data[i][0] : null, i);
  18365. }
  18366. } else {
  18367. var value0 = data[0] || [];
  18368. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18369. cb(value0[i], i);
  18370. }
  18371. }
  18372. }
  18373. /*
  18374. * Licensed to the Apache Software Foundation (ASF) under one
  18375. * or more contributor license agreements. See the NOTICE file
  18376. * distributed with this work for additional information
  18377. * regarding copyright ownership. The ASF licenses this file
  18378. * to you under the Apache License, Version 2.0 (the
  18379. * "License"); you may not use this file except in compliance
  18380. * with the License. You may obtain a copy of the License at
  18381. *
  18382. * http://www.apache.org/licenses/LICENSE-2.0
  18383. *
  18384. * Unless required by applicable law or agreed to in writing,
  18385. * software distributed under the License is distributed on an
  18386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18387. * KIND, either express or implied. See the License for the
  18388. * specific language governing permissions and limitations
  18389. * under the License.
  18390. */
  18391. /**
  18392. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18393. */
  18394. /*
  18395. * Licensed to the Apache Software Foundation (ASF) under one
  18396. * or more contributor license agreements. See the NOTICE file
  18397. * distributed with this work for additional information
  18398. * regarding copyright ownership. The ASF licenses this file
  18399. * to you under the Apache License, Version 2.0 (the
  18400. * "License"); you may not use this file except in compliance
  18401. * with the License. You may obtain a copy of the License at
  18402. *
  18403. * http://www.apache.org/licenses/LICENSE-2.0
  18404. *
  18405. * Unless required by applicable law or agreed to in writing,
  18406. * software distributed under the License is distributed on an
  18407. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18408. * KIND, either express or implied. See the License for the
  18409. * specific language governing permissions and limitations
  18410. * under the License.
  18411. */
  18412. var _a, _b, _c; // TODO
  18413. var providerMethods;
  18414. var mountMethods;
  18415. /**
  18416. * If normal array used, mutable chunk size is supported.
  18417. * If typed array used, chunk size must be fixed.
  18418. */
  18419. var DefaultDataProvider =
  18420. /** @class */
  18421. function () {
  18422. function DefaultDataProvider(sourceParam, dimSize) {
  18423. // let source: Source;
  18424. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  18425. this._source = source;
  18426. var data = this._data = source.data; // Typed array. TODO IE10+?
  18427. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18428. if ("development" !== 'production') {
  18429. if (dimSize == null) {
  18430. throw new Error('Typed array data must specify dimension size');
  18431. }
  18432. }
  18433. this._offset = 0;
  18434. this._dimSize = dimSize;
  18435. this._data = data;
  18436. }
  18437. mountMethods(this, data, source);
  18438. }
  18439. DefaultDataProvider.prototype.getSource = function () {
  18440. return this._source;
  18441. };
  18442. DefaultDataProvider.prototype.count = function () {
  18443. return 0;
  18444. };
  18445. DefaultDataProvider.prototype.getItem = function (idx, out) {
  18446. return;
  18447. };
  18448. DefaultDataProvider.prototype.appendData = function (newData) {};
  18449. DefaultDataProvider.prototype.clean = function () {};
  18450. DefaultDataProvider.protoInitialize = function () {
  18451. // PENDING: To avoid potential incompat (e.g., prototype
  18452. // is visited somewhere), still init them on prototype.
  18453. var proto = DefaultDataProvider.prototype;
  18454. proto.pure = false;
  18455. proto.persistent = true;
  18456. }();
  18457. DefaultDataProvider.internalField = function () {
  18458. var _a;
  18459. mountMethods = function (provider, data, source) {
  18460. var sourceFormat = source.sourceFormat;
  18461. var seriesLayoutBy = source.seriesLayoutBy;
  18462. var startIndex = source.startIndex;
  18463. var dimsDef = source.dimensionsDefine;
  18464. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18465. if ("development" !== 'production') {
  18466. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18467. }
  18468. extend(provider, methods);
  18469. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18470. provider.getItem = getItemForTypedArray;
  18471. provider.count = countForTypedArray;
  18472. provider.fillStorage = fillStorageForTypedArray;
  18473. } else {
  18474. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  18475. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  18476. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  18477. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  18478. }
  18479. };
  18480. var getItemForTypedArray = function (idx, out) {
  18481. idx = idx - this._offset;
  18482. out = out || [];
  18483. var data = this._data;
  18484. var dimSize = this._dimSize;
  18485. var offset = dimSize * idx;
  18486. for (var i = 0; i < dimSize; i++) {
  18487. out[i] = data[offset + i];
  18488. }
  18489. return out;
  18490. };
  18491. var fillStorageForTypedArray = function (start, end, storage, extent) {
  18492. var data = this._data;
  18493. var dimSize = this._dimSize;
  18494. for (var dim = 0; dim < dimSize; dim++) {
  18495. var dimExtent = extent[dim];
  18496. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  18497. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  18498. var count = end - start;
  18499. var arr = storage[dim];
  18500. for (var i = 0; i < count; i++) {
  18501. // appendData with TypedArray will always do replace in provider.
  18502. var val = data[i * dimSize + dim];
  18503. arr[start + i] = val;
  18504. val < min && (min = val);
  18505. val > max && (max = val);
  18506. }
  18507. dimExtent[0] = min;
  18508. dimExtent[1] = max;
  18509. }
  18510. };
  18511. var countForTypedArray = function () {
  18512. return this._data ? this._data.length / this._dimSize : 0;
  18513. };
  18514. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  18515. pure: true,
  18516. appendData: appendDataSimply
  18517. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  18518. pure: true,
  18519. appendData: function () {
  18520. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18521. }
  18522. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  18523. pure: true,
  18524. appendData: appendDataSimply
  18525. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  18526. pure: true,
  18527. appendData: function (newData) {
  18528. var data = this._data;
  18529. each(newData, function (newCol, key) {
  18530. var oldCol = data[key] || (data[key] = []);
  18531. for (var i = 0; i < (newCol || []).length; i++) {
  18532. oldCol.push(newCol[i]);
  18533. }
  18534. });
  18535. }
  18536. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  18537. appendData: appendDataSimply
  18538. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  18539. persistent: false,
  18540. pure: true,
  18541. appendData: function (newData) {
  18542. if ("development" !== 'production') {
  18543. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  18544. }
  18545. this._data = newData;
  18546. },
  18547. // Clean self if data is already used.
  18548. clean: function () {
  18549. // PENDING
  18550. this._offset += this.count();
  18551. this._data = null;
  18552. }
  18553. }, _a);
  18554. function appendDataSimply(newData) {
  18555. for (var i = 0; i < newData.length; i++) {
  18556. this._data.push(newData[i]);
  18557. }
  18558. }
  18559. }();
  18560. return DefaultDataProvider;
  18561. }();
  18562. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  18563. return rawData[idx];
  18564. };
  18565. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  18566. return rawData[idx + startIndex];
  18567. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx) {
  18568. idx += startIndex;
  18569. var item = [];
  18570. var data = rawData;
  18571. for (var i = 0; i < data.length; i++) {
  18572. var row = data[i];
  18573. item.push(row ? row[idx] : null);
  18574. }
  18575. return item;
  18576. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx) {
  18577. var item = [];
  18578. for (var i = 0; i < dimsDef.length; i++) {
  18579. var dimName = dimsDef[i].name;
  18580. if ("development" !== 'production') {
  18581. if (dimName == null) {
  18582. throw new Error();
  18583. }
  18584. }
  18585. var col = rawData[dimName];
  18586. item.push(col ? col[idx] : null);
  18587. }
  18588. return item;
  18589. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  18590. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  18591. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18592. if ("development" !== 'production') {
  18593. assert(method, 'Do not suppport get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18594. }
  18595. return method;
  18596. }
  18597. var countSimply = function (rawData, startIndex, dimsDef) {
  18598. return rawData.length;
  18599. };
  18600. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  18601. return Math.max(0, rawData.length - startIndex);
  18602. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  18603. var row = rawData[0];
  18604. return row ? Math.max(0, row.length - startIndex) : 0;
  18605. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  18606. var dimName = dimsDef[0].name;
  18607. if ("development" !== 'production') {
  18608. if (dimName == null) {
  18609. throw new Error();
  18610. }
  18611. }
  18612. var col = rawData[dimName];
  18613. return col ? col.length : 0;
  18614. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  18615. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  18616. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18617. if ("development" !== 'production') {
  18618. assert(method, 'Do not suppport count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18619. }
  18620. return method;
  18621. }
  18622. var getRawValueSimply = function (dataItem, dimIndex, dimName) {
  18623. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18624. };
  18625. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, dimName) {
  18626. return dimIndex != null ? dataItem[dimName] : dataItem;
  18627. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, dimName) {
  18628. // FIXME: In some case (markpoint in geo (geo-map.html)),
  18629. // dataItem is {coord: [...]}
  18630. var value = getDataItemValue(dataItem);
  18631. return dimIndex == null || !(value instanceof Array) ? value : value[dimIndex];
  18632. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  18633. function getRawSourceValueGetter(sourceFormat) {
  18634. var method = rawSourceValueGetterMap[sourceFormat];
  18635. if ("development" !== 'production') {
  18636. assert(method, 'Do not suppport get value on "' + sourceFormat + '".');
  18637. }
  18638. return method;
  18639. }
  18640. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  18641. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  18642. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18643. // Consider persistent.
  18644. // Caution: why use raw value to display on label or tooltip?
  18645. // A reason is to avoid format. For example time value we do not know
  18646. // how to format is expected. More over, if stack is used, calculated
  18647. // value may be 0.91000000001, which have brings trouble to display.
  18648. // TODO: consider how to treat null/undefined/NaN when display?
  18649. function retrieveRawValue(data, dataIndex, dim // If dimIndex is null/undefined, return OptionDataItem.
  18650. // Otherwise, return OptionDataValue.
  18651. ) {
  18652. if (!data) {
  18653. return;
  18654. } // Consider data may be not persistent.
  18655. var dataItem = data.getRawDataItem(dataIndex);
  18656. if (dataItem == null) {
  18657. return;
  18658. }
  18659. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18660. var dimName;
  18661. var dimIndex;
  18662. var dimInfo = data.getDimensionInfo(dim);
  18663. if (dimInfo) {
  18664. dimName = dimInfo.name;
  18665. dimIndex = dimInfo.index;
  18666. }
  18667. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, dimName);
  18668. }
  18669. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18670. var DataFormatMixin =
  18671. /** @class */
  18672. function () {
  18673. function DataFormatMixin() {}
  18674. /**
  18675. * Get params for formatter
  18676. */
  18677. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  18678. var data = this.getData(dataType);
  18679. var rawValue = this.getRawValue(dataIndex, dataType);
  18680. var rawDataIndex = data.getRawIndex(dataIndex);
  18681. var name = data.getName(dataIndex);
  18682. var itemOpt = data.getRawDataItem(dataIndex);
  18683. var style = data.getItemVisual(dataIndex, 'style');
  18684. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  18685. var borderColor = style && style.stroke;
  18686. var mainType = this.mainType;
  18687. var isSeries = mainType === 'series';
  18688. var userOutput = data.userOutput;
  18689. return {
  18690. componentType: mainType,
  18691. componentSubType: this.subType,
  18692. componentIndex: this.componentIndex,
  18693. seriesType: isSeries ? this.subType : null,
  18694. seriesIndex: this.seriesIndex,
  18695. seriesId: isSeries ? this.id : null,
  18696. seriesName: isSeries ? this.name : null,
  18697. name: name,
  18698. dataIndex: rawDataIndex,
  18699. data: itemOpt,
  18700. dataType: dataType,
  18701. value: rawValue,
  18702. color: color,
  18703. borderColor: borderColor,
  18704. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  18705. encode: userOutput ? userOutput.encode : null,
  18706. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18707. $vars: ['seriesName', 'name', 'value']
  18708. };
  18709. };
  18710. /**
  18711. * Format label
  18712. * @param dataIndex
  18713. * @param status 'normal' by default
  18714. * @param dataType
  18715. * @param labelDimIndex Only used in some chart that
  18716. * use formatter in different dimensions, like radar.
  18717. * @param formatter Formatter given outside.
  18718. * @return return null/undefined if no formatter
  18719. */
  18720. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  18721. status = status || 'normal';
  18722. var data = this.getData(dataType);
  18723. var params = this.getDataParams(dataIndex, dataType);
  18724. if (extendParams) {
  18725. params.value = extendParams.interpolatedValue;
  18726. }
  18727. if (labelDimIndex != null && isArray(params.value)) {
  18728. params.value = params.value[labelDimIndex];
  18729. }
  18730. if (!formatter) {
  18731. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  18732. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  18733. }
  18734. if (typeof formatter === 'function') {
  18735. params.status = status;
  18736. params.dimensionIndex = labelDimIndex;
  18737. return formatter(params);
  18738. } else if (typeof formatter === 'string') {
  18739. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  18740. // Do not support '}' in dim name util have to.
  18741. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  18742. var len = dimStr.length;
  18743. var dimLoose = dimStr.charAt(0) === '[' && dimStr.charAt(len - 1) === ']' ? +dimStr.slice(1, len - 1) // Also support: '[]' => 0
  18744. : dimStr;
  18745. var val = retrieveRawValue(data, dataIndex, dimLoose);
  18746. if (extendParams && isArray(extendParams.interpolatedValue)) {
  18747. var dimInfo = data.getDimensionInfo(dimLoose);
  18748. if (dimInfo) {
  18749. val = extendParams.interpolatedValue[dimInfo.index];
  18750. }
  18751. }
  18752. return val != null ? val + '' : '';
  18753. });
  18754. }
  18755. };
  18756. /**
  18757. * Get raw value in option
  18758. */
  18759. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  18760. return retrieveRawValue(this.getData(dataType), idx);
  18761. };
  18762. /**
  18763. * Should be implemented.
  18764. * @param {number} dataIndex
  18765. * @param {boolean} [multipleSeries=false]
  18766. * @param {string} [dataType]
  18767. */
  18768. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  18769. // Empty function
  18770. return;
  18771. };
  18772. return DataFormatMixin;
  18773. }();
  18774. // but guess little chance has been used outside. Do we need to backward
  18775. // compat it?
  18776. // type TooltipFormatResultLegacyObject = {
  18777. // // `html` means the markup language text, either in 'html' or 'richText'.
  18778. // // The name `html` is not appropriate becuase in 'richText' it is not a HTML
  18779. // // string. But still support it for backward compat.
  18780. // html: string;
  18781. // markers: Dictionary<ColorString>;
  18782. // };
  18783. /**
  18784. * For backward compat, normalize the return from `formatTooltip`.
  18785. */
  18786. function normalizeTooltipFormatResult(result // markersExisting: Dictionary<ColorString>
  18787. ) {
  18788. var markupText; // let markers: Dictionary<ColorString>;
  18789. var markupFragment;
  18790. if (isObject(result)) {
  18791. if (result.type) {
  18792. markupFragment = result;
  18793. } else {
  18794. if ("development" !== 'production') {
  18795. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  18796. }
  18797. } // else {
  18798. // markupText = (result as TooltipFormatResultLegacyObject).html;
  18799. // markers = (result as TooltipFormatResultLegacyObject).markers;
  18800. // if (markersExisting) {
  18801. // markers = zrUtil.merge(markersExisting, markers);
  18802. // }
  18803. // }
  18804. } else {
  18805. markupText = result;
  18806. }
  18807. return {
  18808. markupText: markupText,
  18809. // markers: markers || markersExisting,
  18810. markupFragment: markupFragment
  18811. };
  18812. }
  18813. /**
  18814. * @param {Object} define
  18815. * @return See the return of `createTask`.
  18816. */
  18817. function createTask(define) {
  18818. return new Task(define);
  18819. }
  18820. var Task =
  18821. /** @class */
  18822. function () {
  18823. function Task(define) {
  18824. define = define || {};
  18825. this._reset = define.reset;
  18826. this._plan = define.plan;
  18827. this._count = define.count;
  18828. this._onDirty = define.onDirty;
  18829. this._dirty = true;
  18830. }
  18831. /**
  18832. * @param step Specified step.
  18833. * @param skip Skip customer perform call.
  18834. * @param modBy Sampling window size.
  18835. * @param modDataCount Sampling count.
  18836. * @return whether unfinished.
  18837. */
  18838. Task.prototype.perform = function (performArgs) {
  18839. var upTask = this._upstream;
  18840. var skip = performArgs && performArgs.skip; // TODO some refactor.
  18841. // Pull data. Must pull data each time, because context.data
  18842. // may be updated by Series.setData.
  18843. if (this._dirty && upTask) {
  18844. var context = this.context;
  18845. context.data = context.outputData = upTask.context.outputData;
  18846. }
  18847. if (this.__pipeline) {
  18848. this.__pipeline.currentTask = this;
  18849. }
  18850. var planResult;
  18851. if (this._plan && !skip) {
  18852. planResult = this._plan(this.context);
  18853. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  18854. // elements uniformed distributed when progress, especially when moving or zooming.
  18855. var lastModBy = normalizeModBy(this._modBy);
  18856. var lastModDataCount = this._modDataCount || 0;
  18857. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  18858. var modDataCount = performArgs && performArgs.modDataCount || 0;
  18859. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  18860. planResult = 'reset';
  18861. }
  18862. function normalizeModBy(val) {
  18863. !(val >= 1) && (val = 1); // jshint ignore:line
  18864. return val;
  18865. }
  18866. var forceFirstProgress;
  18867. if (this._dirty || planResult === 'reset') {
  18868. this._dirty = false;
  18869. forceFirstProgress = this._doReset(skip);
  18870. }
  18871. this._modBy = modBy;
  18872. this._modDataCount = modDataCount;
  18873. var step = performArgs && performArgs.step;
  18874. if (upTask) {
  18875. if ("development" !== 'production') {
  18876. assert(upTask._outputDueEnd != null);
  18877. }
  18878. this._dueEnd = upTask._outputDueEnd;
  18879. } // DataTask or overallTask
  18880. else {
  18881. if ("development" !== 'production') {
  18882. assert(!this._progress || this._count);
  18883. }
  18884. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18885. } // Note: Stubs, that its host overall task let it has progress, has progress.
  18886. // If no progress, pass index from upstream to downstream each time plan called.
  18887. if (this._progress) {
  18888. var start = this._dueIndex;
  18889. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  18890. if (!skip && (forceFirstProgress || start < end)) {
  18891. var progress = this._progress;
  18892. if (isArray(progress)) {
  18893. for (var i = 0; i < progress.length; i++) {
  18894. this._doProgress(progress[i], start, end, modBy, modDataCount);
  18895. }
  18896. } else {
  18897. this._doProgress(progress, start, end, modBy, modDataCount);
  18898. }
  18899. }
  18900. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  18901. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  18902. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  18903. if ("development" !== 'production') {
  18904. // ??? Can not rollback.
  18905. assert(outputDueEnd >= this._outputDueEnd);
  18906. }
  18907. this._outputDueEnd = outputDueEnd;
  18908. } else {
  18909. // (1) Some overall task has no progress.
  18910. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  18911. // This should always be performed so it can be passed to downstream.
  18912. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  18913. }
  18914. return this.unfinished();
  18915. };
  18916. Task.prototype.dirty = function () {
  18917. this._dirty = true;
  18918. this._onDirty && this._onDirty(this.context);
  18919. };
  18920. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  18921. iterator.reset(start, end, modBy, modDataCount);
  18922. this._callingProgress = progress;
  18923. this._callingProgress({
  18924. start: start,
  18925. end: end,
  18926. count: end - start,
  18927. next: iterator.next
  18928. }, this.context);
  18929. };
  18930. Task.prototype._doReset = function (skip) {
  18931. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  18932. this._settedOutputEnd = null;
  18933. var progress;
  18934. var forceFirstProgress;
  18935. if (!skip && this._reset) {
  18936. progress = this._reset(this.context);
  18937. if (progress && progress.progress) {
  18938. forceFirstProgress = progress.forceFirstProgress;
  18939. progress = progress.progress;
  18940. } // To simplify no progress checking, array must has item.
  18941. if (isArray(progress) && !progress.length) {
  18942. progress = null;
  18943. }
  18944. }
  18945. this._progress = progress;
  18946. this._modBy = this._modDataCount = null;
  18947. var downstream = this._downstream;
  18948. downstream && downstream.dirty();
  18949. return forceFirstProgress;
  18950. };
  18951. Task.prototype.unfinished = function () {
  18952. return this._progress && this._dueIndex < this._dueEnd;
  18953. };
  18954. /**
  18955. * @param downTask The downstream task.
  18956. * @return The downstream task.
  18957. */
  18958. Task.prototype.pipe = function (downTask) {
  18959. if ("development" !== 'production') {
  18960. assert(downTask && !downTask._disposed && downTask !== this);
  18961. } // If already downstream, do not dirty downTask.
  18962. if (this._downstream !== downTask || this._dirty) {
  18963. this._downstream = downTask;
  18964. downTask._upstream = this;
  18965. downTask.dirty();
  18966. }
  18967. };
  18968. Task.prototype.dispose = function () {
  18969. if (this._disposed) {
  18970. return;
  18971. }
  18972. this._upstream && (this._upstream._downstream = null);
  18973. this._downstream && (this._downstream._upstream = null);
  18974. this._dirty = false;
  18975. this._disposed = true;
  18976. };
  18977. Task.prototype.getUpstream = function () {
  18978. return this._upstream;
  18979. };
  18980. Task.prototype.getDownstream = function () {
  18981. return this._downstream;
  18982. };
  18983. Task.prototype.setOutputEnd = function (end) {
  18984. // This only happend in dataTask, dataZoom, map, currently.
  18985. // where dataZoom do not set end each time, but only set
  18986. // when reset. So we should record the setted end, in case
  18987. // that the stub of dataZoom perform again and earse the
  18988. // setted end by upstream.
  18989. this._outputDueEnd = this._settedOutputEnd = end;
  18990. };
  18991. return Task;
  18992. }();
  18993. var iterator = function () {
  18994. var end;
  18995. var current;
  18996. var modBy;
  18997. var modDataCount;
  18998. var winCount;
  18999. var it = {
  19000. reset: function (s, e, sStep, sCount) {
  19001. current = s;
  19002. end = e;
  19003. modBy = sStep;
  19004. modDataCount = sCount;
  19005. winCount = Math.ceil(modDataCount / modBy);
  19006. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19007. }
  19008. };
  19009. return it;
  19010. function sequentialNext() {
  19011. return current < end ? current++ : null;
  19012. }
  19013. function modNext() {
  19014. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19015. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19016. // Use normal linear rendering mode.
  19017. : current;
  19018. current++;
  19019. return result;
  19020. }
  19021. }(); ///////////////////////////////////////////////////////////
  19022. // For stream debug (Should be commented out after used!)
  19023. // @usage: printTask(this, 'begin');
  19024. // @usage: printTask(this, null, {someExtraProp});
  19025. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19026. //
  19027. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19028. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19029. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19030. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19031. // let props = [];
  19032. // if (task.__pipeline) {
  19033. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19034. // props.push({text: '__idxInPipeline/total', value: val});
  19035. // } else {
  19036. // let stubCount = 0;
  19037. // task.agentStubMap.each(() => stubCount++);
  19038. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19039. // }
  19040. // props.push({text: 'uid', value: task.uidDebug});
  19041. // if (task.__pipeline) {
  19042. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19043. // task.agent && props.push(
  19044. // {text: 'stubFor', value: task.agent.uidDebug}
  19045. // );
  19046. // }
  19047. // props.push(
  19048. // {text: 'dirty', value: task._dirty},
  19049. // {text: 'dueIndex', value: task._dueIndex},
  19050. // {text: 'dueEnd', value: task._dueEnd},
  19051. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19052. // );
  19053. // if (extra) {
  19054. // Object.keys(extra).forEach(key => {
  19055. // props.push({text: key, value: extra[key]});
  19056. // });
  19057. // }
  19058. // let args = ['color: blue'];
  19059. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19060. // args.push('color: green', 'color: red'),
  19061. // `${item.text}: %c${item.value}`
  19062. // )).join('%c, ');
  19063. // console.log.apply(console, [msg].concat(args));
  19064. // // console.log(this);
  19065. // };
  19066. // window.printPipeline = function (task: any, prefix: string) {
  19067. // const pipeline = task.__pipeline;
  19068. // let currTask = pipeline.head;
  19069. // while (currTask) {
  19070. // window.printTask(currTask, prefix);
  19071. // currTask = currTask._downstream;
  19072. // }
  19073. // };
  19074. // window.showChain = function (chainHeadTask) {
  19075. // var chain = [];
  19076. // var task = chainHeadTask;
  19077. // while (task) {
  19078. // chain.push({
  19079. // task: task,
  19080. // up: task._upstream,
  19081. // down: task._downstream,
  19082. // idxInPipeline: task.__idxInPipeline
  19083. // });
  19084. // task = task._downstream;
  19085. // }
  19086. // return chain;
  19087. // };
  19088. // window.findTaskInChain = function (task, chainHeadTask) {
  19089. // let chain = window.showChain(chainHeadTask);
  19090. // let result = [];
  19091. // for (let i = 0; i < chain.length; i++) {
  19092. // let chainItem = chain[i];
  19093. // if (chainItem.task === task) {
  19094. // result.push(i);
  19095. // }
  19096. // }
  19097. // return result;
  19098. // };
  19099. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19100. // let chainA = window.showChain(chainHeadTaskA);
  19101. // for (let i = 0; i < chainA.length; i++) {
  19102. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19103. // }
  19104. // };
  19105. /**
  19106. * Convert raw the value in to inner value in List.
  19107. *
  19108. * [Performance sensitive]
  19109. *
  19110. * [Caution]: this is the key logic of user value parser.
  19111. * For backward compatibiliy, do not modify it until have to!
  19112. */
  19113. function parseDataValue(value, // For high performance, do not omit the second param.
  19114. opt) {
  19115. // Performance sensitive.
  19116. var dimType = opt && opt.type;
  19117. if (dimType === 'ordinal') {
  19118. // If given value is a category string
  19119. var ordinalMeta = opt && opt.ordinalMeta;
  19120. return ordinalMeta ? ordinalMeta.parseAndCollect(value) : value;
  19121. }
  19122. if (dimType === 'time' // spead up when using timestamp
  19123. && typeof value !== 'number' && value != null && value !== '-') {
  19124. value = +parseDate(value);
  19125. } // dimType defaults 'number'.
  19126. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19127. // parse to NaN.
  19128. // number-like string (like ' 123 ') can be converted to a number.
  19129. // where null/undefined or other string will be converted to NaN.
  19130. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19131. // If object, also parse to NaN
  19132. : +value;
  19133. }
  19134. var valueParserMap = createHashMap({
  19135. 'number': function (val) {
  19136. // Do not use `numericToNumber` here. We have by defualt `numericToNumber`.
  19137. // Here the number parser can have loose rule:
  19138. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19139. return parseFloat(val);
  19140. },
  19141. 'time': function (val) {
  19142. // return timestamp.
  19143. return +parseDate(val);
  19144. },
  19145. 'trim': function (val) {
  19146. return typeof val === 'string' ? trim(val) : val;
  19147. }
  19148. });
  19149. var SortOrderComparator =
  19150. /** @class */
  19151. function () {
  19152. /**
  19153. * @param order by defualt: 'asc'
  19154. * @param incomparable by defualt: Always on the tail.
  19155. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19156. * See the definition of "incomparable" in [SORT_COMPARISON_RULE]
  19157. */
  19158. function SortOrderComparator(order, incomparable) {
  19159. var isDesc = order === 'desc';
  19160. this._resultLT = isDesc ? 1 : -1;
  19161. if (incomparable == null) {
  19162. incomparable = isDesc ? 'min' : 'max';
  19163. }
  19164. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  19165. } // See [SORT_COMPARISON_RULE].
  19166. // Performance sensitive.
  19167. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  19168. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19169. var lvalTypeof = typeof lval;
  19170. var rvalTypeof = typeof rval;
  19171. var lvalFloat = lvalTypeof === 'number' ? lval : numericToNumber(lval);
  19172. var rvalFloat = rvalTypeof === 'number' ? rval : numericToNumber(rval);
  19173. var lvalNotNumeric = isNaN(lvalFloat);
  19174. var rvalNotNumeric = isNaN(rvalFloat);
  19175. if (lvalNotNumeric) {
  19176. lvalFloat = this._incomparable;
  19177. }
  19178. if (rvalNotNumeric) {
  19179. rvalFloat = this._incomparable;
  19180. }
  19181. if (lvalNotNumeric && rvalNotNumeric) {
  19182. var lvalIsStr = lvalTypeof === 'string';
  19183. var rvalIsStr = rvalTypeof === 'string';
  19184. if (lvalIsStr) {
  19185. lvalFloat = rvalIsStr ? lval : 0;
  19186. }
  19187. if (rvalIsStr) {
  19188. rvalFloat = lvalIsStr ? rval : 0;
  19189. }
  19190. }
  19191. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  19192. };
  19193. return SortOrderComparator;
  19194. }();
  19195. /**
  19196. * TODO: disable writable.
  19197. * This structure will be exposed to users.
  19198. */
  19199. var ExternalSource =
  19200. /** @class */
  19201. function () {
  19202. function ExternalSource() {}
  19203. ExternalSource.prototype.getRawData = function () {
  19204. // Only built-in transform available.
  19205. throw new Error('not supported');
  19206. };
  19207. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  19208. // Only built-in transform available.
  19209. throw new Error('not supported');
  19210. };
  19211. ExternalSource.prototype.cloneRawData = function () {
  19212. return;
  19213. };
  19214. /**
  19215. * @return If dimension not found, return null/undefined.
  19216. */
  19217. ExternalSource.prototype.getDimensionInfo = function (dim) {
  19218. return;
  19219. };
  19220. /**
  19221. * dimensions defined if and only if either:
  19222. * (a) dataset.dimensions are declared.
  19223. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  19224. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  19225. * the defined dimensions.
  19226. * Otherwise, `dimensionInfoAll` is determined by data columns.
  19227. * @return Always return an array (even empty array).
  19228. */
  19229. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  19230. return;
  19231. };
  19232. ExternalSource.prototype.count = function () {
  19233. return;
  19234. };
  19235. /**
  19236. * Only support by dimension index.
  19237. * No need to support by dimension name in transform function,
  19238. * becuase transform function is not case-specific, no need to use name literally.
  19239. */
  19240. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  19241. return;
  19242. };
  19243. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  19244. return;
  19245. };
  19246. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  19247. return parseDataValue(rawVal, dimInfo);
  19248. };
  19249. return ExternalSource;
  19250. }();
  19251. function createExternalSource(internalSource, externalTransform) {
  19252. var extSource = new ExternalSource();
  19253. var data = internalSource.data;
  19254. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  19255. var sourceHeaderCount = internalSource.startIndex;
  19256. var errMsg = '';
  19257. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  19258. // For the logic simplicity in transformer, only 'culumn' is
  19259. // supported in data transform. Otherwise, the `dimensionsDefine`
  19260. // might be detected by 'row', which probably confuses users.
  19261. if ("development" !== 'production') {
  19262. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  19263. }
  19264. throwError(errMsg);
  19265. } // [MEMO]
  19266. // Create a new dimensions structure for exposing.
  19267. // Do not expose all dimension info to users directly.
  19268. // Becuase the dimension is probably auto detected from data and not might reliable.
  19269. // Should not lead the transformers to think that is relialbe and return it.
  19270. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19271. var dimensions = [];
  19272. var dimsByName = {};
  19273. var dimsDef = internalSource.dimensionsDefine;
  19274. if (dimsDef) {
  19275. each(dimsDef, function (dimDef, idx) {
  19276. var name = dimDef.name;
  19277. var dimDefExt = {
  19278. index: idx,
  19279. name: name,
  19280. displayName: dimDef.displayName
  19281. };
  19282. dimensions.push(dimDefExt); // Users probably not sepcify dimension name. For simplicity, data transform
  19283. // do not generate dimension name.
  19284. if (name != null) {
  19285. // Dimension name should not be duplicated.
  19286. // For simplicity, data transform forbid name duplication, do not generate
  19287. // new name like module `completeDimensions.ts` did, but just tell users.
  19288. var errMsg_1 = '';
  19289. if (hasOwn(dimsByName, name)) {
  19290. if ("development" !== 'production') {
  19291. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  19292. }
  19293. throwError(errMsg_1);
  19294. }
  19295. dimsByName[name] = dimDefExt;
  19296. }
  19297. });
  19298. } // If dimension definitions are not defined and can not be detected.
  19299. // e.g., pure data `[[11, 22], ...]`.
  19300. else {
  19301. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  19302. // Do not generete name or anything others. The consequence process in
  19303. // `transform` or `series` probably have there own name generation strategry.
  19304. dimensions.push({
  19305. index: i
  19306. });
  19307. }
  19308. } // Implement public methods:
  19309. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19310. if (externalTransform.__isBuiltIn) {
  19311. extSource.getRawDataItem = function (dataIndex) {
  19312. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19313. };
  19314. extSource.getRawData = bind(getRawData, null, internalSource);
  19315. }
  19316. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  19317. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19318. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  19319. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  19320. extSource.retrieveValue = function (dataIndex, dimIndex) {
  19321. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19322. return retrieveValueFromItem(rawItem, dimIndex);
  19323. };
  19324. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  19325. if (dataItem == null) {
  19326. return;
  19327. }
  19328. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  19329. if (dimDef) {
  19330. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  19331. }
  19332. };
  19333. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  19334. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  19335. return extSource;
  19336. }
  19337. function getRawData(upstream) {
  19338. var sourceFormat = upstream.sourceFormat;
  19339. if (!isSupportedSourceFormat(sourceFormat)) {
  19340. var errMsg = '';
  19341. if ("development" !== 'production') {
  19342. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  19343. }
  19344. throwError(errMsg);
  19345. }
  19346. return upstream.data;
  19347. }
  19348. function cloneRawData(upstream) {
  19349. var sourceFormat = upstream.sourceFormat;
  19350. var data = upstream.data;
  19351. if (!isSupportedSourceFormat(sourceFormat)) {
  19352. var errMsg = '';
  19353. if ("development" !== 'production') {
  19354. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  19355. }
  19356. throwError(errMsg);
  19357. }
  19358. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19359. var result = [];
  19360. for (var i = 0, len = data.length; i < len; i++) {
  19361. // Not strictly clone for performance
  19362. result.push(data[i].slice());
  19363. }
  19364. return result;
  19365. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19366. var result = [];
  19367. for (var i = 0, len = data.length; i < len; i++) {
  19368. // Not strictly clone for performance
  19369. result.push(extend({}, data[i]));
  19370. }
  19371. return result;
  19372. }
  19373. }
  19374. function getDimensionInfo(dimensions, dimsByName, dim) {
  19375. if (dim == null) {
  19376. return;
  19377. } // Keep the same logic as `List::getDimension` did.
  19378. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  19379. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  19380. return dimensions[dim];
  19381. } else if (hasOwn(dimsByName, dim)) {
  19382. return dimsByName[dim];
  19383. }
  19384. }
  19385. function cloneAllDimensionInfo(dimensions) {
  19386. return clone(dimensions);
  19387. }
  19388. var externalTransformMap = createHashMap();
  19389. function registerExternalTransform(externalTransform) {
  19390. externalTransform = clone(externalTransform);
  19391. var type = externalTransform.type;
  19392. var errMsg = '';
  19393. if (!type) {
  19394. if ("development" !== 'production') {
  19395. errMsg = 'Must have a `type` when `registerTransform`.';
  19396. }
  19397. throwError(errMsg);
  19398. }
  19399. var typeParsed = type.split(':');
  19400. if (typeParsed.length !== 2) {
  19401. if ("development" !== 'production') {
  19402. errMsg = 'Name must include namespace like "ns:regression".';
  19403. }
  19404. throwError(errMsg);
  19405. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  19406. // be called directly via 'xxx' rather than 'echarts:xxx'.
  19407. var isBuiltIn = false;
  19408. if (typeParsed[0] === 'echarts') {
  19409. type = typeParsed[1];
  19410. isBuiltIn = true;
  19411. }
  19412. externalTransform.__isBuiltIn = isBuiltIn;
  19413. externalTransformMap.set(type, externalTransform);
  19414. }
  19415. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  19416. var pipedTransOption = normalizeToArray(rawTransOption);
  19417. var pipeLen = pipedTransOption.length;
  19418. var errMsg = '';
  19419. if (!pipeLen) {
  19420. if ("development" !== 'production') {
  19421. errMsg = 'If `transform` declared, it should at least contain one transform.';
  19422. }
  19423. throwError(errMsg);
  19424. }
  19425. for (var i = 0, len = pipeLen; i < len; i++) {
  19426. var transOption = pipedTransOption[i];
  19427. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  19428. // piped transform only support single output, except the last one.
  19429. if (i !== len - 1) {
  19430. sourceList.length = Math.max(sourceList.length, 1);
  19431. }
  19432. }
  19433. return sourceList;
  19434. }
  19435. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  19436. pipeIndex) {
  19437. var errMsg = '';
  19438. if (!upSourceList.length) {
  19439. if ("development" !== 'production') {
  19440. errMsg = 'Must have at least one upstream dataset.';
  19441. }
  19442. throwError(errMsg);
  19443. }
  19444. if (!isObject(transOption)) {
  19445. if ("development" !== 'production') {
  19446. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  19447. }
  19448. throwError(errMsg);
  19449. }
  19450. var transType = transOption.type;
  19451. var externalTransform = externalTransformMap.get(transType);
  19452. if (!externalTransform) {
  19453. if ("development" !== 'production') {
  19454. errMsg = 'Can not find transform on type "' + transType + '".';
  19455. }
  19456. throwError(errMsg);
  19457. } // Prepare source
  19458. var extUpSourceList = map(upSourceList, function (upSource) {
  19459. return createExternalSource(upSource, externalTransform);
  19460. });
  19461. var resultList = normalizeToArray(externalTransform.transform({
  19462. upstream: extUpSourceList[0],
  19463. upstreamList: extUpSourceList,
  19464. config: clone(transOption.config)
  19465. }));
  19466. if ("development" !== 'production') {
  19467. if (transOption.print) {
  19468. var printStrArr = map(resultList, function (extSource) {
  19469. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  19470. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  19471. }).join('\n');
  19472. consoleLog(printStrArr);
  19473. }
  19474. }
  19475. return map(resultList, function (result, resultIndex) {
  19476. var errMsg = '';
  19477. if (!isObject(result)) {
  19478. if ("development" !== 'production') {
  19479. errMsg = 'A transform should not return some empty results.';
  19480. }
  19481. throwError(errMsg);
  19482. }
  19483. if (!result.data) {
  19484. if ("development" !== 'production') {
  19485. errMsg = 'Transform result data should be not be null or undefined';
  19486. }
  19487. throwError(errMsg);
  19488. }
  19489. var sourceFormat = detectSourceFormat(result.data);
  19490. if (!isSupportedSourceFormat(sourceFormat)) {
  19491. if ("development" !== 'production') {
  19492. errMsg = 'Transform result data should be array rows or object rows.';
  19493. }
  19494. throwError(errMsg);
  19495. }
  19496. var resultMetaRawOption;
  19497. var firstUpSource = upSourceList[0];
  19498. /**
  19499. * Intuitively, the end users known the content of the original `dataset.source`,
  19500. * calucating the transform result in mind.
  19501. * Suppose the original `dataset.source` is:
  19502. * ```js
  19503. * [
  19504. * ['product', '2012', '2013', '2014', '2015'],
  19505. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  19506. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  19507. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  19508. * ]
  19509. * ```
  19510. * The dimension info have to be detected from the source data.
  19511. * Some of the transformers (like filter, sort) will follow the dimension info
  19512. * of upstream, while others use new dimensions (like aggregate).
  19513. * Transformer can output a field `dimensions` to define the its own output dimensions.
  19514. * We also allow transformers to ignore the output `dimensions` field, and
  19515. * inherit the upstream dimensions definition. It can reduce the burden of handling
  19516. * dimensions in transformers.
  19517. *
  19518. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19519. */
  19520. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  19521. // dimensions definitions. We do not inherit anything from upstream.
  19522. && !result.dimensions) {
  19523. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result becuase:
  19524. // (1) The returned data always does not contain header line and can not be used
  19525. // as dimension-detection. In this case we can not use "detected dimensions" of
  19526. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  19527. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  19528. // So the original detected header should be add to the result, otherwise they can not be read.
  19529. if (startIndex) {
  19530. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  19531. }
  19532. resultMetaRawOption = {
  19533. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19534. sourceHeader: startIndex,
  19535. dimensions: firstUpSource.metaRawOption.dimensions
  19536. };
  19537. } else {
  19538. resultMetaRawOption = {
  19539. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19540. sourceHeader: 0,
  19541. dimensions: result.dimensions
  19542. };
  19543. }
  19544. return createSource(result.data, resultMetaRawOption, null, null);
  19545. });
  19546. }
  19547. function isSupportedSourceFormat(sourceFormat) {
  19548. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  19549. }
  19550. /**
  19551. * [REQUIREMENT_MEMO]:
  19552. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  19553. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  19554. * `root-dataset`. Them on `series` has higher priority.
  19555. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  19556. * confuse users: whether those props indicate how to visit the upstream source or visit
  19557. * the transform result source, and some transforms has nothing to do with these props,
  19558. * and some transforms might have multiple upstream.
  19559. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  19560. * declared in `root-dataset`.
  19561. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  19562. * That is for reducing complexity in transfroms.
  19563. * PENDING: Whether to provide transposition transform?
  19564. *
  19565. * [IMPLEMENTAION_MEMO]:
  19566. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  19567. * They will not be calculated until `source` is about to be visited (to prevent from
  19568. * duplicate calcuation). `source` is visited only in series and input to transforms.
  19569. *
  19570. * [DIMENSION_INHERIT_RULE]:
  19571. * By default the dimensions are inherited from ancestors, unless a transform return
  19572. * a new dimensions definition.
  19573. * Consider the case:
  19574. * ```js
  19575. * dataset: [{
  19576. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  19577. * }, {
  19578. * transform: { type: 'filter', ... }
  19579. * }]
  19580. * dataset: [{
  19581. * dimension: ['Product', 'Sales', 'Prise'],
  19582. * source: [ ['Cookies', 321, 44.21], ...]
  19583. * }, {
  19584. * transform: { type: 'filter', ... }
  19585. * }]
  19586. * ```
  19587. * The two types of option should have the same behavior after transform.
  19588. *
  19589. *
  19590. * [SCENARIO]:
  19591. * (1) Provide source data directly:
  19592. * ```js
  19593. * series: {
  19594. * encode: {...},
  19595. * dimensions: [...]
  19596. * seriesLayoutBy: 'row',
  19597. * data: [[...]]
  19598. * }
  19599. * ```
  19600. * (2) Series refer to dataset.
  19601. * ```js
  19602. * series: [{
  19603. * encode: {...}
  19604. * // Ignore datasetIndex means `datasetIndex: 0`
  19605. * // and the dimensions defination in dataset is used
  19606. * }, {
  19607. * encode: {...},
  19608. * seriesLayoutBy: 'column',
  19609. * datasetIndex: 1
  19610. * }]
  19611. * ```
  19612. * (3) dataset transform
  19613. * ```js
  19614. * dataset: [{
  19615. * source: [...]
  19616. * }, {
  19617. * source: [...]
  19618. * }, {
  19619. * // By default from 0.
  19620. * transform: { type: 'filter', config: {...} }
  19621. * }, {
  19622. * // Piped.
  19623. * transform: [
  19624. * { type: 'filter', config: {...} },
  19625. * { type: 'sort', config: {...} }
  19626. * ]
  19627. * }, {
  19628. * id: 'regressionData',
  19629. * fromDatasetIndex: 1,
  19630. * // Third-party transform
  19631. * transform: { type: 'ecStat:regression', config: {...} }
  19632. * }, {
  19633. * // retrieve the extra result.
  19634. * id: 'regressionFormula',
  19635. * fromDatasetId: 'regressionData',
  19636. * fromTransformResult: 1
  19637. * }]
  19638. * ```
  19639. */
  19640. var SourceManager =
  19641. /** @class */
  19642. function () {
  19643. function SourceManager(sourceHost) {
  19644. // Cached source. Do not repeat calculating if not dirty.
  19645. this._sourceList = []; // version sign of each upstream source manager.
  19646. this._upstreamSignList = [];
  19647. this._versionSignBase = 0;
  19648. this._sourceHost = sourceHost;
  19649. }
  19650. /**
  19651. * Mark dirty.
  19652. */
  19653. SourceManager.prototype.dirty = function () {
  19654. this._setLocalSource([], []);
  19655. };
  19656. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  19657. this._sourceList = sourceList;
  19658. this._upstreamSignList = upstreamSignList;
  19659. this._versionSignBase++;
  19660. if (this._versionSignBase > 9e10) {
  19661. this._versionSignBase = 0;
  19662. }
  19663. };
  19664. /**
  19665. * For detecting whether the upstream source is dirty, so that
  19666. * the local cached source (in `_sourceList`) should be discarded.
  19667. */
  19668. SourceManager.prototype._getVersionSign = function () {
  19669. return this._sourceHost.uid + '_' + this._versionSignBase;
  19670. };
  19671. /**
  19672. * Always return a source instance. Otherwise throw error.
  19673. */
  19674. SourceManager.prototype.prepareSource = function () {
  19675. // For the case that call `setOption` multiple time but no data changed,
  19676. // cache the result source to prevent from repeating transform.
  19677. if (this._isDirty()) {
  19678. this._createSource();
  19679. }
  19680. };
  19681. SourceManager.prototype._createSource = function () {
  19682. this._setLocalSource([], []);
  19683. var sourceHost = this._sourceHost;
  19684. var upSourceMgrList = this._getUpstreamSourceManagers();
  19685. var hasUpstream = !!upSourceMgrList.length;
  19686. var resultSourceList;
  19687. var upstreamSignList;
  19688. if (isSeries(sourceHost)) {
  19689. var seriesModel = sourceHost;
  19690. var data = void 0;
  19691. var sourceFormat = void 0;
  19692. var upSource = void 0; // Has upstream dataset
  19693. if (hasUpstream) {
  19694. var upSourceMgr = upSourceMgrList[0];
  19695. upSourceMgr.prepareSource();
  19696. upSource = upSourceMgr.getSource();
  19697. data = upSource.data;
  19698. sourceFormat = upSource.sourceFormat;
  19699. upstreamSignList = [upSourceMgr._getVersionSign()];
  19700. } // Series data is from own.
  19701. else {
  19702. data = seriesModel.get('data', true);
  19703. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  19704. upstreamSignList = [];
  19705. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  19706. var newMetaRawOption = this._getSourceMetaRawOption();
  19707. var upMetaRawOption = upSource ? upSource.metaRawOption : null;
  19708. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption ? upMetaRawOption.seriesLayoutBy : null);
  19709. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption ? upMetaRawOption.sourceHeader : null); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  19710. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  19711. // but series need `seriesLayoutBy: 'row'`.
  19712. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption ? upMetaRawOption.dimensions : null);
  19713. resultSourceList = [createSource(data, {
  19714. seriesLayoutBy: seriesLayoutBy,
  19715. sourceHeader: sourceHeader,
  19716. dimensions: dimensions
  19717. }, sourceFormat, seriesModel.get('encode', true))];
  19718. } else {
  19719. var datasetModel = sourceHost; // Has upstream dataset.
  19720. if (hasUpstream) {
  19721. var result = this._applyTransform(upSourceMgrList);
  19722. resultSourceList = result.sourceList;
  19723. upstreamSignList = result.upstreamSignList;
  19724. } // Is root dataset.
  19725. else {
  19726. var sourceData = datasetModel.get('source', true);
  19727. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null, // Note: dataset option does not have `encode`.
  19728. null)];
  19729. upstreamSignList = [];
  19730. }
  19731. }
  19732. if ("development" !== 'production') {
  19733. assert(resultSourceList && upstreamSignList);
  19734. }
  19735. this._setLocalSource(resultSourceList, upstreamSignList);
  19736. };
  19737. SourceManager.prototype._applyTransform = function (upMgrList) {
  19738. var datasetModel = this._sourceHost;
  19739. var transformOption = datasetModel.get('transform', true);
  19740. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  19741. if ("development" !== 'production') {
  19742. assert(fromTransformResult != null || transformOption != null);
  19743. }
  19744. if (fromTransformResult != null) {
  19745. var errMsg = '';
  19746. if (upMgrList.length !== 1) {
  19747. if ("development" !== 'production') {
  19748. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  19749. }
  19750. doThrow(errMsg);
  19751. }
  19752. }
  19753. var sourceList;
  19754. var upSourceList = [];
  19755. var upstreamSignList = [];
  19756. each(upMgrList, function (upMgr) {
  19757. upMgr.prepareSource();
  19758. var upSource = upMgr.getSource(fromTransformResult || 0);
  19759. var errMsg = '';
  19760. if (fromTransformResult != null && !upSource) {
  19761. if ("development" !== 'production') {
  19762. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  19763. }
  19764. doThrow(errMsg);
  19765. }
  19766. upSourceList.push(upSource);
  19767. upstreamSignList.push(upMgr._getVersionSign());
  19768. });
  19769. if (transformOption) {
  19770. sourceList = applyDataTransform(transformOption, upSourceList, {
  19771. datasetIndex: datasetModel.componentIndex
  19772. });
  19773. } else if (fromTransformResult != null) {
  19774. sourceList = [cloneSourceShallow(upSourceList[0])];
  19775. }
  19776. return {
  19777. sourceList: sourceList,
  19778. upstreamSignList: upstreamSignList
  19779. };
  19780. };
  19781. SourceManager.prototype._isDirty = function () {
  19782. var sourceList = this._sourceList;
  19783. if (!sourceList.length) {
  19784. return true;
  19785. } // All sourceList is from the some upsteam.
  19786. var upSourceMgrList = this._getUpstreamSourceManagers();
  19787. for (var i = 0; i < upSourceMgrList.length; i++) {
  19788. var upSrcMgr = upSourceMgrList[i];
  19789. if ( // Consider the case that there is ancestor diry, call it recursively.
  19790. // The performance is probably not an issue because usually the chain is not long.
  19791. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  19792. return true;
  19793. }
  19794. }
  19795. };
  19796. /**
  19797. * @param sourceIndex By defualt 0, means "main source".
  19798. * Most cases there is only one source.
  19799. */
  19800. SourceManager.prototype.getSource = function (sourceIndex) {
  19801. return this._sourceList[sourceIndex || 0];
  19802. };
  19803. /**
  19804. * PEDING: Is it fast enough?
  19805. * If no upstream, return empty array.
  19806. */
  19807. SourceManager.prototype._getUpstreamSourceManagers = function () {
  19808. // Always get the relationship from the raw option.
  19809. // Do not cache the link of the dependency graph, so that
  19810. // no need to update them when change happen.
  19811. var sourceHost = this._sourceHost;
  19812. if (isSeries(sourceHost)) {
  19813. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  19814. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  19815. } else {
  19816. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  19817. return datasetModel.getSourceManager();
  19818. });
  19819. }
  19820. };
  19821. SourceManager.prototype._getSourceMetaRawOption = function () {
  19822. var sourceHost = this._sourceHost;
  19823. var seriesLayoutBy;
  19824. var sourceHeader;
  19825. var dimensions;
  19826. if (isSeries(sourceHost)) {
  19827. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  19828. sourceHeader = sourceHost.get('sourceHeader', true);
  19829. dimensions = sourceHost.get('dimensions', true);
  19830. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  19831. else if (!this._getUpstreamSourceManagers().length) {
  19832. var model = sourceHost;
  19833. seriesLayoutBy = model.get('seriesLayoutBy', true);
  19834. sourceHeader = model.get('sourceHeader', true);
  19835. dimensions = model.get('dimensions', true);
  19836. }
  19837. return {
  19838. seriesLayoutBy: seriesLayoutBy,
  19839. sourceHeader: sourceHeader,
  19840. dimensions: dimensions
  19841. };
  19842. };
  19843. return SourceManager;
  19844. }();
  19845. // disable the transform merge, but do not disable transfrom clone from rawOption.
  19846. function disableTransformOptionMerge(datasetModel) {
  19847. var transformOption = datasetModel.option.transform;
  19848. transformOption && setAsPrimitive(datasetModel.option.transform);
  19849. }
  19850. function isSeries(sourceHost) {
  19851. // Avoid circular dependency with Series.ts
  19852. return sourceHost.mainType === 'series';
  19853. }
  19854. function doThrow(errMsg) {
  19855. throw new Error(errMsg);
  19856. }
  19857. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  19858. function getTooltipTextStyle(textStyle, renderMode) {
  19859. var nameFontColor = textStyle.color || '#6e7079';
  19860. var nameFontSize = textStyle.fontSize || 12;
  19861. var nameFontWeight = textStyle.fontWeight || '400';
  19862. var valueFontColor = textStyle.color || '#464646';
  19863. var valueFontSize = textStyle.fontSize || 14;
  19864. var valueFontWeight = textStyle.fontWeight || '900';
  19865. if (renderMode === 'html') {
  19866. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  19867. return {
  19868. // eslint-disable-next-line max-len
  19869. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  19870. // eslint-disable-next-line max-len
  19871. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  19872. };
  19873. } else {
  19874. return {
  19875. nameStyle: {
  19876. fontSize: nameFontSize,
  19877. fill: nameFontColor,
  19878. fontWeight: nameFontWeight
  19879. },
  19880. valueStyle: {
  19881. fontSize: valueFontSize,
  19882. fill: valueFontColor,
  19883. fontWeight: valueFontWeight
  19884. }
  19885. };
  19886. }
  19887. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  19888. // (value from UI design)
  19889. var HTML_GAPS = [0, 10, 20, 30];
  19890. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  19891. function createTooltipMarkup(type, option) {
  19892. option.type = type;
  19893. return option;
  19894. }
  19895. function getBuilder(fragment) {
  19896. return hasOwn(builderMap, fragment.type) && builderMap[fragment.type];
  19897. }
  19898. var builderMap = {
  19899. /**
  19900. * A `section` block is like:
  19901. * ```
  19902. * header
  19903. * subBlock
  19904. * subBlock
  19905. * ...
  19906. * ```
  19907. */
  19908. section: {
  19909. planLayout: function (fragment) {
  19910. var subBlockLen = fragment.blocks.length;
  19911. var thisBlockHasInnerGap = subBlockLen > 1 || subBlockLen > 0 && !fragment.noHeader;
  19912. var thisGapLevelBetweenSubBlocks = 0;
  19913. each(fragment.blocks, function (subBlock) {
  19914. getBuilder(subBlock).planLayout(subBlock);
  19915. var subGapLevel = subBlock.__gapLevelBetweenSubBlocks; // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  19916. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  19917. if (subGapLevel >= thisGapLevelBetweenSubBlocks) {
  19918. thisGapLevelBetweenSubBlocks = subGapLevel + (thisBlockHasInnerGap && ( // 0 always can not be readable gap level.
  19919. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  19920. // look weird in case `multipleSeries`.
  19921. || subBlock.type === 'section' && !subBlock.noHeader) ? 1 : 0);
  19922. }
  19923. });
  19924. fragment.__gapLevelBetweenSubBlocks = thisGapLevelBetweenSubBlocks;
  19925. },
  19926. build: function (ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  19927. var noHeader = fragment.noHeader;
  19928. var gaps = getGap(fragment);
  19929. var subMarkupText = buildSubBlocks(ctx, fragment, noHeader ? topMarginForOuterGap : gaps.html, toolTipTextStyle);
  19930. if (noHeader) {
  19931. return subMarkupText;
  19932. }
  19933. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  19934. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  19935. if (ctx.renderMode === 'richText') {
  19936. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  19937. } else {
  19938. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  19939. }
  19940. }
  19941. },
  19942. /**
  19943. * A `nameValue` block is like:
  19944. * ```
  19945. * marker name value
  19946. * ```
  19947. */
  19948. nameValue: {
  19949. planLayout: function (fragment) {
  19950. fragment.__gapLevelBetweenSubBlocks = 0;
  19951. },
  19952. build: function (ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  19953. var renderMode = ctx.renderMode;
  19954. var noName = fragment.noName;
  19955. var noValue = fragment.noValue;
  19956. var noMarker = !fragment.markerType;
  19957. var name = fragment.name;
  19958. var value = fragment.value;
  19959. var useUTC = ctx.useUTC;
  19960. if (noName && noValue) {
  19961. return;
  19962. }
  19963. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  19964. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  19965. var valueTypeOption = fragment.valueType;
  19966. var readableValueList = noValue ? [] : isArray(value) ? map(value, function (val, idx) {
  19967. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  19968. }) : [makeValueReadable(value, isArray(valueTypeOption) ? valueTypeOption[0] : valueTypeOption, useUTC)];
  19969. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  19970. var valueCloseToMarker = !noMarker && noName;
  19971. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  19972. nameStyle = _a.nameStyle,
  19973. valueStyle = _a.valueStyle;
  19974. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  19975. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  19976. }
  19977. }
  19978. };
  19979. function buildSubBlocks(ctx, fragment, topMarginForOuterGap, tooltipTextStyle) {
  19980. var subMarkupTextList = [];
  19981. var subBlocks = fragment.blocks || [];
  19982. assert(!subBlocks || isArray(subBlocks));
  19983. subBlocks = subBlocks || [];
  19984. var orderMode = ctx.orderMode;
  19985. if (fragment.sortBlocks && orderMode) {
  19986. subBlocks = subBlocks.slice();
  19987. var orderMap = {
  19988. valueAsc: 'asc',
  19989. valueDesc: 'desc'
  19990. };
  19991. if (hasOwn(orderMap, orderMode)) {
  19992. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  19993. subBlocks.sort(function (a, b) {
  19994. return comparator_1.evaluate(a.sortParam, b.sortParam);
  19995. });
  19996. } // FIXME 'seriesDesc' necessary?
  19997. else if (orderMode === 'seriesDesc') {
  19998. subBlocks.reverse();
  19999. }
  20000. }
  20001. var gaps = getGap(fragment);
  20002. each(subBlocks, function (subBlock, idx) {
  20003. var subMarkupText = getBuilder(subBlock).build(ctx, subBlock, idx > 0 ? gaps.html : 0, tooltipTextStyle);
  20004. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  20005. });
  20006. if (!subMarkupTextList.length) {
  20007. return;
  20008. }
  20009. return ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), topMarginForOuterGap);
  20010. }
  20011. /**
  20012. * @return markupText. null/undefined means no content.
  20013. */
  20014. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  20015. if (!fragment) {
  20016. return;
  20017. }
  20018. var builder = getBuilder(fragment);
  20019. builder.planLayout(fragment);
  20020. var ctx = {
  20021. useUTC: useUTC,
  20022. renderMode: renderMode,
  20023. orderMode: orderMode,
  20024. markupStyleCreator: markupStyleCreator
  20025. };
  20026. return builder.build(ctx, fragment, 0, toolTipTextStyle);
  20027. }
  20028. function getGap(fragment) {
  20029. var gapLevelBetweenSubBlocks = fragment.__gapLevelBetweenSubBlocks;
  20030. return {
  20031. html: HTML_GAPS[gapLevelBetweenSubBlocks],
  20032. richText: RICH_TEXT_GAPS[gapLevelBetweenSubBlocks]
  20033. };
  20034. }
  20035. function wrapBlockHTML(encodedContent, topGap) {
  20036. var clearfix = '<div style="clear:both"></div>';
  20037. var marginCSS = "margin: " + topGap + "px 0 0";
  20038. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  20039. }
  20040. function wrapInlineNameHTML(name, leftHasMarker, style) {
  20041. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  20042. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  20043. }
  20044. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  20045. // Do not too close to marker, considering there are multiple values separated by spaces.
  20046. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  20047. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  20048. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  20049. + map(valueList, function (value) {
  20050. return encodeHTML(value);
  20051. }).join('&nbsp;&nbsp;') + '</span>';
  20052. }
  20053. function wrapInlineNameRichText(ctx, name, style) {
  20054. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  20055. }
  20056. function wrapInlineValueRichText(ctx, valueList, alignRight, valueCloseToMarker, style) {
  20057. var styles = [style];
  20058. var paddingLeft = valueCloseToMarker ? 10 : 20;
  20059. alignRight && styles.push({
  20060. padding: [0, 0, 0, paddingLeft],
  20061. align: 'right'
  20062. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  20063. return ctx.markupStyleCreator.wrapRichTextStyle(valueList.join(' '), styles);
  20064. }
  20065. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  20066. var style = series.getData().getItemVisual(dataIndex, 'style');
  20067. var color = style[series.visualDrawType];
  20068. return convertToColorString(color);
  20069. }
  20070. function getPaddingFromTooltipModel(model, renderMode) {
  20071. var padding = model.get('padding');
  20072. return padding != null ? padding // We give slightly different to look pretty.
  20073. : renderMode === 'richText' ? [8, 10] : 10;
  20074. }
  20075. /**
  20076. * The major feature is generate styles for `renderMode: 'richText'`.
  20077. * But it also serves `renderMode: 'html'` to provide
  20078. * "renderMode-independent" API.
  20079. */
  20080. var TooltipMarkupStyleCreator =
  20081. /** @class */
  20082. function () {
  20083. function TooltipMarkupStyleCreator() {
  20084. this.richTextStyles = {}; // Notice that "generate a style name" usuall happens repeatly when mouse moving and
  20085. // displaying a tooltip. So we put the `_nextStyleNameId` as a member of each creator
  20086. // rather than static shared by all creators (which will cause it increase to fast).
  20087. this._nextStyleNameId = getRandomIdBase();
  20088. }
  20089. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  20090. return '__EC_aUTo_' + this._nextStyleNameId++;
  20091. };
  20092. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  20093. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  20094. var marker = getTooltipMarker({
  20095. color: colorStr,
  20096. type: markerType,
  20097. renderMode: renderMode,
  20098. markerId: markerId
  20099. });
  20100. if (isString(marker)) {
  20101. return marker;
  20102. } else {
  20103. if ("development" !== 'production') {
  20104. assert(markerId);
  20105. }
  20106. this.richTextStyles[markerId] = marker.style;
  20107. return marker.content;
  20108. }
  20109. };
  20110. /**
  20111. * @usage
  20112. * ```ts
  20113. * const styledText = markupStyleCreator.wrapRichTextStyle([
  20114. * // The styles will be auto merged.
  20115. * {
  20116. * fontSize: 12,
  20117. * color: 'blue'
  20118. * },
  20119. * {
  20120. * padding: 20
  20121. * }
  20122. * ]);
  20123. * ```
  20124. */
  20125. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  20126. var finalStl = {};
  20127. if (isArray(styles)) {
  20128. each(styles, function (stl) {
  20129. return extend(finalStl, stl);
  20130. });
  20131. } else {
  20132. extend(finalStl, styles);
  20133. }
  20134. var styleName = this._generateStyleName();
  20135. this.richTextStyles[styleName] = finalStl;
  20136. return "{" + styleName + "|" + text + "}";
  20137. };
  20138. return TooltipMarkupStyleCreator;
  20139. }();
  20140. function defaultSeriesFormatTooltip(opt) {
  20141. var series = opt.series;
  20142. var dataIndex = opt.dataIndex;
  20143. var multipleSeries = opt.multipleSeries;
  20144. var data = series.getData();
  20145. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  20146. var tooltipDimLen = tooltipDims.length;
  20147. var value = series.getRawValue(dataIndex);
  20148. var isValueArr = isArray(value);
  20149. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  20150. var inlineValue;
  20151. var inlineValueType;
  20152. var subBlocks;
  20153. var sortParam;
  20154. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  20155. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  20156. inlineValue = formatArrResult.inlineValues;
  20157. inlineValueType = formatArrResult.inlineValueTypes;
  20158. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  20159. sortParam = formatArrResult.inlineValues[0];
  20160. } else if (tooltipDimLen) {
  20161. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  20162. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  20163. inlineValueType = dimInfo.type;
  20164. } else {
  20165. sortParam = inlineValue = isValueArr ? value[0] : value;
  20166. } // Do not show generated series name. It might not be readable.
  20167. var seriesNameSpecified = isNameSpecified(series);
  20168. var seriesName = seriesNameSpecified && series.name || '';
  20169. var itemName = data.getName(dataIndex);
  20170. var inlineName = multipleSeries ? seriesName : itemName;
  20171. return createTooltipMarkup('section', {
  20172. header: seriesName,
  20173. // When series name not specified, do not show a header line with only '-'.
  20174. // This case alway happen in tooltip.trigger: 'item'.
  20175. noHeader: multipleSeries || !seriesNameSpecified,
  20176. sortParam: sortParam,
  20177. blocks: [createTooltipMarkup('nameValue', {
  20178. markerType: 'item',
  20179. markerColor: markerColor,
  20180. // Do not mix display seriesName and itemName in one tooltip,
  20181. // which might confuses users.
  20182. name: inlineName,
  20183. // name dimension might be auto assigned, where the name might
  20184. // be not readable. So we check trim here.
  20185. noName: !trim(inlineName),
  20186. value: inlineValue,
  20187. valueType: inlineValueType
  20188. })].concat(subBlocks || [])
  20189. });
  20190. }
  20191. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  20192. // check: category-no-encode-has-axis-data in dataset.html
  20193. var data = series.getData();
  20194. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  20195. var dimItem = data.getDimensionInfo(idx);
  20196. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20197. }, false);
  20198. var inlineValues = [];
  20199. var inlineValueTypes = [];
  20200. var blocks = [];
  20201. tooltipDims.length ? each(tooltipDims, function (dim) {
  20202. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20203. }) // By default, all dims is used on tooltip.
  20204. : each(value, setEachItem);
  20205. function setEachItem(val, dim) {
  20206. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  20207. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20208. return;
  20209. }
  20210. if (isValueMultipleLine) {
  20211. blocks.push(createTooltipMarkup('nameValue', {
  20212. markerType: 'subItem',
  20213. markerColor: colorStr,
  20214. name: dimInfo.displayName,
  20215. value: val,
  20216. valueType: dimInfo.type
  20217. }));
  20218. } else {
  20219. inlineValues.push(val);
  20220. inlineValueTypes.push(dimInfo.type);
  20221. }
  20222. }
  20223. return {
  20224. inlineValues: inlineValues,
  20225. inlineValueTypes: inlineValueTypes,
  20226. blocks: blocks
  20227. };
  20228. }
  20229. var inner$1 = makeInner();
  20230. function getSelectionKey(data, dataIndex) {
  20231. return data.getName(dataIndex) || data.getId(dataIndex);
  20232. }
  20233. var SeriesModel =
  20234. /** @class */
  20235. function (_super) {
  20236. __extends(SeriesModel, _super);
  20237. function SeriesModel() {
  20238. // [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`,
  20239. // the class members must not be initialized in constructor or declaration place.
  20240. // Otherwise there is bad case:
  20241. // class A {xxx = 1;}
  20242. // enableClassExtend(A);
  20243. // class B extends A {}
  20244. // var C = B.extend({xxx: 5});
  20245. // var c = new C();
  20246. // console.log(c.xxx); // expect 5 but always 1.
  20247. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  20248. // Props about data selection
  20249. // ---------------------------------------
  20250. _this._selectedDataIndicesMap = {};
  20251. return _this;
  20252. }
  20253. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  20254. this.seriesIndex = this.componentIndex;
  20255. this.dataTask = createTask({
  20256. count: dataTaskCount,
  20257. reset: dataTaskReset
  20258. });
  20259. this.dataTask.context = {
  20260. model: this
  20261. };
  20262. this.mergeDefaultAndTheme(option, ecModel);
  20263. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  20264. sourceManager.prepareSource();
  20265. var data = this.getInitialData(option, ecModel);
  20266. wrapData(data, this);
  20267. this.dataTask.context.data = data;
  20268. if ("development" !== 'production') {
  20269. assert(data, 'getInitialData returned invalid data.');
  20270. }
  20271. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  20272. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20273. // cause data.graph.data !== data when using
  20274. // module:echarts/data/Graph or module:echarts/data/Tree.
  20275. // See module:echarts/data/helper/linkList
  20276. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20277. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20278. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20279. // Call `seriesModel.getRawData()` instead.
  20280. // this.restoreData();
  20281. autoSeriesName(this);
  20282. this._initSelectedMapFromData(data);
  20283. };
  20284. /**
  20285. * Util for merge default and theme to option
  20286. */
  20287. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  20288. var layoutMode = fetchLayoutMode(this);
  20289. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  20290. // But if name duplicate between series subType
  20291. // (for example: parallel) add component mainType,
  20292. // add suffix 'Series'.
  20293. var themeSubType = this.subType;
  20294. if (ComponentModel.hasClass(themeSubType)) {
  20295. themeSubType += 'Series';
  20296. }
  20297. merge(option, ecModel.getTheme().get(this.subType));
  20298. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  20299. defaultEmphasis(option, 'label', ['show']);
  20300. this.fillDataTextStyle(option.data);
  20301. if (layoutMode) {
  20302. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20303. }
  20304. };
  20305. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  20306. // this.settingTask.dirty();
  20307. newSeriesOption = merge(this.option, newSeriesOption, true);
  20308. this.fillDataTextStyle(newSeriesOption.data);
  20309. var layoutMode = fetchLayoutMode(this);
  20310. if (layoutMode) {
  20311. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20312. }
  20313. var sourceManager = inner$1(this).sourceManager;
  20314. sourceManager.dirty();
  20315. sourceManager.prepareSource();
  20316. var data = this.getInitialData(newSeriesOption, ecModel);
  20317. wrapData(data, this);
  20318. this.dataTask.dirty();
  20319. this.dataTask.context.data = data;
  20320. inner$1(this).dataBeforeProcessed = data;
  20321. autoSeriesName(this);
  20322. this._initSelectedMapFromData(data);
  20323. };
  20324. SeriesModel.prototype.fillDataTextStyle = function (data) {
  20325. // Default data label emphasis `show`
  20326. // FIXME Tree structure data ?
  20327. // FIXME Performance ?
  20328. if (data && !isTypedArray(data)) {
  20329. var props = ['show'];
  20330. for (var i = 0; i < data.length; i++) {
  20331. if (data[i] && data[i].label) {
  20332. defaultEmphasis(data[i], 'label', props);
  20333. }
  20334. }
  20335. }
  20336. };
  20337. /**
  20338. * Init a data structure from data related option in series
  20339. * Must be overriden.
  20340. */
  20341. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  20342. return;
  20343. };
  20344. /**
  20345. * Append data to list
  20346. */
  20347. SeriesModel.prototype.appendData = function (params) {
  20348. // FIXME ???
  20349. // (1) If data from dataset, forbidden append.
  20350. // (2) support append data of dataset.
  20351. var data = this.getRawData();
  20352. data.appendData(params.data);
  20353. };
  20354. /**
  20355. * Consider some method like `filter`, `map` need make new data,
  20356. * We should make sure that `seriesModel.getData()` get correct
  20357. * data in the stream procedure. So we fetch data from upstream
  20358. * each time `task.perform` called.
  20359. */
  20360. SeriesModel.prototype.getData = function (dataType) {
  20361. var task = getCurrentTask(this);
  20362. if (task) {
  20363. var data = task.context.data;
  20364. return dataType == null ? data : data.getLinkedData(dataType);
  20365. } else {
  20366. // When series is not alive (that may happen when click toolbox
  20367. // restore or setOption with not merge mode), series data may
  20368. // be still need to judge animation or something when graphic
  20369. // elements want to know whether fade out.
  20370. return inner$1(this).data;
  20371. }
  20372. };
  20373. SeriesModel.prototype.getAllData = function () {
  20374. var mainData = this.getData();
  20375. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  20376. data: mainData
  20377. }];
  20378. };
  20379. SeriesModel.prototype.setData = function (data) {
  20380. var task = getCurrentTask(this);
  20381. if (task) {
  20382. var context = task.context; // Consider case: filter, data sample.
  20383. // FIXME:TS never used, so comment it
  20384. // if (context.data !== data && task.modifyOutputEnd) {
  20385. // task.setOutputEnd(data.count());
  20386. // }
  20387. context.outputData = data; // Caution: setData should update context.data,
  20388. // Because getData may be called multiply in a
  20389. // single stage and expect to get the data just
  20390. // set. (For example, AxisProxy, x y both call
  20391. // getData and setDate sequentially).
  20392. // So the context.data should be fetched from
  20393. // upstream each time when a stage starts to be
  20394. // performed.
  20395. if (task !== this.dataTask) {
  20396. context.data = data;
  20397. }
  20398. }
  20399. inner$1(this).data = data;
  20400. };
  20401. SeriesModel.prototype.getSource = function () {
  20402. return inner$1(this).sourceManager.getSource();
  20403. };
  20404. /**
  20405. * Get data before processed
  20406. */
  20407. SeriesModel.prototype.getRawData = function () {
  20408. return inner$1(this).dataBeforeProcessed;
  20409. };
  20410. /**
  20411. * Get base axis if has coordinate system and has axis.
  20412. * By default use coordSys.getBaseAxis();
  20413. * Can be overrided for some chart.
  20414. * @return {type} description
  20415. */
  20416. SeriesModel.prototype.getBaseAxis = function () {
  20417. var coordSys = this.coordinateSystem; // @ts-ignore
  20418. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20419. };
  20420. /**
  20421. * Default tooltip formatter
  20422. *
  20423. * @param dataIndex
  20424. * @param multipleSeries
  20425. * @param dataType
  20426. * @param renderMode valid values: 'html'(by default) and 'richText'.
  20427. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20428. * string is used as DOM HTML content.
  20429. * 'richText' is used for rendering tooltip in rich text form, for those where
  20430. * DOM operation is not supported.
  20431. * @return formatted tooltip with `html` and `markers`
  20432. * Notice: The override method can also return string
  20433. */
  20434. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  20435. return defaultSeriesFormatTooltip({
  20436. series: this,
  20437. dataIndex: dataIndex,
  20438. multipleSeries: multipleSeries
  20439. });
  20440. };
  20441. SeriesModel.prototype.isAnimationEnabled = function () {
  20442. if (env.node) {
  20443. return false;
  20444. }
  20445. var animationEnabled = this.getShallow('animation');
  20446. if (animationEnabled) {
  20447. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20448. animationEnabled = false;
  20449. }
  20450. }
  20451. return !!animationEnabled;
  20452. };
  20453. SeriesModel.prototype.restoreData = function () {
  20454. this.dataTask.dirty();
  20455. };
  20456. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  20457. var ecModel = this.ecModel; // PENDING
  20458. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  20459. if (!color) {
  20460. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20461. }
  20462. return color;
  20463. };
  20464. /**
  20465. * Use `data.mapDimensionsAll(coordDim)` instead.
  20466. * @deprecated
  20467. */
  20468. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  20469. return this.getRawData().mapDimensionsAll(coordDim);
  20470. };
  20471. /**
  20472. * Get progressive rendering count each step
  20473. */
  20474. SeriesModel.prototype.getProgressive = function () {
  20475. return this.get('progressive');
  20476. };
  20477. /**
  20478. * Get progressive rendering count each step
  20479. */
  20480. SeriesModel.prototype.getProgressiveThreshold = function () {
  20481. return this.get('progressiveThreshold');
  20482. }; // PENGING If selectedMode is null ?
  20483. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  20484. this._innerSelect(this.getData(dataType), innerDataIndices);
  20485. };
  20486. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  20487. var selectedMap = this.option.selectedMap;
  20488. if (!selectedMap) {
  20489. return;
  20490. }
  20491. var data = this.getData(dataType);
  20492. for (var i = 0; i < innerDataIndices.length; i++) {
  20493. var dataIndex = innerDataIndices[i];
  20494. var nameOrId = getSelectionKey(data, dataIndex);
  20495. selectedMap[nameOrId] = false;
  20496. this._selectedDataIndicesMap[nameOrId] = -1;
  20497. }
  20498. };
  20499. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  20500. var tmpArr = [];
  20501. for (var i = 0; i < innerDataIndices.length; i++) {
  20502. tmpArr[0] = innerDataIndices[i];
  20503. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  20504. }
  20505. };
  20506. SeriesModel.prototype.getSelectedDataIndices = function () {
  20507. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  20508. var nameOrIds = keys(selectedDataIndicesMap);
  20509. var dataIndices = [];
  20510. for (var i = 0; i < nameOrIds.length; i++) {
  20511. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  20512. if (dataIndex >= 0) {
  20513. dataIndices.push(dataIndex);
  20514. }
  20515. }
  20516. return dataIndices;
  20517. };
  20518. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  20519. var selectedMap = this.option.selectedMap;
  20520. if (!selectedMap) {
  20521. return false;
  20522. }
  20523. var data = this.getData(dataType);
  20524. var nameOrId = getSelectionKey(data, dataIndex);
  20525. return selectedMap[nameOrId] || false;
  20526. };
  20527. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  20528. var _a, _b;
  20529. var selectedMode = this.option.selectedMode;
  20530. var len = innerDataIndices.length;
  20531. if (!selectedMode || !len) {
  20532. return;
  20533. }
  20534. if (selectedMode === 'multiple') {
  20535. var selectedMap = this.option.selectedMap || (this.option.selectedMap = {});
  20536. for (var i = 0; i < len; i++) {
  20537. var dataIndex = innerDataIndices[i]; // TODO diffrent types of data share same object.
  20538. var nameOrId = getSelectionKey(data, dataIndex);
  20539. selectedMap[nameOrId] = true;
  20540. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  20541. }
  20542. } else if (selectedMode === 'single' || selectedMode === true) {
  20543. var lastDataIndex = innerDataIndices[len - 1];
  20544. var nameOrId = getSelectionKey(data, lastDataIndex);
  20545. this.option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  20546. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  20547. }
  20548. };
  20549. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  20550. // Ignore select info in data if selectedMap exists.
  20551. // NOTE It's only for legacy usage. edge data is not supported.
  20552. if (this.option.selectedMap) {
  20553. return;
  20554. }
  20555. var dataIndices = [];
  20556. if (data.hasItemOption) {
  20557. data.each(function (idx) {
  20558. var rawItem = data.getRawDataItem(idx);
  20559. if (typeof rawItem === 'object' && rawItem.selected) {
  20560. dataIndices.push(idx);
  20561. }
  20562. });
  20563. }
  20564. if (dataIndices.length > 0) {
  20565. this._innerSelect(data, dataIndices);
  20566. }
  20567. }; // /**
  20568. // * @see {module:echarts/stream/Scheduler}
  20569. // */
  20570. // abstract pipeTask: null
  20571. SeriesModel.registerClass = function (clz) {
  20572. return ComponentModel.registerClass(clz);
  20573. };
  20574. SeriesModel.protoInitialize = function () {
  20575. var proto = SeriesModel.prototype;
  20576. proto.type = 'series.__base__';
  20577. proto.seriesIndex = 0;
  20578. proto.useColorPaletteOnData = false;
  20579. proto.ignoreStyleOnData = false;
  20580. proto.hasSymbolVisual = false;
  20581. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  20582. proto.visualStyleAccessPath = 'itemStyle';
  20583. proto.visualDrawType = 'fill';
  20584. }();
  20585. return SeriesModel;
  20586. }(ComponentModel);
  20587. mixin(SeriesModel, DataFormatMixin);
  20588. mixin(SeriesModel, PaletteMixin);
  20589. mountExtend(SeriesModel, ComponentModel);
  20590. /**
  20591. * MUST be called after `prepareSource` called
  20592. * Here we need to make auto series, especially for auto legend. But we
  20593. * do not modify series.name in option to avoid side effects.
  20594. */
  20595. function autoSeriesName(seriesModel) {
  20596. // User specified name has higher priority, otherwise it may cause
  20597. // series can not be queried unexpectedly.
  20598. var name = seriesModel.name;
  20599. if (!isNameSpecified(seriesModel)) {
  20600. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20601. }
  20602. }
  20603. function getSeriesAutoName(seriesModel) {
  20604. var data = seriesModel.getRawData();
  20605. var dataDims = data.mapDimensionsAll('seriesName');
  20606. var nameArr = [];
  20607. each(dataDims, function (dataDim) {
  20608. var dimInfo = data.getDimensionInfo(dataDim);
  20609. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20610. });
  20611. return nameArr.join(' ');
  20612. }
  20613. function dataTaskCount(context) {
  20614. return context.model.getRawData().count();
  20615. }
  20616. function dataTaskReset(context) {
  20617. var seriesModel = context.model;
  20618. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20619. return dataTaskProgress;
  20620. }
  20621. function dataTaskProgress(param, context) {
  20622. // Avoid repead cloneShallow when data just created in reset.
  20623. if (context.outputData && param.end > context.outputData.count()) {
  20624. context.model.getRawData().cloneShallow(context.outputData);
  20625. }
  20626. } // TODO refactor
  20627. function wrapData(data, seriesModel) {
  20628. each(__spreadArrays(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  20629. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  20630. });
  20631. }
  20632. function onDataChange(seriesModel, newList) {
  20633. var task = getCurrentTask(seriesModel);
  20634. if (task) {
  20635. // Consider case: filter, selectRange
  20636. task.setOutputEnd((newList || this).count());
  20637. }
  20638. return newList;
  20639. }
  20640. function getCurrentTask(seriesModel) {
  20641. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20642. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20643. if (pipeline) {
  20644. // When pipline finished, the currrentTask keep the last
  20645. // task (renderTask).
  20646. var task = pipeline.currentTask;
  20647. if (task) {
  20648. var agentStubMap = task.agentStubMap;
  20649. if (agentStubMap) {
  20650. task = agentStubMap.get(seriesModel.uid);
  20651. }
  20652. }
  20653. return task;
  20654. }
  20655. }
  20656. var ComponentView =
  20657. /** @class */
  20658. function () {
  20659. function ComponentView() {
  20660. this.group = new Group();
  20661. this.uid = getUID('viewComponent');
  20662. }
  20663. ComponentView.prototype.init = function (ecModel, api) {};
  20664. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  20665. ComponentView.prototype.dispose = function (ecModel, api) {};
  20666. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  20667. };
  20668. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  20669. };
  20670. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  20671. };
  20672. /**
  20673. * Hook for blur target series.
  20674. * Can be used in marker for blur the markers
  20675. */
  20676. ComponentView.prototype.blurSeries = function (seriesModels, ecModel) {// Do nothing;
  20677. };
  20678. return ComponentView;
  20679. }();
  20680. enableClassExtend(ComponentView);
  20681. enableClassManagement(ComponentView);
  20682. /**
  20683. * @return {string} If large mode changed, return string 'reset';
  20684. */
  20685. function createRenderPlanner() {
  20686. var inner = makeInner();
  20687. return function (seriesModel) {
  20688. var fields = inner(seriesModel);
  20689. var pipelineContext = seriesModel.pipelineContext;
  20690. var originalLarge = !!fields.large;
  20691. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  20692. // exists. See #11611 . Probably we need to modify this structure, see the comment
  20693. // on `performRawSeries` in `Schedular.js`.
  20694. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  20695. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  20696. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  20697. };
  20698. }
  20699. var inner$2 = makeInner();
  20700. var renderPlanner = createRenderPlanner();
  20701. var ChartView =
  20702. /** @class */
  20703. function () {
  20704. function ChartView() {
  20705. this.group = new Group();
  20706. this.uid = getUID('viewChart');
  20707. this.renderTask = createTask({
  20708. plan: renderTaskPlan,
  20709. reset: renderTaskReset
  20710. });
  20711. this.renderTask.context = {
  20712. view: this
  20713. };
  20714. }
  20715. ChartView.prototype.init = function (ecModel, api) {};
  20716. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {};
  20717. /**
  20718. * Highlight series or specified data item.
  20719. */
  20720. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  20721. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20722. };
  20723. /**
  20724. * Downplay series or specified data item.
  20725. */
  20726. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  20727. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20728. };
  20729. /**
  20730. * Remove self.
  20731. */
  20732. ChartView.prototype.remove = function (ecModel, api) {
  20733. this.group.removeAll();
  20734. };
  20735. /**
  20736. * Dispose self.
  20737. */
  20738. ChartView.prototype.dispose = function (ecModel, api) {};
  20739. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  20740. this.render(seriesModel, ecModel, api, payload);
  20741. }; // FIXME never used?
  20742. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  20743. this.render(seriesModel, ecModel, api, payload);
  20744. }; // FIXME never used?
  20745. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  20746. this.render(seriesModel, ecModel, api, payload);
  20747. };
  20748. ChartView.markUpdateMethod = function (payload, methodName) {
  20749. inner$2(payload).updateMethod = methodName;
  20750. };
  20751. ChartView.protoInitialize = function () {
  20752. var proto = ChartView.prototype;
  20753. proto.type = 'chart';
  20754. }();
  20755. return ChartView;
  20756. }();
  20757. /**
  20758. * Set state of single element
  20759. */
  20760. function elSetState(el, state, highlightDigit) {
  20761. if (el) {
  20762. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  20763. }
  20764. }
  20765. function toggleHighlight(data, payload, state) {
  20766. var dataIndex = queryDataIndex(data, payload);
  20767. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  20768. if (dataIndex != null) {
  20769. each(normalizeToArray(dataIndex), function (dataIdx) {
  20770. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  20771. });
  20772. } else {
  20773. data.eachItemGraphicEl(function (el) {
  20774. elSetState(el, state, highlightDigit);
  20775. });
  20776. }
  20777. }
  20778. enableClassExtend(ChartView, ['dispose']);
  20779. enableClassManagement(ChartView);
  20780. function renderTaskPlan(context) {
  20781. return renderPlanner(context.model);
  20782. }
  20783. function renderTaskReset(context) {
  20784. var seriesModel = context.model;
  20785. var ecModel = context.ecModel;
  20786. var api = context.api;
  20787. var payload = context.payload; // FIXME: remove updateView updateVisual
  20788. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20789. var view = context.view;
  20790. var updateMethod = payload && inner$2(payload).updateMethod;
  20791. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  20792. // is less than progressive threshold.
  20793. : 'render';
  20794. if (methodName !== 'render') {
  20795. view[methodName](seriesModel, ecModel, api, payload);
  20796. }
  20797. return progressMethodMap[methodName];
  20798. }
  20799. var progressMethodMap = {
  20800. incrementalPrepareRender: {
  20801. progress: function (params, context) {
  20802. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  20803. }
  20804. },
  20805. render: {
  20806. // Put view.render in `progress` to support appendData. But in this case
  20807. // view.render should not be called in reset, otherwise it will be called
  20808. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20809. // in any cases.
  20810. forceFirstProgress: true,
  20811. progress: function (params, context) {
  20812. context.view.render(context.model, context.ecModel, context.api, context.payload);
  20813. }
  20814. }
  20815. };
  20816. /*
  20817. * Licensed to the Apache Software Foundation (ASF) under one
  20818. * or more contributor license agreements. See the NOTICE file
  20819. * distributed with this work for additional information
  20820. * regarding copyright ownership. The ASF licenses this file
  20821. * to you under the Apache License, Version 2.0 (the
  20822. * "License"); you may not use this file except in compliance
  20823. * with the License. You may obtain a copy of the License at
  20824. *
  20825. * http://www.apache.org/licenses/LICENSE-2.0
  20826. *
  20827. * Unless required by applicable law or agreed to in writing,
  20828. * software distributed under the License is distributed on an
  20829. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20830. * KIND, either express or implied. See the License for the
  20831. * specific language governing permissions and limitations
  20832. * under the License.
  20833. */
  20834. /**
  20835. * AUTO-GENERATED FILE. DO NOT MODIFY.
  20836. */
  20837. /*
  20838. * Licensed to the Apache Software Foundation (ASF) under one
  20839. * or more contributor license agreements. See the NOTICE file
  20840. * distributed with this work for additional information
  20841. * regarding copyright ownership. The ASF licenses this file
  20842. * to you under the Apache License, Version 2.0 (the
  20843. * "License"); you may not use this file except in compliance
  20844. * with the License. You may obtain a copy of the License at
  20845. *
  20846. * http://www.apache.org/licenses/LICENSE-2.0
  20847. *
  20848. * Unless required by applicable law or agreed to in writing,
  20849. * software distributed under the License is distributed on an
  20850. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20851. * KIND, either express or implied. See the License for the
  20852. * specific language governing permissions and limitations
  20853. * under the License.
  20854. */
  20855. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  20856. var RATE = '\0__throttleRate';
  20857. var THROTTLE_TYPE = '\0__throttleType';
  20858. /**
  20859. * @public
  20860. * @param {(Function)} fn
  20861. * @param {number} [delay=0] Unit: ms.
  20862. * @param {boolean} [debounce=false]
  20863. * true: If call interval less than `delay`, only the last call works.
  20864. * false: If call interval less than `delay, call works on fixed rate.
  20865. * @return {(Function)} throttled fn.
  20866. */
  20867. function throttle(fn, delay, debounce) {
  20868. var currCall;
  20869. var lastCall = 0;
  20870. var lastExec = 0;
  20871. var timer = null;
  20872. var diff;
  20873. var scope;
  20874. var args;
  20875. var debounceNextCall;
  20876. delay = delay || 0;
  20877. function exec() {
  20878. lastExec = new Date().getTime();
  20879. timer = null;
  20880. fn.apply(scope, args || []);
  20881. }
  20882. var cb = function () {
  20883. var cbArgs = [];
  20884. for (var _i = 0; _i < arguments.length; _i++) {
  20885. cbArgs[_i] = arguments[_i];
  20886. }
  20887. currCall = new Date().getTime();
  20888. scope = this;
  20889. args = cbArgs;
  20890. var thisDelay = debounceNextCall || delay;
  20891. var thisDebounce = debounceNextCall || debounce;
  20892. debounceNextCall = null;
  20893. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20894. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  20895. // than a new call of `cb`, that is, preserving the command order. Consider
  20896. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20897. // happens, either the `exec` is called dierectly, or the call is delayed.
  20898. // But the delayed call should never be later than next call of `cb`. Under
  20899. // this assurance, we can simply update view state each time `dispatchAction`
  20900. // triggered by user roaming, but not need to add extra code to avoid the
  20901. // state being "rolled-back".
  20902. if (thisDebounce) {
  20903. timer = setTimeout(exec, thisDelay);
  20904. } else {
  20905. if (diff >= 0) {
  20906. exec();
  20907. } else {
  20908. timer = setTimeout(exec, -diff);
  20909. }
  20910. }
  20911. lastCall = currCall;
  20912. };
  20913. /**
  20914. * Clear throttle.
  20915. * @public
  20916. */
  20917. cb.clear = function () {
  20918. if (timer) {
  20919. clearTimeout(timer);
  20920. timer = null;
  20921. }
  20922. };
  20923. /**
  20924. * Enable debounce once.
  20925. */
  20926. cb.debounceNextCall = function (debounceDelay) {
  20927. debounceNextCall = debounceDelay;
  20928. };
  20929. return cb;
  20930. }
  20931. /**
  20932. * Create throttle method or update throttle rate.
  20933. *
  20934. * @example
  20935. * ComponentView.prototype.render = function () {
  20936. * ...
  20937. * throttle.createOrUpdate(
  20938. * this,
  20939. * '_dispatchAction',
  20940. * this.model.get('throttle'),
  20941. * 'fixRate'
  20942. * );
  20943. * };
  20944. * ComponentView.prototype.remove = function () {
  20945. * throttle.clear(this, '_dispatchAction');
  20946. * };
  20947. * ComponentView.prototype.dispose = function () {
  20948. * throttle.clear(this, '_dispatchAction');
  20949. * };
  20950. *
  20951. */
  20952. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  20953. var fn = obj[fnAttr];
  20954. if (!fn) {
  20955. return;
  20956. }
  20957. var originFn = fn[ORIGIN_METHOD] || fn;
  20958. var lastThrottleType = fn[THROTTLE_TYPE];
  20959. var lastRate = fn[RATE];
  20960. if (lastRate !== rate || lastThrottleType !== throttleType) {
  20961. if (rate == null || !throttleType) {
  20962. return obj[fnAttr] = originFn;
  20963. }
  20964. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  20965. fn[ORIGIN_METHOD] = originFn;
  20966. fn[THROTTLE_TYPE] = throttleType;
  20967. fn[RATE] = rate;
  20968. }
  20969. return fn;
  20970. }
  20971. /**
  20972. * Clear throttle. Example see throttle.createOrUpdate.
  20973. */
  20974. function clear(obj, fnAttr) {
  20975. var fn = obj[fnAttr];
  20976. if (fn && fn[ORIGIN_METHOD]) {
  20977. obj[fnAttr] = fn[ORIGIN_METHOD];
  20978. }
  20979. }
  20980. var inner$3 = makeInner();
  20981. var defaultStyleMappers = {
  20982. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  20983. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  20984. };
  20985. var defaultColorKey = {
  20986. lineStyle: 'stroke',
  20987. itemStyle: 'fill'
  20988. };
  20989. function getStyleMapper(seriesModel, stylePath) {
  20990. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  20991. if (!styleMapper) {
  20992. console.warn("Unkown style type '" + stylePath + "'.");
  20993. return defaultStyleMappers.itemStyle;
  20994. }
  20995. return styleMapper;
  20996. }
  20997. function getDefaultColorKey(seriesModel, stylePath) {
  20998. // return defaultColorKey[stylePath] ||
  20999. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  21000. if (!colorKey) {
  21001. console.warn("Unkown style type '" + stylePath + "'.");
  21002. return 'fill';
  21003. }
  21004. return colorKey;
  21005. }
  21006. var seriesStyleTask = {
  21007. createOnAllSeries: true,
  21008. performRawSeries: true,
  21009. reset: function (seriesModel, ecModel) {
  21010. var data = seriesModel.getData();
  21011. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  21012. var styleModel = seriesModel.getModel(stylePath);
  21013. var getStyle = getStyleMapper(seriesModel, stylePath);
  21014. var globalStyle = getStyle(styleModel);
  21015. var decalOption = styleModel.getShallow('decal');
  21016. if (decalOption) {
  21017. data.setVisual('decal', decalOption);
  21018. decalOption.dirty = true;
  21019. } // TODO
  21020. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  21021. var color = globalStyle[colorKey]; // TODO style callback
  21022. var colorCallback = isFunction(color) ? color : null; // Get from color palette by default.
  21023. if (!globalStyle[colorKey] || colorCallback) {
  21024. // Note: if some series has color specified (e.g., by itemStyle.color), we DO NOT
  21025. // make it effect palette. Bacause some scenarios users need to make some series
  21026. // transparent or as background, which should better not effect the palette.
  21027. globalStyle[colorKey] = seriesModel.getColorFromPalette( // TODO series count changed.
  21028. seriesModel.name, null, ecModel.getSeriesCount());
  21029. data.setVisual('colorFromPalette', true);
  21030. }
  21031. data.setVisual('style', globalStyle);
  21032. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  21033. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  21034. data.setVisual('colorFromPalette', false);
  21035. return {
  21036. dataEach: function (data, idx) {
  21037. var dataParams = seriesModel.getDataParams(idx);
  21038. var itemStyle = extend({}, globalStyle);
  21039. itemStyle[colorKey] = colorCallback(dataParams);
  21040. data.setItemVisual(idx, 'style', itemStyle);
  21041. }
  21042. };
  21043. }
  21044. }
  21045. };
  21046. var sharedModel = new Model();
  21047. var dataStyleTask = {
  21048. createOnAllSeries: true,
  21049. performRawSeries: true,
  21050. reset: function (seriesModel, ecModel) {
  21051. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  21052. return;
  21053. }
  21054. var data = seriesModel.getData();
  21055. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  21056. var getStyle = getStyleMapper(seriesModel, stylePath);
  21057. var colorKey = data.getVisual('drawType');
  21058. return {
  21059. dataEach: data.hasItemOption ? function (data, idx) {
  21060. // Not use getItemModel for performance considuration
  21061. var rawItem = data.getRawDataItem(idx);
  21062. if (rawItem && rawItem[stylePath]) {
  21063. sharedModel.option = rawItem[stylePath];
  21064. var style = getStyle(sharedModel);
  21065. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  21066. extend(existsStyle, style);
  21067. if (sharedModel.option.decal) {
  21068. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  21069. sharedModel.option.decal.dirty = true;
  21070. }
  21071. if (colorKey in style) {
  21072. data.setItemVisual(idx, 'colorFromPalette', false);
  21073. }
  21074. }
  21075. } : null
  21076. };
  21077. }
  21078. }; // Pick color from palette for the data which has not been set with color yet.
  21079. // Note: do not support stream rendering. No such cases yet.
  21080. var dataColorPaletteTask = {
  21081. performRawSeries: true,
  21082. overallReset: function (ecModel) {
  21083. // Each type of series use one scope.
  21084. // Pie and funnel are using diferrent scopes
  21085. var paletteScopeGroupByType = createHashMap();
  21086. ecModel.eachSeries(function (seriesModel) {
  21087. if (!seriesModel.useColorPaletteOnData) {
  21088. return;
  21089. }
  21090. var colorScope = paletteScopeGroupByType.get(seriesModel.type);
  21091. if (!colorScope) {
  21092. colorScope = {};
  21093. paletteScopeGroupByType.set(seriesModel.type, colorScope);
  21094. }
  21095. inner$3(seriesModel).scope = colorScope;
  21096. });
  21097. ecModel.eachSeries(function (seriesModel) {
  21098. if (!seriesModel.useColorPaletteOnData || ecModel.isSeriesFiltered(seriesModel)) {
  21099. return;
  21100. }
  21101. var dataAll = seriesModel.getRawData();
  21102. var idxMap = {};
  21103. var data = seriesModel.getData();
  21104. var colorScope = inner$3(seriesModel).scope;
  21105. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  21106. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  21107. data.each(function (idx) {
  21108. var rawIdx = data.getRawIndex(idx);
  21109. idxMap[rawIdx] = idx;
  21110. }); // Iterate on data before filtered. To make sure color from palette can be
  21111. // Consistent when toggling legend.
  21112. dataAll.each(function (rawIdx) {
  21113. var idx = idxMap[rawIdx];
  21114. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  21115. // also picked from color palette. So following situation is not in the case:
  21116. // 1. series.itemStyle.color is set
  21117. // 2. color is encoded by visualMap
  21118. if (fromPalette) {
  21119. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  21120. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  21121. var dataCount = dataAll.count();
  21122. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  21123. }
  21124. });
  21125. });
  21126. }
  21127. };
  21128. var PI$3 = Math.PI;
  21129. /**
  21130. * @param {module:echarts/ExtensionAPI} api
  21131. * @param {Object} [opts]
  21132. * @param {string} [opts.text]
  21133. * @param {string} [opts.color]
  21134. * @param {string} [opts.textColor]
  21135. * @return {module:zrender/Element}
  21136. */
  21137. function defaultLoading(api, opts) {
  21138. opts = opts || {};
  21139. defaults(opts, {
  21140. text: 'loading',
  21141. textColor: '#000',
  21142. fontSize: 12,
  21143. fontWeight: 'normal',
  21144. fontStyle: 'normal',
  21145. fontFamily: 'sans-serif',
  21146. maskColor: 'rgba(255, 255, 255, 0.8)',
  21147. showSpinner: true,
  21148. color: '#5470c6',
  21149. spinnerRadius: 10,
  21150. lineWidth: 5,
  21151. zlevel: 0
  21152. });
  21153. var group = new Group();
  21154. var mask = new Rect({
  21155. style: {
  21156. fill: opts.maskColor
  21157. },
  21158. zlevel: opts.zlevel,
  21159. z: 10000
  21160. });
  21161. group.add(mask);
  21162. var textContent = new ZRText({
  21163. style: {
  21164. text: opts.text,
  21165. fill: opts.textColor,
  21166. fontSize: opts.fontSize,
  21167. fontWeight: opts.fontWeight,
  21168. fontStyle: opts.fontStyle,
  21169. fontFamily: opts.fontFamily
  21170. }
  21171. });
  21172. var labelRect = new Rect({
  21173. style: {
  21174. fill: 'none'
  21175. },
  21176. textContent: textContent,
  21177. textConfig: {
  21178. position: 'right',
  21179. distance: 10
  21180. },
  21181. zlevel: opts.zlevel,
  21182. z: 10001
  21183. });
  21184. group.add(labelRect);
  21185. var arc;
  21186. if (opts.showSpinner) {
  21187. arc = new Arc({
  21188. shape: {
  21189. startAngle: -PI$3 / 2,
  21190. endAngle: -PI$3 / 2 + 0.1,
  21191. r: opts.spinnerRadius
  21192. },
  21193. style: {
  21194. stroke: opts.color,
  21195. lineCap: 'round',
  21196. lineWidth: opts.lineWidth
  21197. },
  21198. zlevel: opts.zlevel,
  21199. z: 10001
  21200. });
  21201. arc.animateShape(true).when(1000, {
  21202. endAngle: PI$3 * 3 / 2
  21203. }).start('circularInOut');
  21204. arc.animateShape(true).when(1000, {
  21205. startAngle: PI$3 * 3 / 2
  21206. }).delay(300).start('circularInOut');
  21207. group.add(arc);
  21208. } // Inject resize
  21209. group.resize = function () {
  21210. var textWidth = textContent.getBoundingRect().width;
  21211. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  21212. // textDistance needs to be calculated when both animation and text exist
  21213. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  21214. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  21215. + (textWidth ? 0 : r);
  21216. var cy = api.getHeight() / 2;
  21217. opts.showSpinner && arc.setShape({
  21218. cx: cx,
  21219. cy: cy
  21220. });
  21221. labelRect.setShape({
  21222. x: cx - r,
  21223. y: cy - r,
  21224. width: r * 2,
  21225. height: r * 2
  21226. });
  21227. mask.setShape({
  21228. x: 0,
  21229. y: 0,
  21230. width: api.getWidth(),
  21231. height: api.getHeight()
  21232. });
  21233. };
  21234. group.resize();
  21235. return group;
  21236. }
  21237. var Scheduler =
  21238. /** @class */
  21239. function () {
  21240. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21241. // key: handlerUID
  21242. this._stageTaskMap = createHashMap();
  21243. this.ecInstance = ecInstance;
  21244. this.api = api; // Fix current processors in case that in some rear cases that
  21245. // processors might be registered after echarts instance created.
  21246. // Register processors incrementally for a echarts instance is
  21247. // not supported by this stream architecture.
  21248. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21249. visualHandlers = this._visualHandlers = visualHandlers.slice();
  21250. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21251. }
  21252. Scheduler.prototype.restoreData = function (ecModel, payload) {
  21253. // TODO: Only restore needed series and components, but not all components.
  21254. // Currently `restoreData` of all of the series and component will be called.
  21255. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21256. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21257. // and some components like coordinate system, axes, dataZoom, visualMap only
  21258. // need their target series refresh.
  21259. // (1) If we are implementing this feature some day, we should consider these cases:
  21260. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21261. // on the settings of `dataZoom`), it should be re-performed if the component
  21262. // is modified by `setOption`.
  21263. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21264. // it should be re-performed when the result array of `getTargetSeries` changed.
  21265. // We use `dependencies` to cover these issues.
  21266. // (3) How to update target series when coordinate system related components modified.
  21267. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21268. // and this case all of the tasks will be set as dirty.
  21269. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  21270. // depends on all of the series.
  21271. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21272. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21273. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21274. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21275. // probably cause state chaos (consider `dataZoomProcessor`).
  21276. this._stageTaskMap.each(function (taskRecord) {
  21277. var overallTask = taskRecord.overallTask;
  21278. overallTask && overallTask.dirty();
  21279. });
  21280. }; // If seriesModel provided, incremental threshold is check by series data.
  21281. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  21282. // For overall task
  21283. if (!task.__pipeline) {
  21284. return;
  21285. }
  21286. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21287. var pCtx = pipeline.context;
  21288. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  21289. var step = incremental ? pipeline.step : null;
  21290. var modDataCount = pCtx && pCtx.modDataCount;
  21291. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21292. return {
  21293. step: step,
  21294. modBy: modBy,
  21295. modDataCount: modDataCount
  21296. };
  21297. };
  21298. Scheduler.prototype.getPipeline = function (pipelineId) {
  21299. return this._pipelineMap.get(pipelineId);
  21300. };
  21301. /**
  21302. * Current, progressive rendering starts from visual and layout.
  21303. * Always detect render mode in the same stage, avoiding that incorrect
  21304. * detection caused by data filtering.
  21305. * Caution:
  21306. * `updateStreamModes` use `seriesModel.getData()`.
  21307. */
  21308. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  21309. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21310. var data = seriesModel.getData();
  21311. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  21312. // animation frame. Note that some types of series do not provide
  21313. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21314. // use the term `incremental` but not `progressive` to describe the
  21315. // case that `chart.appendData`.
  21316. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  21317. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21318. // see `test/candlestick-large3.html`
  21319. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21320. seriesModel.pipelineContext = pipeline.context = {
  21321. progressiveRender: progressiveRender,
  21322. modDataCount: modDataCount,
  21323. large: large
  21324. };
  21325. };
  21326. Scheduler.prototype.restorePipelines = function (ecModel) {
  21327. var scheduler = this;
  21328. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21329. ecModel.eachSeries(function (seriesModel) {
  21330. var progressive = seriesModel.getProgressive();
  21331. var pipelineId = seriesModel.uid;
  21332. pipelineMap.set(pipelineId, {
  21333. id: pipelineId,
  21334. head: null,
  21335. tail: null,
  21336. threshold: seriesModel.getProgressiveThreshold(),
  21337. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21338. blockIndex: -1,
  21339. step: Math.round(progressive || 700),
  21340. count: 0
  21341. });
  21342. scheduler._pipe(seriesModel, seriesModel.dataTask);
  21343. });
  21344. };
  21345. Scheduler.prototype.prepareStageTasks = function () {
  21346. var stageTaskMap = this._stageTaskMap;
  21347. var ecModel = this.api.getModel();
  21348. var api = this.api;
  21349. each(this._allHandlers, function (handler) {
  21350. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  21351. var errMsg = '';
  21352. if ("development" !== 'production') {
  21353. // Currently do not need to support to sepecify them both.
  21354. errMsg = '"reset" and "overallReset" must not be both specified.';
  21355. }
  21356. assert(!(handler.reset && handler.overallReset), errMsg);
  21357. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  21358. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  21359. }, this);
  21360. };
  21361. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  21362. var renderTask = view.renderTask;
  21363. var context = renderTask.context;
  21364. context.model = model;
  21365. context.ecModel = ecModel;
  21366. context.api = api;
  21367. renderTask.__block = !view.incrementalPrepareRender;
  21368. this._pipe(model, renderTask);
  21369. };
  21370. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  21371. // If we do not use `block` here, it should be considered when to update modes.
  21372. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  21373. block: true
  21374. });
  21375. };
  21376. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  21377. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  21378. };
  21379. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  21380. opt = opt || {};
  21381. var unfinished = false;
  21382. var scheduler = this;
  21383. each(stageHandlers, function (stageHandler, idx) {
  21384. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21385. return;
  21386. }
  21387. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21388. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21389. var overallTask = stageHandlerRecord.overallTask;
  21390. if (overallTask) {
  21391. var overallNeedDirty_1;
  21392. var agentStubMap = overallTask.agentStubMap;
  21393. agentStubMap.each(function (stub) {
  21394. if (needSetDirty(opt, stub)) {
  21395. stub.dirty();
  21396. overallNeedDirty_1 = true;
  21397. }
  21398. });
  21399. overallNeedDirty_1 && overallTask.dirty();
  21400. scheduler.updatePayload(overallTask, payload);
  21401. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  21402. // then execute the overall task. And stub will call seriesModel.setData,
  21403. // which ensures that in the overallTask seriesModel.getData() will not
  21404. // return incorrect data.
  21405. agentStubMap.each(function (stub) {
  21406. stub.perform(performArgs_1);
  21407. });
  21408. if (overallTask.perform(performArgs_1)) {
  21409. unfinished = true;
  21410. }
  21411. } else if (seriesTaskMap) {
  21412. seriesTaskMap.each(function (task, pipelineId) {
  21413. if (needSetDirty(opt, task)) {
  21414. task.dirty();
  21415. }
  21416. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  21417. // if intending to decalare `performRawSeries` in handlers, only
  21418. // stream-independent (specifically, data item independent) operations can be
  21419. // performed. Because is a series is filtered, most of the tasks will not
  21420. // be performed. A stream-dependent operation probably cause wrong biz logic.
  21421. // Perhaps we should not provide a separate callback for this case instead
  21422. // of providing the config `performRawSeries`. The stream-dependent operaions
  21423. // and stream-independent operations should better not be mixed.
  21424. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  21425. scheduler.updatePayload(task, payload);
  21426. if (task.perform(performArgs)) {
  21427. unfinished = true;
  21428. }
  21429. });
  21430. }
  21431. });
  21432. function needSetDirty(opt, task) {
  21433. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21434. }
  21435. this.unfinished = unfinished || this.unfinished;
  21436. };
  21437. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  21438. var unfinished;
  21439. ecModel.eachSeries(function (seriesModel) {
  21440. // Progress to the end for dataInit and dataRestore.
  21441. unfinished = seriesModel.dataTask.perform() || unfinished;
  21442. });
  21443. this.unfinished = unfinished || this.unfinished;
  21444. };
  21445. Scheduler.prototype.plan = function () {
  21446. // Travel pipelines, check block.
  21447. this._pipelineMap.each(function (pipeline) {
  21448. var task = pipeline.tail;
  21449. do {
  21450. if (task.__block) {
  21451. pipeline.blockIndex = task.__idxInPipeline;
  21452. break;
  21453. }
  21454. task = task.getUpstream();
  21455. } while (task);
  21456. });
  21457. };
  21458. Scheduler.prototype.updatePayload = function (task, payload) {
  21459. payload !== 'remain' && (task.context.payload = payload);
  21460. };
  21461. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  21462. var scheduler = this;
  21463. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  21464. // do not need to reuse the map.
  21465. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  21466. var seriesType = stageHandler.seriesType;
  21467. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21468. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21469. // it works but it may cause other irrelevant charts blocked.
  21470. if (stageHandler.createOnAllSeries) {
  21471. ecModel.eachRawSeries(create);
  21472. } else if (seriesType) {
  21473. ecModel.eachRawSeriesByType(seriesType, create);
  21474. } else if (getTargetSeries) {
  21475. getTargetSeries(ecModel, api).each(create);
  21476. }
  21477. function create(seriesModel) {
  21478. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  21479. // Reuse original task instance.
  21480. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  21481. plan: seriesTaskPlan,
  21482. reset: seriesTaskReset,
  21483. count: seriesTaskCount
  21484. }));
  21485. task.context = {
  21486. model: seriesModel,
  21487. ecModel: ecModel,
  21488. api: api,
  21489. // PENDING: `useClearVisual` not used?
  21490. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21491. plan: stageHandler.plan,
  21492. reset: stageHandler.reset,
  21493. scheduler: scheduler
  21494. };
  21495. scheduler._pipe(seriesModel, task);
  21496. }
  21497. };
  21498. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  21499. var scheduler = this;
  21500. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  21501. || createTask({
  21502. reset: overallTaskReset
  21503. });
  21504. overallTask.context = {
  21505. ecModel: ecModel,
  21506. api: api,
  21507. overallReset: stageHandler.overallReset,
  21508. scheduler: scheduler
  21509. };
  21510. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  21511. // do not need to reuse the map.
  21512. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  21513. var seriesType = stageHandler.seriesType;
  21514. var getTargetSeries = stageHandler.getTargetSeries;
  21515. var overallProgress = true;
  21516. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  21517. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  21518. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21519. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21520. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21521. // we set the pipeline block.
  21522. var errMsg = '';
  21523. if ("development" !== 'production') {
  21524. errMsg = '"createOnAllSeries" do not supported for "overallReset", ' + 'becuase it will block all streams.';
  21525. }
  21526. assert(!stageHandler.createOnAllSeries, errMsg);
  21527. if (seriesType) {
  21528. ecModel.eachRawSeriesByType(seriesType, createStub);
  21529. } else if (getTargetSeries) {
  21530. getTargetSeries(ecModel, api).each(createStub);
  21531. } // Otherwise, (usually it is legancy case), the overall task will only be
  21532. // executed when upstream dirty. Otherwise the progressive rendering of all
  21533. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21534. // dirty info from upsteam.
  21535. else {
  21536. overallProgress = false;
  21537. each(ecModel.getSeries(), createStub);
  21538. }
  21539. function createStub(seriesModel) {
  21540. var pipelineId = seriesModel.uid;
  21541. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  21542. // should be set as dirty and re-performed.
  21543. shouldOverallTaskDirty = true, createTask({
  21544. reset: stubReset,
  21545. onDirty: stubOnDirty
  21546. })));
  21547. stub.context = {
  21548. model: seriesModel,
  21549. overallProgress: overallProgress // FIXME:TS never used, so comment it
  21550. // modifyOutputEnd: modifyOutputEnd
  21551. };
  21552. stub.agent = overallTask;
  21553. stub.__block = overallProgress;
  21554. scheduler._pipe(seriesModel, stub);
  21555. }
  21556. if (shouldOverallTaskDirty) {
  21557. overallTask.dirty();
  21558. }
  21559. };
  21560. Scheduler.prototype._pipe = function (seriesModel, task) {
  21561. var pipelineId = seriesModel.uid;
  21562. var pipeline = this._pipelineMap.get(pipelineId);
  21563. !pipeline.head && (pipeline.head = task);
  21564. pipeline.tail && pipeline.tail.pipe(task);
  21565. pipeline.tail = task;
  21566. task.__idxInPipeline = pipeline.count++;
  21567. task.__pipeline = pipeline;
  21568. };
  21569. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21570. if (isFunction(stageHandler)) {
  21571. stageHandler = {
  21572. overallReset: stageHandler,
  21573. seriesType: detectSeriseType(stageHandler)
  21574. };
  21575. }
  21576. stageHandler.uid = getUID('stageHandler');
  21577. visualType && (stageHandler.visualType = visualType);
  21578. return stageHandler;
  21579. };
  21580. return Scheduler;
  21581. }();
  21582. function overallTaskReset(context) {
  21583. context.overallReset(context.ecModel, context.api, context.payload);
  21584. }
  21585. function stubReset(context) {
  21586. return context.overallProgress && stubProgress;
  21587. }
  21588. function stubProgress() {
  21589. this.agent.dirty();
  21590. this.getDownstream().dirty();
  21591. }
  21592. function stubOnDirty() {
  21593. this.agent && this.agent.dirty();
  21594. }
  21595. function seriesTaskPlan(context) {
  21596. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  21597. }
  21598. function seriesTaskReset(context) {
  21599. if (context.useClearVisual) {
  21600. context.data.clearAllVisual();
  21601. }
  21602. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  21603. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  21604. return makeSeriesTaskProgress(idx);
  21605. }) : singleSeriesTaskProgress;
  21606. }
  21607. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21608. function makeSeriesTaskProgress(resetDefineIdx) {
  21609. return function (params, context) {
  21610. var data = context.data;
  21611. var resetDefine = context.resetDefines[resetDefineIdx];
  21612. if (resetDefine && resetDefine.dataEach) {
  21613. for (var i = params.start; i < params.end; i++) {
  21614. resetDefine.dataEach(data, i);
  21615. }
  21616. } else if (resetDefine && resetDefine.progress) {
  21617. resetDefine.progress(params, data);
  21618. }
  21619. };
  21620. }
  21621. function seriesTaskCount(context) {
  21622. return context.data.count();
  21623. }
  21624. /**
  21625. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21626. * To ensure that they can work normally, they should work in block mode, that is,
  21627. * they should not be started util the previous tasks finished. So they cause the
  21628. * progressive rendering disabled. We try to detect the series type, to narrow down
  21629. * the block range to only the series type they concern, but not all series.
  21630. */
  21631. function detectSeriseType(legacyFunc) {
  21632. seriesType = null;
  21633. try {
  21634. // Assume there is no async when calling `eachSeriesByType`.
  21635. legacyFunc(ecModelMock, apiMock);
  21636. } catch (e) {}
  21637. return seriesType;
  21638. }
  21639. var ecModelMock = {};
  21640. var apiMock = {};
  21641. var seriesType;
  21642. mockMethods(ecModelMock, GlobalModel);
  21643. mockMethods(apiMock, ExtensionAPI);
  21644. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21645. seriesType = type;
  21646. };
  21647. ecModelMock.eachComponent = function (cond) {
  21648. if (cond.mainType === 'series' && cond.subType) {
  21649. seriesType = cond.subType;
  21650. }
  21651. };
  21652. function mockMethods(target, Clz) {
  21653. /* eslint-disable */
  21654. for (var name_1 in Clz.prototype) {
  21655. // Do not use hasOwnProperty
  21656. target[name_1] = noop;
  21657. }
  21658. /* eslint-enable */
  21659. }
  21660. /*
  21661. * Licensed to the Apache Software Foundation (ASF) under one
  21662. * or more contributor license agreements. See the NOTICE file
  21663. * distributed with this work for additional information
  21664. * regarding copyright ownership. The ASF licenses this file
  21665. * to you under the Apache License, Version 2.0 (the
  21666. * "License"); you may not use this file except in compliance
  21667. * with the License. You may obtain a copy of the License at
  21668. *
  21669. * http://www.apache.org/licenses/LICENSE-2.0
  21670. *
  21671. * Unless required by applicable law or agreed to in writing,
  21672. * software distributed under the License is distributed on an
  21673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21674. * KIND, either express or implied. See the License for the
  21675. * specific language governing permissions and limitations
  21676. * under the License.
  21677. */
  21678. /**
  21679. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21680. */
  21681. /*
  21682. * Licensed to the Apache Software Foundation (ASF) under one
  21683. * or more contributor license agreements. See the NOTICE file
  21684. * distributed with this work for additional information
  21685. * regarding copyright ownership. The ASF licenses this file
  21686. * to you under the Apache License, Version 2.0 (the
  21687. * "License"); you may not use this file except in compliance
  21688. * with the License. You may obtain a copy of the License at
  21689. *
  21690. * http://www.apache.org/licenses/LICENSE-2.0
  21691. *
  21692. * Unless required by applicable law or agreed to in writing,
  21693. * software distributed under the License is distributed on an
  21694. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21695. * KIND, either express or implied. See the License for the
  21696. * specific language governing permissions and limitations
  21697. * under the License.
  21698. */
  21699. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  21700. var lightTheme = {
  21701. color: colorAll,
  21702. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  21703. };
  21704. /*
  21705. * Licensed to the Apache Software Foundation (ASF) under one
  21706. * or more contributor license agreements. See the NOTICE file
  21707. * distributed with this work for additional information
  21708. * regarding copyright ownership. The ASF licenses this file
  21709. * to you under the Apache License, Version 2.0 (the
  21710. * "License"); you may not use this file except in compliance
  21711. * with the License. You may obtain a copy of the License at
  21712. *
  21713. * http://www.apache.org/licenses/LICENSE-2.0
  21714. *
  21715. * Unless required by applicable law or agreed to in writing,
  21716. * software distributed under the License is distributed on an
  21717. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21718. * KIND, either express or implied. See the License for the
  21719. * specific language governing permissions and limitations
  21720. * under the License.
  21721. */
  21722. /**
  21723. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21724. */
  21725. /*
  21726. * Licensed to the Apache Software Foundation (ASF) under one
  21727. * or more contributor license agreements. See the NOTICE file
  21728. * distributed with this work for additional information
  21729. * regarding copyright ownership. The ASF licenses this file
  21730. * to you under the Apache License, Version 2.0 (the
  21731. * "License"); you may not use this file except in compliance
  21732. * with the License. You may obtain a copy of the License at
  21733. *
  21734. * http://www.apache.org/licenses/LICENSE-2.0
  21735. *
  21736. * Unless required by applicable law or agreed to in writing,
  21737. * software distributed under the License is distributed on an
  21738. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21739. * KIND, either express or implied. See the License for the
  21740. * specific language governing permissions and limitations
  21741. * under the License.
  21742. */
  21743. var contrastColor = '#B9B8CE';
  21744. var backgroundColor = '#100C2A';
  21745. var axisCommon = function () {
  21746. return {
  21747. axisLine: {
  21748. lineStyle: {
  21749. color: contrastColor
  21750. }
  21751. },
  21752. splitLine: {
  21753. lineStyle: {
  21754. color: '#484753'
  21755. }
  21756. },
  21757. splitArea: {
  21758. areaStyle: {
  21759. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  21760. }
  21761. },
  21762. minorSplitLine: {
  21763. lineStyle: {
  21764. color: '#20203B'
  21765. }
  21766. }
  21767. };
  21768. };
  21769. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  21770. var theme = {
  21771. darkMode: true,
  21772. color: colorPalette,
  21773. backgroundColor: backgroundColor,
  21774. axisPointer: {
  21775. lineStyle: {
  21776. color: '#817f91'
  21777. },
  21778. crossStyle: {
  21779. color: '#817f91'
  21780. },
  21781. label: {
  21782. // TODO Contrast of label backgorundColor
  21783. color: '#fff'
  21784. }
  21785. },
  21786. legend: {
  21787. textStyle: {
  21788. color: contrastColor
  21789. }
  21790. },
  21791. textStyle: {
  21792. color: contrastColor
  21793. },
  21794. title: {
  21795. textStyle: {
  21796. color: '#EEF1FA'
  21797. },
  21798. subtextStyle: {
  21799. color: '#B9B8CE'
  21800. }
  21801. },
  21802. toolbox: {
  21803. iconStyle: {
  21804. borderColor: contrastColor
  21805. }
  21806. },
  21807. dataZoom: {
  21808. borderColor: '#71708A',
  21809. textStyle: {
  21810. color: contrastColor
  21811. },
  21812. brushStyle: {
  21813. color: 'rgba(135,163,206,0.3)'
  21814. },
  21815. handleStyle: {
  21816. color: '#353450',
  21817. borderColor: '#C5CBE3'
  21818. },
  21819. moveHandleStyle: {
  21820. color: '#B0B6C3',
  21821. opacity: 0.3
  21822. },
  21823. fillerColor: 'rgba(135,163,206,0.2)',
  21824. emphasis: {
  21825. handleStyle: {
  21826. borderColor: '#91B7F2',
  21827. color: '#4D587D'
  21828. },
  21829. moveHandleStyle: {
  21830. color: '#636D9A',
  21831. opacity: 0.7
  21832. }
  21833. },
  21834. dataBackground: {
  21835. lineStyle: {
  21836. color: '#71708A',
  21837. width: 1
  21838. },
  21839. areaStyle: {
  21840. color: '#71708A'
  21841. }
  21842. },
  21843. selectedDataBackground: {
  21844. lineStyle: {
  21845. color: '#87A3CE'
  21846. },
  21847. areaStyle: {
  21848. color: '#87A3CE'
  21849. }
  21850. }
  21851. },
  21852. visualMap: {
  21853. textStyle: {
  21854. color: contrastColor
  21855. }
  21856. },
  21857. timeline: {
  21858. lineStyle: {
  21859. color: contrastColor
  21860. },
  21861. label: {
  21862. color: contrastColor
  21863. },
  21864. controlStyle: {
  21865. color: contrastColor,
  21866. borderColor: contrastColor
  21867. }
  21868. },
  21869. calendar: {
  21870. itemStyle: {
  21871. color: backgroundColor
  21872. },
  21873. dayLabel: {
  21874. color: contrastColor
  21875. },
  21876. monthLabel: {
  21877. color: contrastColor
  21878. },
  21879. yearLabel: {
  21880. color: contrastColor
  21881. }
  21882. },
  21883. timeAxis: axisCommon(),
  21884. logAxis: axisCommon(),
  21885. valueAxis: axisCommon(),
  21886. categoryAxis: axisCommon(),
  21887. line: {
  21888. symbol: 'circle'
  21889. },
  21890. graph: {
  21891. color: colorPalette
  21892. },
  21893. gauge: {
  21894. title: {
  21895. color: contrastColor
  21896. },
  21897. axisLine: {
  21898. lineStyle: {
  21899. color: [[1, 'rgba(207,212,219,0.2)']]
  21900. }
  21901. },
  21902. axisLabel: {
  21903. color: contrastColor
  21904. },
  21905. detail: {
  21906. color: '#EEF1FA'
  21907. }
  21908. },
  21909. candlestick: {
  21910. itemStyle: {
  21911. color: '#f64e56',
  21912. color0: '#54ea92',
  21913. borderColor: '#f64e56',
  21914. borderColor0: '#54ea92' // borderColor: '#ca2824',
  21915. // borderColor0: '#09a443'
  21916. }
  21917. }
  21918. };
  21919. theme.categoryAxis.splitLine.show = false;
  21920. function parseXML(svg) {
  21921. if (isString(svg)) {
  21922. var parser = new DOMParser();
  21923. svg = parser.parseFromString(svg, 'text/xml');
  21924. }
  21925. var svgNode = svg;
  21926. if (svgNode.nodeType === 9) {
  21927. svgNode = svgNode.firstChild;
  21928. }
  21929. while (svgNode.nodeName.toLowerCase() !== 'svg' || svgNode.nodeType !== 1) {
  21930. svgNode = svgNode.nextSibling;
  21931. }
  21932. return svgNode;
  21933. }
  21934. var storage = createHashMap();
  21935. var mapDataStorage = {
  21936. /**
  21937. * Compatible with previous `echarts.registerMap`.
  21938. * @usage
  21939. * ```js
  21940. * $.get('USA.json', function (geoJson) {
  21941. * echarts.registerMap('USA', geoJson);
  21942. * // Or
  21943. * echarts.registerMap('USA', {
  21944. * geoJson: geoJson,
  21945. * specialAreas: {}
  21946. * })
  21947. * });
  21948. *
  21949. * $.get('airport.svg', function (svg) {
  21950. * echarts.registerMap('airport', {
  21951. * svg: svg
  21952. * }
  21953. * });
  21954. *
  21955. * echarts.registerMap('eu', [
  21956. * {svg: eu-topographic.svg},
  21957. * {geoJSON: eu.json}
  21958. * ])
  21959. * ```
  21960. */
  21961. registerMap: function (mapName, rawDef, rawSpecialAreas) {
  21962. var records;
  21963. if (isArray(rawDef)) {
  21964. records = rawDef;
  21965. } else if (rawDef.svg) {
  21966. records = [{
  21967. type: 'svg',
  21968. source: rawDef.svg,
  21969. specialAreas: rawDef.specialAreas
  21970. }];
  21971. } else {
  21972. // Backward compatibility.
  21973. var geoSource = rawDef.geoJson || rawDef.geoJSON;
  21974. if (geoSource && !rawDef.features) {
  21975. rawSpecialAreas = rawDef.specialAreas;
  21976. rawDef = geoSource;
  21977. }
  21978. records = [{
  21979. type: 'geoJSON',
  21980. source: rawDef,
  21981. specialAreas: rawSpecialAreas
  21982. }];
  21983. }
  21984. each(records, function (record) {
  21985. var type = record.type;
  21986. type === 'geoJson' && (type = record.type = 'geoJSON');
  21987. var parse = parsers[type];
  21988. if ("development" !== 'production') {
  21989. assert(parse, 'Illegal map type: ' + type);
  21990. }
  21991. parse(record);
  21992. });
  21993. return storage.set(mapName, records);
  21994. },
  21995. retrieveMap: function (mapName) {
  21996. return storage.get(mapName);
  21997. }
  21998. };
  21999. var parsers = {
  22000. geoJSON: function (record) {
  22001. var source = record.source;
  22002. record.geoJSON = !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  22003. },
  22004. // Only perform parse to XML object here, which might be time
  22005. // consiming for large SVG.
  22006. // Although convert XML to zrender element is also time consiming,
  22007. // if we do it here, the clone of zrender elements has to be
  22008. // required. So we do it once for each geo instance, util real
  22009. // performance issues call for optimizing it.
  22010. svg: function (record) {
  22011. record.svgXML = parseXML(record.source);
  22012. }
  22013. };
  22014. /**
  22015. * Usage of query:
  22016. * `chart.on('click', query, handler);`
  22017. * The `query` can be:
  22018. * + The component type query string, only `mainType` or `mainType.subType`,
  22019. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  22020. * + The component query object, like:
  22021. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  22022. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  22023. * + The data query object, like:
  22024. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  22025. * + The other query object (cmponent customized query), like:
  22026. * `{element: 'some'}` (only available in custom series).
  22027. *
  22028. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  22029. * same as there is no such prop in the `query` object.
  22030. */
  22031. var ECEventProcessor =
  22032. /** @class */
  22033. function () {
  22034. function ECEventProcessor() {}
  22035. ECEventProcessor.prototype.normalizeQuery = function (query) {
  22036. var cptQuery = {};
  22037. var dataQuery = {};
  22038. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  22039. if (isString(query)) {
  22040. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  22041. cptQuery.mainType = condCptType.main || null;
  22042. cptQuery.subType = condCptType.sub || null;
  22043. } // `query` is an object, convert to {mainType, index, name, id}.
  22044. else {
  22045. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  22046. // can not be used in `compomentModel.filterForExposedEvent`.
  22047. var suffixes_1 = ['Index', 'Name', 'Id'];
  22048. var dataKeys_1 = {
  22049. name: 1,
  22050. dataIndex: 1,
  22051. dataType: 1
  22052. };
  22053. each(query, function (val, key) {
  22054. var reserved = false;
  22055. for (var i = 0; i < suffixes_1.length; i++) {
  22056. var propSuffix = suffixes_1[i];
  22057. var suffixPos = key.lastIndexOf(propSuffix);
  22058. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  22059. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  22060. if (mainType !== 'data') {
  22061. cptQuery.mainType = mainType;
  22062. cptQuery[propSuffix.toLowerCase()] = val;
  22063. reserved = true;
  22064. }
  22065. }
  22066. }
  22067. if (dataKeys_1.hasOwnProperty(key)) {
  22068. dataQuery[key] = val;
  22069. reserved = true;
  22070. }
  22071. if (!reserved) {
  22072. otherQuery[key] = val;
  22073. }
  22074. });
  22075. }
  22076. return {
  22077. cptQuery: cptQuery,
  22078. dataQuery: dataQuery,
  22079. otherQuery: otherQuery
  22080. };
  22081. };
  22082. ECEventProcessor.prototype.filter = function (eventType, query) {
  22083. // They should be assigned before each trigger call.
  22084. var eventInfo = this.eventInfo;
  22085. if (!eventInfo) {
  22086. return true;
  22087. }
  22088. var targetEl = eventInfo.targetEl;
  22089. var packedEvent = eventInfo.packedEvent;
  22090. var model = eventInfo.model;
  22091. var view = eventInfo.view; // For event like 'globalout'.
  22092. if (!model || !view) {
  22093. return true;
  22094. }
  22095. var cptQuery = query.cptQuery;
  22096. var dataQuery = query.dataQuery;
  22097. 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));
  22098. function check(query, host, prop, propOnHost) {
  22099. return query[prop] == null || host[propOnHost || prop] === query[prop];
  22100. }
  22101. };
  22102. ECEventProcessor.prototype.afterTrigger = function () {
  22103. // Make sure the eventInfo wont be used in next trigger.
  22104. this.eventInfo = null;
  22105. };
  22106. return ECEventProcessor;
  22107. }();
  22108. var seriesSymbolTask = {
  22109. createOnAllSeries: true,
  22110. // For legend.
  22111. performRawSeries: true,
  22112. reset: function (seriesModel, ecModel) {
  22113. var data = seriesModel.getData();
  22114. if (seriesModel.legendSymbol) {
  22115. data.setVisual('legendSymbol', seriesModel.legendSymbol);
  22116. }
  22117. if (!seriesModel.hasSymbolVisual) {
  22118. return;
  22119. }
  22120. var symbolType = seriesModel.get('symbol');
  22121. var symbolSize = seriesModel.get('symbolSize');
  22122. var keepAspect = seriesModel.get('symbolKeepAspect');
  22123. var symbolRotate = seriesModel.get('symbolRotate');
  22124. var hasSymbolTypeCallback = isFunction(symbolType);
  22125. var hasSymbolSizeCallback = isFunction(symbolSize);
  22126. var hasSymbolRotateCallback = isFunction(symbolRotate);
  22127. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  22128. var seriesSymbol = !hasSymbolTypeCallback && symbolType ? symbolType : seriesModel.defaultSymbol;
  22129. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  22130. var seriesSymbolRotate = !hasSymbolRotateCallback ? symbolRotate : null;
  22131. data.setVisual({
  22132. legendSymbol: seriesModel.legendSymbol || seriesSymbol,
  22133. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  22134. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  22135. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  22136. // some cases but generally it is not recommanded.
  22137. symbol: seriesSymbol,
  22138. symbolSize: seriesSymbolSize,
  22139. symbolKeepAspect: keepAspect,
  22140. symbolRotate: seriesSymbolRotate
  22141. }); // Only visible series has each data be visual encoded
  22142. if (ecModel.isSeriesFiltered(seriesModel)) {
  22143. return;
  22144. }
  22145. function dataEach(data, idx) {
  22146. var rawValue = seriesModel.getRawValue(idx);
  22147. var params = seriesModel.getDataParams(idx);
  22148. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  22149. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  22150. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  22151. }
  22152. return {
  22153. dataEach: hasCallback ? dataEach : null
  22154. };
  22155. }
  22156. };
  22157. var dataSymbolTask = {
  22158. createOnAllSeries: true,
  22159. // For legend.
  22160. performRawSeries: true,
  22161. reset: function (seriesModel, ecModel) {
  22162. if (!seriesModel.hasSymbolVisual) {
  22163. return;
  22164. } // Only visible series has each data be visual encoded
  22165. if (ecModel.isSeriesFiltered(seriesModel)) {
  22166. return;
  22167. }
  22168. var data = seriesModel.getData();
  22169. function dataEach(data, idx) {
  22170. var itemModel = data.getItemModel(idx);
  22171. var itemSymbolType = itemModel.getShallow('symbol', true);
  22172. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  22173. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  22174. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true); // If has item symbol
  22175. if (itemSymbolType != null) {
  22176. data.setItemVisual(idx, 'symbol', itemSymbolType);
  22177. }
  22178. if (itemSymbolSize != null) {
  22179. // PENDING Transform symbolSize ?
  22180. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  22181. }
  22182. if (itemSymbolRotate != null) {
  22183. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  22184. }
  22185. if (itemSymbolKeepAspect != null) {
  22186. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  22187. }
  22188. }
  22189. return {
  22190. dataEach: data.hasItemOption ? dataEach : null
  22191. };
  22192. }
  22193. };
  22194. /*
  22195. * Licensed to the Apache Software Foundation (ASF) under one
  22196. * or more contributor license agreements. See the NOTICE file
  22197. * distributed with this work for additional information
  22198. * regarding copyright ownership. The ASF licenses this file
  22199. * to you under the Apache License, Version 2.0 (the
  22200. * "License"); you may not use this file except in compliance
  22201. * with the License. You may obtain a copy of the License at
  22202. *
  22203. * http://www.apache.org/licenses/LICENSE-2.0
  22204. *
  22205. * Unless required by applicable law or agreed to in writing,
  22206. * software distributed under the License is distributed on an
  22207. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22208. * KIND, either express or implied. See the License for the
  22209. * specific language governing permissions and limitations
  22210. * under the License.
  22211. */
  22212. /**
  22213. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22214. */
  22215. /*
  22216. * Licensed to the Apache Software Foundation (ASF) under one
  22217. * or more contributor license agreements. See the NOTICE file
  22218. * distributed with this work for additional information
  22219. * regarding copyright ownership. The ASF licenses this file
  22220. * to you under the Apache License, Version 2.0 (the
  22221. * "License"); you may not use this file except in compliance
  22222. * with the License. You may obtain a copy of the License at
  22223. *
  22224. * http://www.apache.org/licenses/LICENSE-2.0
  22225. *
  22226. * Unless required by applicable law or agreed to in writing,
  22227. * software distributed under the License is distributed on an
  22228. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22229. * KIND, either express or implied. See the License for the
  22230. * specific language governing permissions and limitations
  22231. * under the License.
  22232. */
  22233. function getItemVisualFromData(data, dataIndex, key) {
  22234. switch (key) {
  22235. case 'color':
  22236. var style = data.getItemVisual(dataIndex, 'style');
  22237. return style[data.getVisual('drawType')];
  22238. case 'opacity':
  22239. return data.getItemVisual(dataIndex, 'style').opacity;
  22240. case 'symbol':
  22241. case 'symbolSize':
  22242. case 'liftZ':
  22243. return data.getItemVisual(dataIndex, key);
  22244. default:
  22245. if ("development" !== 'production') {
  22246. console.warn("Unknown visual type " + key);
  22247. }
  22248. }
  22249. }
  22250. function getVisualFromData(data, key) {
  22251. switch (key) {
  22252. case 'color':
  22253. var style = data.getVisual('style');
  22254. return style[data.getVisual('drawType')];
  22255. case 'opacity':
  22256. return data.getVisual('style').opacity;
  22257. case 'symbol':
  22258. case 'symbolSize':
  22259. case 'liftZ':
  22260. return data.getVisual(key);
  22261. default:
  22262. if ("development" !== 'production') {
  22263. console.warn("Unknown visual type " + key);
  22264. }
  22265. }
  22266. }
  22267. var PI2$6 = Math.PI * 2;
  22268. var CMD$3 = PathProxy.CMD;
  22269. var DEFAULT_SEARCH_SPACE = ['top', 'right', 'bottom', 'left'];
  22270. function getCandidateAnchor(pos, distance, rect, outPt, outDir) {
  22271. var width = rect.width;
  22272. var height = rect.height;
  22273. switch (pos) {
  22274. case 'top':
  22275. outPt.set(rect.x + width / 2, rect.y - distance);
  22276. outDir.set(0, -1);
  22277. break;
  22278. case 'bottom':
  22279. outPt.set(rect.x + width / 2, rect.y + height + distance);
  22280. outDir.set(0, 1);
  22281. break;
  22282. case 'left':
  22283. outPt.set(rect.x - distance, rect.y + height / 2);
  22284. outDir.set(-1, 0);
  22285. break;
  22286. case 'right':
  22287. outPt.set(rect.x + width + distance, rect.y + height / 2);
  22288. outDir.set(1, 0);
  22289. break;
  22290. }
  22291. }
  22292. function projectPointToArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) {
  22293. x -= cx;
  22294. y -= cy;
  22295. var d = Math.sqrt(x * x + y * y);
  22296. x /= d;
  22297. y /= d; // Intersect point.
  22298. var ox = x * r + cx;
  22299. var oy = y * r + cy;
  22300. if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) {
  22301. // Is a circle
  22302. out[0] = ox;
  22303. out[1] = oy;
  22304. return d - r;
  22305. }
  22306. if (anticlockwise) {
  22307. var tmp = startAngle;
  22308. startAngle = normalizeRadian(endAngle);
  22309. endAngle = normalizeRadian(tmp);
  22310. } else {
  22311. startAngle = normalizeRadian(startAngle);
  22312. endAngle = normalizeRadian(endAngle);
  22313. }
  22314. if (startAngle > endAngle) {
  22315. endAngle += PI2$6;
  22316. }
  22317. var angle = Math.atan2(y, x);
  22318. if (angle < 0) {
  22319. angle += PI2$6;
  22320. }
  22321. if (angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) {
  22322. // Project point is on the arc.
  22323. out[0] = ox;
  22324. out[1] = oy;
  22325. return d - r;
  22326. }
  22327. var x1 = r * Math.cos(startAngle) + cx;
  22328. var y1 = r * Math.sin(startAngle) + cy;
  22329. var x2 = r * Math.cos(endAngle) + cx;
  22330. var y2 = r * Math.sin(endAngle) + cy;
  22331. var d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
  22332. var d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
  22333. if (d1 < d2) {
  22334. out[0] = x1;
  22335. out[1] = y1;
  22336. return Math.sqrt(d1);
  22337. } else {
  22338. out[0] = x2;
  22339. out[1] = y2;
  22340. return Math.sqrt(d2);
  22341. }
  22342. }
  22343. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  22344. var dx = x - x1;
  22345. var dy = y - y1;
  22346. var dx1 = x2 - x1;
  22347. var dy1 = y2 - y1;
  22348. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  22349. dx1 /= lineLen;
  22350. dy1 /= lineLen; // dot product
  22351. var projectedLen = dx * dx1 + dy * dy1;
  22352. var t = projectedLen / lineLen;
  22353. if (limitToEnds) {
  22354. t = Math.min(Math.max(t, 0), 1);
  22355. }
  22356. t *= lineLen;
  22357. var ox = out[0] = x1 + t * dx1;
  22358. var oy = out[1] = y1 + t * dy1;
  22359. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  22360. }
  22361. function projectPointToRect(x1, y1, width, height, x, y, out) {
  22362. if (width < 0) {
  22363. x1 = x1 + width;
  22364. width = -width;
  22365. }
  22366. if (height < 0) {
  22367. y1 = y1 + height;
  22368. height = -height;
  22369. }
  22370. var x2 = x1 + width;
  22371. var y2 = y1 + height;
  22372. var ox = out[0] = Math.min(Math.max(x, x1), x2);
  22373. var oy = out[1] = Math.min(Math.max(y, y1), y2);
  22374. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  22375. }
  22376. var tmpPt = [];
  22377. function nearestPointOnRect(pt, rect, out) {
  22378. var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt);
  22379. out.set(tmpPt[0], tmpPt[1]);
  22380. return dist;
  22381. }
  22382. /**
  22383. * Calculate min distance corresponding point.
  22384. * This method won't evaluate if point is in the path.
  22385. */
  22386. function nearestPointOnPath(pt, path, out) {
  22387. var xi = 0;
  22388. var yi = 0;
  22389. var x0 = 0;
  22390. var y0 = 0;
  22391. var x1;
  22392. var y1;
  22393. var minDist = Infinity;
  22394. var data = path.data;
  22395. var x = pt.x;
  22396. var y = pt.y;
  22397. for (var i = 0; i < data.length;) {
  22398. var cmd = data[i++];
  22399. if (i === 1) {
  22400. xi = data[i];
  22401. yi = data[i + 1];
  22402. x0 = xi;
  22403. y0 = yi;
  22404. }
  22405. var d = minDist;
  22406. switch (cmd) {
  22407. case CMD$3.M:
  22408. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  22409. // 在 closePath 的时候使用
  22410. x0 = data[i++];
  22411. y0 = data[i++];
  22412. xi = x0;
  22413. yi = y0;
  22414. break;
  22415. case CMD$3.L:
  22416. d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, true);
  22417. xi = data[i++];
  22418. yi = data[i++];
  22419. break;
  22420. case CMD$3.C:
  22421. d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  22422. xi = data[i++];
  22423. yi = data[i++];
  22424. break;
  22425. case CMD$3.Q:
  22426. d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  22427. xi = data[i++];
  22428. yi = data[i++];
  22429. break;
  22430. case CMD$3.A:
  22431. // TODO Arc 判断的开销比较大
  22432. var cx = data[i++];
  22433. var cy = data[i++];
  22434. var rx = data[i++];
  22435. var ry = data[i++];
  22436. var theta = data[i++];
  22437. var dTheta = data[i++]; // TODO Arc 旋转
  22438. i += 1;
  22439. var anticlockwise = !!(1 - data[i++]);
  22440. x1 = Math.cos(theta) * rx + cx;
  22441. y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  22442. if (i <= 1) {
  22443. // 第一个命令起点还未定义
  22444. x0 = x1;
  22445. y0 = y1;
  22446. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  22447. var _x = (x - cx) * ry / rx + cx;
  22448. d = projectPointToArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt);
  22449. xi = Math.cos(theta + dTheta) * rx + cx;
  22450. yi = Math.sin(theta + dTheta) * ry + cy;
  22451. break;
  22452. case CMD$3.R:
  22453. x0 = xi = data[i++];
  22454. y0 = yi = data[i++];
  22455. var width = data[i++];
  22456. var height = data[i++];
  22457. d = projectPointToRect(x0, y0, width, height, x, y, tmpPt);
  22458. break;
  22459. case CMD$3.Z:
  22460. d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, true);
  22461. xi = x0;
  22462. yi = y0;
  22463. break;
  22464. }
  22465. if (d < minDist) {
  22466. minDist = d;
  22467. out.set(tmpPt[0], tmpPt[1]);
  22468. }
  22469. }
  22470. return minDist;
  22471. } // Temporal varible for intermediate usage.
  22472. var pt0 = new Point();
  22473. var pt1 = new Point();
  22474. var pt2 = new Point();
  22475. var dir = new Point();
  22476. var dir2 = new Point();
  22477. /**
  22478. * Calculate a proper guide line based on the label position and graphic element definition
  22479. * @param label
  22480. * @param labelRect
  22481. * @param target
  22482. * @param targetRect
  22483. */
  22484. function updateLabelLinePoints(target, labelLineModel) {
  22485. if (!target) {
  22486. return;
  22487. }
  22488. var labelLine = target.getTextGuideLine();
  22489. var label = target.getTextContent(); // Needs to create text guide in each charts.
  22490. if (!(label && labelLine)) {
  22491. return;
  22492. }
  22493. var labelGuideConfig = target.textGuideLineConfig || {};
  22494. var points = [[0, 0], [0, 0], [0, 0]];
  22495. var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;
  22496. var labelRect = label.getBoundingRect().clone();
  22497. labelRect.applyTransform(label.getComputedTransform());
  22498. var minDist = Infinity;
  22499. var anchorPoint = labelGuideConfig.anchor;
  22500. var targetTransform = target.getComputedTransform();
  22501. var targetInversedTransform = targetTransform && invert([], targetTransform);
  22502. var len = labelLineModel.get('length2') || 0;
  22503. if (anchorPoint) {
  22504. pt2.copy(anchorPoint);
  22505. }
  22506. for (var i = 0; i < searchSpace.length; i++) {
  22507. var candidate = searchSpace[i];
  22508. getCandidateAnchor(candidate, 0, labelRect, pt0, dir);
  22509. Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.
  22510. pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.
  22511. var boundingRect = target.getBoundingRect();
  22512. var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path
  22513. if (dist < minDist) {
  22514. minDist = dist; // Transform back to global space.
  22515. pt1.transform(targetTransform);
  22516. pt2.transform(targetTransform);
  22517. pt2.toArray(points[0]);
  22518. pt1.toArray(points[1]);
  22519. pt0.toArray(points[2]);
  22520. }
  22521. }
  22522. limitTurnAngle(points, labelLineModel.get('minTurnAngle'));
  22523. labelLine.setShape({
  22524. points: points
  22525. });
  22526. } // Temporal variable for the limitTurnAngle function
  22527. var tmpArr = [];
  22528. var tmpProjPoint = new Point();
  22529. /**
  22530. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  22531. * @param linePoints
  22532. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  22533. */
  22534. function limitTurnAngle(linePoints, minTurnAngle) {
  22535. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  22536. return;
  22537. }
  22538. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  22539. // /pt1----pt2 (label)
  22540. // /
  22541. // pt0/
  22542. pt0.fromArray(linePoints[0]);
  22543. pt1.fromArray(linePoints[1]);
  22544. pt2.fromArray(linePoints[2]);
  22545. Point.sub(dir, pt0, pt1);
  22546. Point.sub(dir2, pt2, pt1);
  22547. var len1 = dir.len();
  22548. var len2 = dir2.len();
  22549. if (len1 < 1e-3 || len2 < 1e-3) {
  22550. return;
  22551. }
  22552. dir.scale(1 / len1);
  22553. dir2.scale(1 / len2);
  22554. var angleCos = dir.dot(dir2);
  22555. var minTurnAngleCos = Math.cos(minTurnAngle);
  22556. if (minTurnAngleCos < angleCos) {
  22557. // Smaller than minTurnAngle
  22558. // Calculate project point of pt0 on pt1-pt2
  22559. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  22560. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  22561. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  22562. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  22563. if (isNaN(t)) {
  22564. return;
  22565. }
  22566. if (t < 0) {
  22567. Point.copy(tmpProjPoint, pt1);
  22568. } else if (t > 1) {
  22569. Point.copy(tmpProjPoint, pt2);
  22570. }
  22571. tmpProjPoint.toArray(linePoints[1]);
  22572. }
  22573. }
  22574. /**
  22575. * Limit the angle of line and the surface
  22576. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  22577. */
  22578. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  22579. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  22580. return;
  22581. }
  22582. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  22583. pt0.fromArray(linePoints[0]);
  22584. pt1.fromArray(linePoints[1]);
  22585. pt2.fromArray(linePoints[2]);
  22586. Point.sub(dir, pt1, pt0);
  22587. Point.sub(dir2, pt2, pt1);
  22588. var len1 = dir.len();
  22589. var len2 = dir2.len();
  22590. if (len1 < 1e-3 || len2 < 1e-3) {
  22591. return;
  22592. }
  22593. dir.scale(1 / len1);
  22594. dir2.scale(1 / len2);
  22595. var angleCos = dir.dot(surfaceNormal);
  22596. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  22597. if (angleCos < maxSurfaceAngleCos) {
  22598. // Calculate project point of pt0 on pt1-pt2
  22599. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  22600. tmpProjPoint.fromArray(tmpArr);
  22601. var HALF_PI = Math.PI / 2;
  22602. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  22603. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  22604. if (newAngle >= HALF_PI) {
  22605. // parallel
  22606. Point.copy(tmpProjPoint, pt2);
  22607. } else {
  22608. // Calculate new projected length with limited minTurnAngle and get the new connect point
  22609. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  22610. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  22611. if (isNaN(t)) {
  22612. return;
  22613. }
  22614. if (t < 0) {
  22615. Point.copy(tmpProjPoint, pt1);
  22616. } else if (t > 1) {
  22617. Point.copy(tmpProjPoint, pt2);
  22618. }
  22619. }
  22620. tmpProjPoint.toArray(linePoints[1]);
  22621. }
  22622. }
  22623. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  22624. var isNormal = stateName === 'normal';
  22625. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  22626. stateObj.ignore = ignore; // Set smooth
  22627. var smooth = stateModel.get('smooth');
  22628. if (smooth && smooth === true) {
  22629. smooth = 0.3;
  22630. }
  22631. stateObj.shape = stateObj.shape || {};
  22632. if (smooth > 0) {
  22633. stateObj.shape.smooth = smooth;
  22634. }
  22635. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  22636. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  22637. }
  22638. function buildLabelLinePath(path, shape) {
  22639. var smooth = shape.smooth;
  22640. var points = shape.points;
  22641. if (!points) {
  22642. return;
  22643. }
  22644. path.moveTo(points[0][0], points[0][1]);
  22645. if (smooth > 0 && points.length >= 3) {
  22646. var len1 = dist(points[0], points[1]);
  22647. var len2 = dist(points[1], points[2]);
  22648. if (!len1 || !len2) {
  22649. path.lineTo(points[1][0], points[1][1]);
  22650. path.lineTo(points[2][0], points[2][1]);
  22651. return;
  22652. }
  22653. var moveLen = Math.min(len1, len2) * smooth;
  22654. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  22655. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  22656. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  22657. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  22658. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  22659. } else {
  22660. for (var i = 1; i < points.length; i++) {
  22661. path.lineTo(points[i][0], points[i][1]);
  22662. }
  22663. }
  22664. }
  22665. /**
  22666. * Create a label line if necessary and set it's style.
  22667. */
  22668. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  22669. var labelLine = targetEl.getTextGuideLine();
  22670. var label = targetEl.getTextContent();
  22671. if (!label) {
  22672. // Not show label line if there is no label.
  22673. if (labelLine) {
  22674. targetEl.removeTextGuideLine();
  22675. }
  22676. return;
  22677. }
  22678. var normalModel = statesModels.normal;
  22679. var showNormal = normalModel.get('show');
  22680. var labelIgnoreNormal = label.ignore;
  22681. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  22682. var stateName = DISPLAY_STATES[i];
  22683. var stateModel = statesModels[stateName];
  22684. var isNormal = stateName === 'normal';
  22685. if (stateModel) {
  22686. var stateShow = stateModel.get('show');
  22687. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  22688. if (isLabelIgnored // Not show when label is not shown in this state.
  22689. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  22690. ) {
  22691. var stateObj = isNormal ? labelLine : labelLine && labelLine.states.normal;
  22692. if (stateObj) {
  22693. stateObj.ignore = true;
  22694. }
  22695. continue;
  22696. } // Create labelLine if not exists
  22697. if (!labelLine) {
  22698. labelLine = new Polyline();
  22699. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  22700. // NOTE: NORMAL should always been the first!
  22701. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  22702. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  22703. } // Use same state proxy.
  22704. if (targetEl.stateProxy) {
  22705. labelLine.stateProxy = targetEl.stateProxy;
  22706. }
  22707. }
  22708. setLabelLineState(labelLine, false, stateName, stateModel);
  22709. }
  22710. }
  22711. if (labelLine) {
  22712. defaults(labelLine.style, defaultStyle); // Not fill.
  22713. labelLine.style.fill = null;
  22714. var showAbove = normalModel.get('showAbove');
  22715. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  22716. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  22717. labelLine.buildPath = buildLabelLinePath;
  22718. }
  22719. }
  22720. function getLabelLineStatesModels(itemModel, labelLineName) {
  22721. labelLineName = labelLineName || 'labelLine';
  22722. var statesModels = {
  22723. normal: itemModel.getModel(labelLineName)
  22724. };
  22725. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  22726. var stateName = SPECIAL_STATES[i];
  22727. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  22728. }
  22729. return statesModels;
  22730. }
  22731. function prepareLayoutList(input) {
  22732. var list = [];
  22733. for (var i = 0; i < input.length; i++) {
  22734. var rawItem = input[i];
  22735. if (rawItem.defaultAttr.ignore) {
  22736. continue;
  22737. }
  22738. var label = rawItem.label;
  22739. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  22740. var localRect = label.getBoundingRect();
  22741. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  22742. var minMargin = label.style.margin || 0;
  22743. var globalRect = localRect.clone();
  22744. globalRect.applyTransform(transform);
  22745. globalRect.x -= minMargin / 2;
  22746. globalRect.y -= minMargin / 2;
  22747. globalRect.width += minMargin;
  22748. globalRect.height += minMargin;
  22749. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  22750. list.push({
  22751. label: label,
  22752. labelLine: rawItem.labelLine,
  22753. rect: globalRect,
  22754. localRect: localRect,
  22755. obb: obb,
  22756. priority: rawItem.priority,
  22757. defaultAttr: rawItem.defaultAttr,
  22758. layoutOption: rawItem.computedLayoutOption,
  22759. axisAligned: isAxisAligned,
  22760. transform: transform
  22761. });
  22762. }
  22763. return list;
  22764. }
  22765. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  22766. var len = list.length;
  22767. if (len < 2) {
  22768. return;
  22769. }
  22770. list.sort(function (a, b) {
  22771. return a.rect[xyDim] - b.rect[xyDim];
  22772. });
  22773. var lastPos = 0;
  22774. var delta;
  22775. var adjusted = false;
  22776. var totalShifts = 0;
  22777. for (var i = 0; i < len; i++) {
  22778. var item = list[i];
  22779. var rect = item.rect;
  22780. delta = rect[xyDim] - lastPos;
  22781. if (delta < 0) {
  22782. // shiftForward(i, len, -delta);
  22783. rect[xyDim] -= delta;
  22784. item.label[xyDim] -= delta;
  22785. adjusted = true;
  22786. }
  22787. var shift = Math.max(-delta, 0);
  22788. totalShifts += shift;
  22789. lastPos = rect[xyDim] + rect[sizeDim];
  22790. }
  22791. if (totalShifts > 0 && balanceShift) {
  22792. // Shift back to make the distribution more equally.
  22793. shiftList(-totalShifts / len, 0, len);
  22794. } // TODO bleedMargin?
  22795. var first = list[0];
  22796. var last = list[len - 1];
  22797. var minGap;
  22798. var maxGap;
  22799. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  22800. minGap < 0 && squeezeGaps(-minGap, 0.8);
  22801. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  22802. updateMinMaxGap();
  22803. takeBoundsGap(minGap, maxGap, 1);
  22804. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  22805. updateMinMaxGap();
  22806. if (minGap < 0) {
  22807. squeezeWhenBailout(-minGap);
  22808. }
  22809. if (maxGap < 0) {
  22810. squeezeWhenBailout(maxGap);
  22811. }
  22812. function updateMinMaxGap() {
  22813. minGap = first.rect[xyDim] - minBound;
  22814. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  22815. }
  22816. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  22817. if (gapThisBound < 0) {
  22818. // Move from other gap if can.
  22819. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  22820. if (moveFromMaxGap > 0) {
  22821. shiftList(moveFromMaxGap * moveDir, 0, len);
  22822. var remained = moveFromMaxGap + gapThisBound;
  22823. if (remained < 0) {
  22824. squeezeGaps(-remained * moveDir, 1);
  22825. }
  22826. } else {
  22827. squeezeGaps(-gapThisBound * moveDir, 1);
  22828. }
  22829. }
  22830. }
  22831. function shiftList(delta, start, end) {
  22832. if (delta !== 0) {
  22833. adjusted = true;
  22834. }
  22835. for (var i = start; i < end; i++) {
  22836. var item = list[i];
  22837. var rect = item.rect;
  22838. rect[xyDim] += delta;
  22839. item.label[xyDim] += delta;
  22840. }
  22841. } // Squeeze gaps if the labels exceed margin.
  22842. function squeezeGaps(delta, maxSqeezePercent) {
  22843. var gaps = [];
  22844. var totalGaps = 0;
  22845. for (var i = 1; i < len; i++) {
  22846. var prevItemRect = list[i - 1].rect;
  22847. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  22848. gaps.push(gap);
  22849. totalGaps += gap;
  22850. }
  22851. if (!totalGaps) {
  22852. return;
  22853. }
  22854. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  22855. if (delta > 0) {
  22856. for (var i = 0; i < len - 1; i++) {
  22857. // Distribute the shift delta to all gaps.
  22858. var movement = gaps[i] * squeezePercent; // Forward
  22859. shiftList(movement, 0, i + 1);
  22860. }
  22861. } else {
  22862. // Backward
  22863. for (var i = len - 1; i > 0; i--) {
  22864. // Distribute the shift delta to all gaps.
  22865. var movement = gaps[i - 1] * squeezePercent;
  22866. shiftList(-movement, i, len);
  22867. }
  22868. }
  22869. }
  22870. /**
  22871. * Squeeze to allow overlap if there is no more space available.
  22872. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  22873. */
  22874. function squeezeWhenBailout(delta) {
  22875. var dir = delta < 0 ? -1 : 1;
  22876. delta = Math.abs(delta);
  22877. var moveForEachLabel = Math.ceil(delta / (len - 1));
  22878. for (var i = 0; i < len - 1; i++) {
  22879. if (dir > 0) {
  22880. // Forward
  22881. shiftList(moveForEachLabel, 0, i + 1);
  22882. } else {
  22883. // Backward
  22884. shiftList(-moveForEachLabel, len - i - 1, len);
  22885. }
  22886. delta -= moveForEachLabel;
  22887. if (delta <= 0) {
  22888. return;
  22889. }
  22890. }
  22891. }
  22892. return adjusted;
  22893. }
  22894. /**
  22895. * Adjust labels on x direction to avoid overlap.
  22896. */
  22897. function shiftLayoutOnX(list, leftBound, rightBound, // If average the shifts on all labels and add them to 0
  22898. // TODO: Not sure if should enable it.
  22899. // Pros: The angle of lines will distribute more equally
  22900. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  22901. balanceShift) {
  22902. return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift);
  22903. }
  22904. /**
  22905. * Adjust labels on y direction to avoid overlap.
  22906. */
  22907. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  22908. balanceShift) {
  22909. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  22910. }
  22911. function hideOverlap(labelList) {
  22912. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  22913. labelList.sort(function (a, b) {
  22914. return b.priority - a.priority;
  22915. });
  22916. var globalRect = new BoundingRect(0, 0, 0, 0);
  22917. function hideEl(el) {
  22918. if (!el.ignore) {
  22919. // Show on emphasis.
  22920. var emphasisState = el.ensureState('emphasis');
  22921. if (emphasisState.ignore == null) {
  22922. emphasisState.ignore = false;
  22923. }
  22924. }
  22925. el.ignore = true;
  22926. }
  22927. for (var i = 0; i < labelList.length; i++) {
  22928. var labelItem = labelList[i];
  22929. var isAxisAligned = labelItem.axisAligned;
  22930. var localRect = labelItem.localRect;
  22931. var transform = labelItem.transform;
  22932. var label = labelItem.label;
  22933. var labelLine = labelItem.labelLine;
  22934. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  22935. globalRect.width -= 0.1;
  22936. globalRect.height -= 0.1;
  22937. globalRect.x += 0.05;
  22938. globalRect.y += 0.05;
  22939. var obb = labelItem.obb;
  22940. var overlapped = false;
  22941. for (var j = 0; j < displayedLabels.length; j++) {
  22942. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  22943. if (!globalRect.intersect(existsTextCfg.rect)) {
  22944. continue;
  22945. }
  22946. if (isAxisAligned && existsTextCfg.axisAligned) {
  22947. // Is overlapped
  22948. overlapped = true;
  22949. break;
  22950. }
  22951. if (!existsTextCfg.obb) {
  22952. // If self is not axis aligned. But other is.
  22953. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  22954. }
  22955. if (!obb) {
  22956. // If self is axis aligned. But other is not.
  22957. obb = new OrientedBoundingRect(localRect, transform);
  22958. }
  22959. if (obb.intersect(existsTextCfg.obb)) {
  22960. overlapped = true;
  22961. break;
  22962. }
  22963. } // TODO Callback to determine if this overlap should be handled?
  22964. if (overlapped) {
  22965. hideEl(label);
  22966. labelLine && hideEl(labelLine);
  22967. } else {
  22968. label.attr('ignore', labelItem.defaultAttr.ignore);
  22969. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  22970. displayedLabels.push(labelItem);
  22971. }
  22972. }
  22973. }
  22974. function cloneArr(points) {
  22975. if (points) {
  22976. var newPoints = [];
  22977. for (var i = 0; i < points.length; i++) {
  22978. newPoints.push(points[i].slice());
  22979. }
  22980. return newPoints;
  22981. }
  22982. }
  22983. function prepareLayoutCallbackParams(labelItem, hostEl) {
  22984. var label = labelItem.label;
  22985. var labelLine = hostEl && hostEl.getTextGuideLine();
  22986. return {
  22987. dataIndex: labelItem.dataIndex,
  22988. dataType: labelItem.dataType,
  22989. seriesIndex: labelItem.seriesModel.seriesIndex,
  22990. text: labelItem.label.style.text,
  22991. rect: labelItem.hostRect,
  22992. labelRect: labelItem.rect,
  22993. // x: labelAttr.x,
  22994. // y: labelAttr.y,
  22995. align: label.style.align,
  22996. verticalAlign: label.style.verticalAlign,
  22997. labelLinePoints: cloneArr(labelLine && labelLine.shape.points)
  22998. };
  22999. }
  23000. var LABEL_OPTION_TO_STYLE_KEYS = ['align', 'verticalAlign', 'width', 'height', 'fontSize'];
  23001. var dummyTransformable = new Transformable();
  23002. var labelLayoutInnerStore = makeInner();
  23003. var labelLineAnimationStore = makeInner();
  23004. function extendWithKeys(target, source, keys) {
  23005. for (var i = 0; i < keys.length; i++) {
  23006. var key = keys[i];
  23007. if (source[key] != null) {
  23008. target[key] = source[key];
  23009. }
  23010. }
  23011. }
  23012. var LABEL_LAYOUT_PROPS = ['x', 'y', 'rotation'];
  23013. var LabelManager =
  23014. /** @class */
  23015. function () {
  23016. function LabelManager() {
  23017. this._labelList = [];
  23018. this._chartViewList = [];
  23019. }
  23020. LabelManager.prototype.clearLabels = function () {
  23021. this._labelList = [];
  23022. this._chartViewList = [];
  23023. };
  23024. /**
  23025. * Add label to manager
  23026. */
  23027. LabelManager.prototype._addLabel = function (dataIndex, dataType, seriesModel, label, layoutOption) {
  23028. var labelStyle = label.style;
  23029. var hostEl = label.__hostTarget;
  23030. var textConfig = hostEl.textConfig || {}; // TODO: If label is in other state.
  23031. var labelTransform = label.getComputedTransform();
  23032. var labelRect = label.getBoundingRect().plain();
  23033. BoundingRect.applyTransform(labelRect, labelRect, labelTransform);
  23034. if (labelTransform) {
  23035. dummyTransformable.setLocalTransform(labelTransform);
  23036. } else {
  23037. // Identity transform.
  23038. dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0;
  23039. dummyTransformable.scaleX = dummyTransformable.scaleY = 1;
  23040. }
  23041. var host = label.__hostTarget;
  23042. var hostRect;
  23043. if (host) {
  23044. hostRect = host.getBoundingRect().plain();
  23045. var transform = host.getComputedTransform();
  23046. BoundingRect.applyTransform(hostRect, hostRect, transform);
  23047. }
  23048. var labelGuide = hostRect && host.getTextGuideLine();
  23049. this._labelList.push({
  23050. label: label,
  23051. labelLine: labelGuide,
  23052. seriesModel: seriesModel,
  23053. dataIndex: dataIndex,
  23054. dataType: dataType,
  23055. layoutOption: layoutOption,
  23056. computedLayoutOption: null,
  23057. rect: labelRect,
  23058. hostRect: hostRect,
  23059. // Label with lower priority will be hidden when overlapped
  23060. // Use rect size as default priority
  23061. priority: hostRect ? hostRect.width * hostRect.height : 0,
  23062. // Save default label attributes.
  23063. // For restore if developers want get back to default value in callback.
  23064. defaultAttr: {
  23065. ignore: label.ignore,
  23066. labelGuideIgnore: labelGuide && labelGuide.ignore,
  23067. x: dummyTransformable.x,
  23068. y: dummyTransformable.y,
  23069. rotation: dummyTransformable.rotation,
  23070. style: {
  23071. x: labelStyle.x,
  23072. y: labelStyle.y,
  23073. align: labelStyle.align,
  23074. verticalAlign: labelStyle.verticalAlign,
  23075. width: labelStyle.width,
  23076. height: labelStyle.height,
  23077. fontSize: labelStyle.fontSize
  23078. },
  23079. cursor: label.cursor,
  23080. attachedPos: textConfig.position,
  23081. attachedRot: textConfig.rotation
  23082. }
  23083. });
  23084. };
  23085. LabelManager.prototype.addLabelsOfSeries = function (chartView) {
  23086. var _this = this;
  23087. this._chartViewList.push(chartView);
  23088. var seriesModel = chartView.__model;
  23089. var layoutOption = seriesModel.get('labelLayout');
  23090. /**
  23091. * Ignore layouting if it's not specified anything.
  23092. */
  23093. if (!(isFunction(layoutOption) || keys(layoutOption).length)) {
  23094. return;
  23095. }
  23096. chartView.group.traverse(function (child) {
  23097. if (child.ignore) {
  23098. return true; // Stop traverse descendants.
  23099. } // Only support label being hosted on graphic elements.
  23100. var textEl = child.getTextContent();
  23101. var ecData = getECData(child); // Can only attach the text on the element with dataIndex
  23102. if (textEl && !textEl.disableLabelLayout) {
  23103. _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption);
  23104. }
  23105. });
  23106. };
  23107. LabelManager.prototype.updateLayoutConfig = function (api) {
  23108. var width = api.getWidth();
  23109. var height = api.getHeight();
  23110. function createDragHandler(el, labelLineModel) {
  23111. return function () {
  23112. updateLabelLinePoints(el, labelLineModel);
  23113. };
  23114. }
  23115. for (var i = 0; i < this._labelList.length; i++) {
  23116. var labelItem = this._labelList[i];
  23117. var label = labelItem.label;
  23118. var hostEl = label.__hostTarget;
  23119. var defaultLabelAttr = labelItem.defaultAttr;
  23120. var layoutOption = void 0; // TODO A global layout option?
  23121. if (typeof labelItem.layoutOption === 'function') {
  23122. layoutOption = labelItem.layoutOption(prepareLayoutCallbackParams(labelItem, hostEl));
  23123. } else {
  23124. layoutOption = labelItem.layoutOption;
  23125. }
  23126. layoutOption = layoutOption || {};
  23127. labelItem.computedLayoutOption = layoutOption;
  23128. var degreeToRadian = Math.PI / 180;
  23129. if (hostEl) {
  23130. hostEl.setTextConfig({
  23131. // Force to set local false.
  23132. local: false,
  23133. // Ignore position and rotation config on the host el if x or y is changed.
  23134. position: layoutOption.x != null || layoutOption.y != null ? null : defaultLabelAttr.attachedPos,
  23135. // Ignore rotation config on the host el if rotation is changed.
  23136. rotation: layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot,
  23137. offset: [layoutOption.dx || 0, layoutOption.dy || 0]
  23138. });
  23139. }
  23140. var needsUpdateLabelLine = false;
  23141. if (layoutOption.x != null) {
  23142. // TODO width of chart view.
  23143. label.x = parsePercent$1(layoutOption.x, width);
  23144. label.setStyle('x', 0); // Ignore movement in style. TODO: origin.
  23145. needsUpdateLabelLine = true;
  23146. } else {
  23147. label.x = defaultLabelAttr.x;
  23148. label.setStyle('x', defaultLabelAttr.style.x);
  23149. }
  23150. if (layoutOption.y != null) {
  23151. // TODO height of chart view.
  23152. label.y = parsePercent$1(layoutOption.y, height);
  23153. label.setStyle('y', 0); // Ignore movement in style.
  23154. needsUpdateLabelLine = true;
  23155. } else {
  23156. label.y = defaultLabelAttr.y;
  23157. label.setStyle('y', defaultLabelAttr.style.y);
  23158. }
  23159. if (layoutOption.labelLinePoints) {
  23160. var guideLine = hostEl.getTextGuideLine();
  23161. if (guideLine) {
  23162. guideLine.setShape({
  23163. points: layoutOption.labelLinePoints
  23164. }); // Not update
  23165. needsUpdateLabelLine = false;
  23166. }
  23167. }
  23168. var labelLayoutStore = labelLayoutInnerStore(label);
  23169. labelLayoutStore.needsUpdateLabelLine = needsUpdateLabelLine;
  23170. label.rotation = layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation;
  23171. for (var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++) {
  23172. var key = LABEL_OPTION_TO_STYLE_KEYS[k];
  23173. label.setStyle(key, layoutOption[key] != null ? layoutOption[key] : defaultLabelAttr.style[key]);
  23174. }
  23175. if (layoutOption.draggable) {
  23176. label.draggable = true;
  23177. label.cursor = 'move';
  23178. if (hostEl) {
  23179. var hostModel = labelItem.seriesModel;
  23180. if (labelItem.dataIndex != null) {
  23181. var data = labelItem.seriesModel.getData(labelItem.dataType);
  23182. hostModel = data.getItemModel(labelItem.dataIndex);
  23183. }
  23184. label.on('drag', createDragHandler(hostEl, hostModel.getModel('labelLine')));
  23185. }
  23186. } else {
  23187. // TODO Other drag functions?
  23188. label.off('drag');
  23189. label.cursor = defaultLabelAttr.cursor;
  23190. }
  23191. }
  23192. };
  23193. LabelManager.prototype.layout = function (api) {
  23194. var width = api.getWidth();
  23195. var height = api.getHeight();
  23196. var labelList = prepareLayoutList(this._labelList);
  23197. var labelsNeedsAdjustOnX = filter(labelList, function (item) {
  23198. return item.layoutOption.moveOverlap === 'shiftX';
  23199. });
  23200. var labelsNeedsAdjustOnY = filter(labelList, function (item) {
  23201. return item.layoutOption.moveOverlap === 'shiftY';
  23202. });
  23203. shiftLayoutOnX(labelsNeedsAdjustOnX, 0, width);
  23204. shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height);
  23205. var labelsNeedsHideOverlap = filter(labelList, function (item) {
  23206. return item.layoutOption.hideOverlap;
  23207. });
  23208. hideOverlap(labelsNeedsHideOverlap);
  23209. };
  23210. /**
  23211. * Process all labels. Not only labels with layoutOption.
  23212. */
  23213. LabelManager.prototype.processLabelsOverall = function () {
  23214. var _this = this;
  23215. each(this._chartViewList, function (chartView) {
  23216. var seriesModel = chartView.__model;
  23217. var ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate;
  23218. var animationEnabled = seriesModel.isAnimationEnabled();
  23219. chartView.group.traverse(function (child) {
  23220. if (child.ignore) {
  23221. return true; // Stop traverse descendants.
  23222. }
  23223. var needsUpdateLabelLine = !ignoreLabelLineUpdate;
  23224. var label = child.getTextContent();
  23225. if (!needsUpdateLabelLine && label) {
  23226. needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine;
  23227. }
  23228. if (needsUpdateLabelLine) {
  23229. _this._updateLabelLine(child, seriesModel);
  23230. }
  23231. if (animationEnabled) {
  23232. _this._animateLabels(child, seriesModel);
  23233. }
  23234. });
  23235. });
  23236. };
  23237. LabelManager.prototype._updateLabelLine = function (el, seriesModel) {
  23238. // Only support label being hosted on graphic elements.
  23239. var textEl = el.getTextContent(); // Update label line style.
  23240. var ecData = getECData(el);
  23241. var dataIndex = ecData.dataIndex; // Only support labelLine on the labels represent data.
  23242. if (textEl && dataIndex != null) {
  23243. var data = seriesModel.getData(ecData.dataType);
  23244. var itemModel = data.getItemModel(dataIndex);
  23245. var defaultStyle = {};
  23246. var visualStyle = data.getItemVisual(dataIndex, 'style');
  23247. var visualType = data.getVisual('drawType'); // Default to be same with main color
  23248. defaultStyle.stroke = visualStyle[visualType];
  23249. var labelLineModel = itemModel.getModel('labelLine');
  23250. setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle);
  23251. updateLabelLinePoints(el, labelLineModel);
  23252. }
  23253. };
  23254. LabelManager.prototype._animateLabels = function (el, seriesModel) {
  23255. var textEl = el.getTextContent();
  23256. var guideLine = el.getTextGuideLine(); // Animate
  23257. if (textEl && !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el)) {
  23258. var layoutStore = labelLayoutInnerStore(textEl);
  23259. var oldLayout = layoutStore.oldLayout;
  23260. var ecData = getECData(el);
  23261. var dataIndex = ecData.dataIndex;
  23262. var newProps = {
  23263. x: textEl.x,
  23264. y: textEl.y,
  23265. rotation: textEl.rotation
  23266. };
  23267. var data = seriesModel.getData(ecData.dataType);
  23268. if (!oldLayout) {
  23269. textEl.attr(newProps); // Disable fade in animation if value animation is enabled.
  23270. if (!labelInner(textEl).valueAnimation) {
  23271. var oldOpacity = retrieve2(textEl.style.opacity, 1); // Fade in animation
  23272. textEl.style.opacity = 0;
  23273. initProps(textEl, {
  23274. style: {
  23275. opacity: oldOpacity
  23276. }
  23277. }, seriesModel, dataIndex);
  23278. }
  23279. } else {
  23280. textEl.attr(oldLayout); // Make sure the animation from is in the right status.
  23281. var prevStates = el.prevStates;
  23282. if (prevStates) {
  23283. if (indexOf(prevStates, 'select') >= 0) {
  23284. textEl.attr(layoutStore.oldLayoutSelect);
  23285. }
  23286. if (indexOf(prevStates, 'emphasis') >= 0) {
  23287. textEl.attr(layoutStore.oldLayoutEmphasis);
  23288. }
  23289. }
  23290. updateProps(textEl, newProps, seriesModel, dataIndex);
  23291. }
  23292. layoutStore.oldLayout = newProps;
  23293. if (textEl.states.select) {
  23294. var layoutSelect = layoutStore.oldLayoutSelect = {};
  23295. extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS);
  23296. extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS);
  23297. }
  23298. if (textEl.states.emphasis) {
  23299. var layoutEmphasis = layoutStore.oldLayoutEmphasis = {};
  23300. extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS);
  23301. extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS);
  23302. }
  23303. animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel);
  23304. }
  23305. if (guideLine && !guideLine.ignore && !guideLine.invisible) {
  23306. var layoutStore = labelLineAnimationStore(guideLine);
  23307. var oldLayout = layoutStore.oldLayout;
  23308. var newLayout = {
  23309. points: guideLine.shape.points
  23310. };
  23311. if (!oldLayout) {
  23312. guideLine.setShape(newLayout);
  23313. guideLine.style.strokePercent = 0;
  23314. initProps(guideLine, {
  23315. style: {
  23316. strokePercent: 1
  23317. }
  23318. }, seriesModel);
  23319. } else {
  23320. guideLine.attr({
  23321. shape: oldLayout
  23322. });
  23323. updateProps(guideLine, {
  23324. shape: newLayout
  23325. }, seriesModel);
  23326. }
  23327. layoutStore.oldLayout = newLayout;
  23328. }
  23329. };
  23330. return LabelManager;
  23331. }();
  23332. // Inlucdes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  23333. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  23334. function getSeriesIndices(ecModel, payload) {
  23335. var seriesIndices = [];
  23336. ecModel.eachComponent({
  23337. mainType: 'series',
  23338. subType: seriesType,
  23339. query: payload
  23340. }, function (seriesModel) {
  23341. seriesIndices.push(seriesModel.seriesIndex);
  23342. });
  23343. return seriesIndices;
  23344. }
  23345. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  23346. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  23347. payload = extend({}, payload);
  23348. if ("development" !== 'production') {
  23349. deprecateReplaceLog(payload.type, eventsMap[1]);
  23350. }
  23351. api.dispatchAction(extend(payload, {
  23352. type: eventsMap[1],
  23353. seriesIndex: getSeriesIndices(ecModel, payload)
  23354. }));
  23355. });
  23356. });
  23357. }
  23358. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  23359. var legacyEventName = type + eventPostfix;
  23360. if (!ecIns.isSilent(legacyEventName)) {
  23361. if ("development" !== 'production') {
  23362. deprecateLog("event " + legacyEventName + " is deprecated.");
  23363. }
  23364. ecModel.eachComponent({
  23365. mainType: 'series',
  23366. subType: 'pie'
  23367. }, function (seriesModel) {
  23368. var seriesIndex = seriesModel.seriesIndex;
  23369. var selected = payload.selected;
  23370. for (var i = 0; i < selected.length; i++) {
  23371. if (selected[i].seriesIndex === seriesIndex) {
  23372. var data = seriesModel.getData();
  23373. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  23374. ecIns.trigger(legacyEventName, {
  23375. type: legacyEventName,
  23376. seriesId: seriesModel.id,
  23377. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  23378. selected: extend({}, seriesModel.option.selectedMap)
  23379. });
  23380. }
  23381. }
  23382. });
  23383. }
  23384. }
  23385. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  23386. messageCenter.on('selectchanged', function (params) {
  23387. var ecModel = api.getModel();
  23388. if (params.isFromClick) {
  23389. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  23390. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  23391. } else if (params.fromAction === 'select') {
  23392. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  23393. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  23394. } else if (params.fromAction === 'unselect') {
  23395. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  23396. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  23397. }
  23398. });
  23399. }
  23400. /*
  23401. * Licensed to the Apache Software Foundation (ASF) under one
  23402. * or more contributor license agreements. See the NOTICE file
  23403. * distributed with this work for additional information
  23404. * regarding copyright ownership. The ASF licenses this file
  23405. * to you under the Apache License, Version 2.0 (the
  23406. * "License"); you may not use this file except in compliance
  23407. * with the License. You may obtain a copy of the License at
  23408. *
  23409. * http://www.apache.org/licenses/LICENSE-2.0
  23410. *
  23411. * Unless required by applicable law or agreed to in writing,
  23412. * software distributed under the License is distributed on an
  23413. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23414. * KIND, either express or implied. See the License for the
  23415. * specific language governing permissions and limitations
  23416. * under the License.
  23417. */
  23418. /**
  23419. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23420. */
  23421. /*
  23422. * Licensed to the Apache Software Foundation (ASF) under one
  23423. * or more contributor license agreements. See the NOTICE file
  23424. * distributed with this work for additional information
  23425. * regarding copyright ownership. The ASF licenses this file
  23426. * to you under the Apache License, Version 2.0 (the
  23427. * "License"); you may not use this file except in compliance
  23428. * with the License. You may obtain a copy of the License at
  23429. *
  23430. * http://www.apache.org/licenses/LICENSE-2.0
  23431. *
  23432. * Unless required by applicable law or agreed to in writing,
  23433. * software distributed under the License is distributed on an
  23434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23435. * KIND, either express or implied. See the License for the
  23436. * specific language governing permissions and limitations
  23437. * under the License.
  23438. */
  23439. function findEventDispatcher(target, det, returnFirstMatch) {
  23440. var found;
  23441. while (target) {
  23442. if (det(target)) {
  23443. found = target;
  23444. if (returnFirstMatch) {
  23445. break;
  23446. }
  23447. }
  23448. target = target.__hostTarget || target.parent;
  23449. }
  23450. return found;
  23451. }
  23452. var wmUniqueIndex = Math.round(Math.random() * 9);
  23453. var WeakMap = (function () {
  23454. function WeakMap() {
  23455. this._id = '__ec_inner_' + wmUniqueIndex++;
  23456. }
  23457. WeakMap.prototype.get = function (key) {
  23458. return this._guard(key)[this._id];
  23459. };
  23460. WeakMap.prototype.set = function (key, value) {
  23461. var target = this._guard(key);
  23462. if (typeof Object.defineProperty === 'function') {
  23463. Object.defineProperty(target, this._id, {
  23464. value: value,
  23465. enumerable: false,
  23466. configurable: true
  23467. });
  23468. }
  23469. else {
  23470. target[this._id] = value;
  23471. }
  23472. return this;
  23473. };
  23474. WeakMap.prototype["delete"] = function (key) {
  23475. if (this.has(key)) {
  23476. delete this._guard(key)[this._id];
  23477. return true;
  23478. }
  23479. return false;
  23480. };
  23481. WeakMap.prototype.has = function (key) {
  23482. return !!this._guard(key)[this._id];
  23483. };
  23484. WeakMap.prototype._guard = function (key) {
  23485. if (key !== Object(key)) {
  23486. throw TypeError('Value of WeakMap is not a non-null object.');
  23487. }
  23488. return key;
  23489. };
  23490. return WeakMap;
  23491. }());
  23492. /**
  23493. * Triangle shape
  23494. * @inner
  23495. */
  23496. var Triangle = Path.extend({
  23497. type: 'triangle',
  23498. shape: {
  23499. cx: 0,
  23500. cy: 0,
  23501. width: 0,
  23502. height: 0
  23503. },
  23504. buildPath: function (path, shape) {
  23505. var cx = shape.cx;
  23506. var cy = shape.cy;
  23507. var width = shape.width / 2;
  23508. var height = shape.height / 2;
  23509. path.moveTo(cx, cy - height);
  23510. path.lineTo(cx + width, cy + height);
  23511. path.lineTo(cx - width, cy + height);
  23512. path.closePath();
  23513. }
  23514. });
  23515. /**
  23516. * Diamond shape
  23517. * @inner
  23518. */
  23519. var Diamond = Path.extend({
  23520. type: 'diamond',
  23521. shape: {
  23522. cx: 0,
  23523. cy: 0,
  23524. width: 0,
  23525. height: 0
  23526. },
  23527. buildPath: function (path, shape) {
  23528. var cx = shape.cx;
  23529. var cy = shape.cy;
  23530. var width = shape.width / 2;
  23531. var height = shape.height / 2;
  23532. path.moveTo(cx, cy - height);
  23533. path.lineTo(cx + width, cy);
  23534. path.lineTo(cx, cy + height);
  23535. path.lineTo(cx - width, cy);
  23536. path.closePath();
  23537. }
  23538. });
  23539. /**
  23540. * Pin shape
  23541. * @inner
  23542. */
  23543. var Pin = Path.extend({
  23544. type: 'pin',
  23545. shape: {
  23546. // x, y on the cusp
  23547. x: 0,
  23548. y: 0,
  23549. width: 0,
  23550. height: 0
  23551. },
  23552. buildPath: function (path, shape) {
  23553. var x = shape.x;
  23554. var y = shape.y;
  23555. var w = shape.width / 5 * 3; // Height must be larger than width
  23556. var h = Math.max(w, shape.height);
  23557. var r = w / 2; // Dist on y with tangent point and circle center
  23558. var dy = r * r / (h - r);
  23559. var cy = y - h + r + dy;
  23560. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  23561. var dx = Math.cos(angle) * r;
  23562. var tanX = Math.sin(angle);
  23563. var tanY = Math.cos(angle);
  23564. var cpLen = r * 0.6;
  23565. var cpLen2 = r * 0.7;
  23566. path.moveTo(x - dx, cy + dy);
  23567. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  23568. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  23569. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  23570. path.closePath();
  23571. }
  23572. });
  23573. /**
  23574. * Arrow shape
  23575. * @inner
  23576. */
  23577. var Arrow = Path.extend({
  23578. type: 'arrow',
  23579. shape: {
  23580. x: 0,
  23581. y: 0,
  23582. width: 0,
  23583. height: 0
  23584. },
  23585. buildPath: function (ctx, shape) {
  23586. var height = shape.height;
  23587. var width = shape.width;
  23588. var x = shape.x;
  23589. var y = shape.y;
  23590. var dx = width / 3 * 2;
  23591. ctx.moveTo(x, y);
  23592. ctx.lineTo(x + dx, y + height);
  23593. ctx.lineTo(x, y + height / 4 * 3);
  23594. ctx.lineTo(x - dx, y + height);
  23595. ctx.lineTo(x, y);
  23596. ctx.closePath();
  23597. }
  23598. });
  23599. /**
  23600. * Map of path contructors
  23601. */
  23602. // TODO Use function to build symbol path.
  23603. var symbolCtors = {
  23604. // Use small height rect to simulate line.
  23605. // Avoid using stroke.
  23606. line: Rect,
  23607. rect: Rect,
  23608. roundRect: Rect,
  23609. square: Rect,
  23610. circle: Circle,
  23611. diamond: Diamond,
  23612. pin: Pin,
  23613. arrow: Arrow,
  23614. triangle: Triangle
  23615. }; // NOTICE Only use fill. No line!
  23616. var symbolShapeMakers = {
  23617. line: function (x, y, w, h, shape) {
  23618. var thickness = 2; // A thin line
  23619. shape.x = x;
  23620. shape.y = y + h / 2 - thickness / 2;
  23621. shape.width = w;
  23622. shape.height = thickness;
  23623. },
  23624. rect: function (x, y, w, h, shape) {
  23625. shape.x = x;
  23626. shape.y = y;
  23627. shape.width = w;
  23628. shape.height = h;
  23629. },
  23630. roundRect: function (x, y, w, h, shape) {
  23631. shape.x = x;
  23632. shape.y = y;
  23633. shape.width = w;
  23634. shape.height = h;
  23635. shape.r = Math.min(w, h) / 4;
  23636. },
  23637. square: function (x, y, w, h, shape) {
  23638. var size = Math.min(w, h);
  23639. shape.x = x;
  23640. shape.y = y;
  23641. shape.width = size;
  23642. shape.height = size;
  23643. },
  23644. circle: function (x, y, w, h, shape) {
  23645. // Put circle in the center of square
  23646. shape.cx = x + w / 2;
  23647. shape.cy = y + h / 2;
  23648. shape.r = Math.min(w, h) / 2;
  23649. },
  23650. diamond: function (x, y, w, h, shape) {
  23651. shape.cx = x + w / 2;
  23652. shape.cy = y + h / 2;
  23653. shape.width = w;
  23654. shape.height = h;
  23655. },
  23656. pin: function (x, y, w, h, shape) {
  23657. shape.x = x + w / 2;
  23658. shape.y = y + h / 2;
  23659. shape.width = w;
  23660. shape.height = h;
  23661. },
  23662. arrow: function (x, y, w, h, shape) {
  23663. shape.x = x + w / 2;
  23664. shape.y = y + h / 2;
  23665. shape.width = w;
  23666. shape.height = h;
  23667. },
  23668. triangle: function (x, y, w, h, shape) {
  23669. shape.cx = x + w / 2;
  23670. shape.cy = y + h / 2;
  23671. shape.width = w;
  23672. shape.height = h;
  23673. }
  23674. };
  23675. var symbolBuildProxies = {};
  23676. each(symbolCtors, function (Ctor, name) {
  23677. symbolBuildProxies[name] = new Ctor();
  23678. });
  23679. var SymbolClz = Path.extend({
  23680. type: 'symbol',
  23681. shape: {
  23682. symbolType: '',
  23683. x: 0,
  23684. y: 0,
  23685. width: 0,
  23686. height: 0
  23687. },
  23688. calculateTextPosition: function (out, config, rect) {
  23689. var res = calculateTextPosition(out, config, rect);
  23690. var shape = this.shape;
  23691. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  23692. res.y = rect.y + rect.height * 0.4;
  23693. }
  23694. return res;
  23695. },
  23696. buildPath: function (ctx, shape, inBundle) {
  23697. var symbolType = shape.symbolType;
  23698. if (symbolType !== 'none') {
  23699. var proxySymbol = symbolBuildProxies[symbolType];
  23700. if (!proxySymbol) {
  23701. // Default rect
  23702. symbolType = 'rect';
  23703. proxySymbol = symbolBuildProxies[symbolType];
  23704. }
  23705. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  23706. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  23707. }
  23708. }
  23709. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  23710. function symbolPathSetColor(color, innerColor) {
  23711. if (this.type !== 'image') {
  23712. var symbolStyle = this.style;
  23713. if (this.__isEmptyBrush) {
  23714. symbolStyle.stroke = color;
  23715. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView.
  23716. symbolStyle.lineWidth = 2;
  23717. } else {
  23718. symbolStyle.fill = color;
  23719. }
  23720. this.markRedraw();
  23721. }
  23722. }
  23723. /**
  23724. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  23725. */
  23726. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  23727. keepAspect) {
  23728. // TODO Support image object, DynamicImage.
  23729. var isEmpty = symbolType.indexOf('empty') === 0;
  23730. if (isEmpty) {
  23731. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  23732. }
  23733. var symbolPath;
  23734. if (symbolType.indexOf('image://') === 0) {
  23735. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23736. } else if (symbolType.indexOf('path://') === 0) {
  23737. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23738. } else {
  23739. symbolPath = new SymbolClz({
  23740. shape: {
  23741. symbolType: symbolType,
  23742. x: x,
  23743. y: y,
  23744. width: w,
  23745. height: h
  23746. }
  23747. });
  23748. }
  23749. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  23750. symbolPath.setColor = symbolPathSetColor;
  23751. if (color) {
  23752. symbolPath.setColor(color);
  23753. }
  23754. return symbolPath;
  23755. }
  23756. function createLinearGradient(ctx, obj, rect) {
  23757. var x = obj.x == null ? 0 : obj.x;
  23758. var x2 = obj.x2 == null ? 1 : obj.x2;
  23759. var y = obj.y == null ? 0 : obj.y;
  23760. var y2 = obj.y2 == null ? 0 : obj.y2;
  23761. if (!obj.global) {
  23762. x = x * rect.width + rect.x;
  23763. x2 = x2 * rect.width + rect.x;
  23764. y = y * rect.height + rect.y;
  23765. y2 = y2 * rect.height + rect.y;
  23766. }
  23767. x = isNaN(x) ? 0 : x;
  23768. x2 = isNaN(x2) ? 1 : x2;
  23769. y = isNaN(y) ? 0 : y;
  23770. y2 = isNaN(y2) ? 0 : y2;
  23771. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  23772. return canvasGradient;
  23773. }
  23774. function createRadialGradient(ctx, obj, rect) {
  23775. var width = rect.width;
  23776. var height = rect.height;
  23777. var min = Math.min(width, height);
  23778. var x = obj.x == null ? 0.5 : obj.x;
  23779. var y = obj.y == null ? 0.5 : obj.y;
  23780. var r = obj.r == null ? 0.5 : obj.r;
  23781. if (!obj.global) {
  23782. x = x * width + rect.x;
  23783. y = y * height + rect.y;
  23784. r = r * min;
  23785. }
  23786. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  23787. return canvasGradient;
  23788. }
  23789. function getCanvasGradient(ctx, obj, rect) {
  23790. var canvasGradient = obj.type === 'radial'
  23791. ? createRadialGradient(ctx, obj, rect)
  23792. : createLinearGradient(ctx, obj, rect);
  23793. var colorStops = obj.colorStops;
  23794. for (var i = 0; i < colorStops.length; i++) {
  23795. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  23796. }
  23797. return canvasGradient;
  23798. }
  23799. function isClipPathChanged(clipPaths, prevClipPaths) {
  23800. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  23801. return false;
  23802. }
  23803. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  23804. return true;
  23805. }
  23806. for (var i = 0; i < clipPaths.length; i++) {
  23807. if (clipPaths[i] !== prevClipPaths[i]) {
  23808. return true;
  23809. }
  23810. }
  23811. return false;
  23812. }
  23813. function normalizeLineDash(lineType, lineWidth) {
  23814. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  23815. return null;
  23816. }
  23817. lineWidth = lineWidth || 1;
  23818. return lineType === 'dashed'
  23819. ? [4 * lineWidth, 2 * lineWidth]
  23820. : lineType === 'dotted'
  23821. ? [lineWidth]
  23822. : isNumber(lineType)
  23823. ? [lineType] : isArray(lineType) ? lineType : null;
  23824. }
  23825. var pathProxyForDraw = new PathProxy(true);
  23826. function styleHasStroke(style) {
  23827. var stroke = style.stroke;
  23828. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  23829. }
  23830. function styleHasFill(style) {
  23831. var fill = style.fill;
  23832. return fill != null && fill !== 'none';
  23833. }
  23834. function doFillPath(ctx, style) {
  23835. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  23836. var originalGlobalAlpha = ctx.globalAlpha;
  23837. ctx.globalAlpha = style.fillOpacity * style.opacity;
  23838. ctx.fill();
  23839. ctx.globalAlpha = originalGlobalAlpha;
  23840. }
  23841. else {
  23842. ctx.fill();
  23843. }
  23844. }
  23845. function doStrokePath(ctx, style) {
  23846. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  23847. var originalGlobalAlpha = ctx.globalAlpha;
  23848. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  23849. ctx.stroke();
  23850. ctx.globalAlpha = originalGlobalAlpha;
  23851. }
  23852. else {
  23853. ctx.stroke();
  23854. }
  23855. }
  23856. function createCanvasPattern(ctx, pattern, el) {
  23857. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  23858. if (isImageReady(image)) {
  23859. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  23860. if (typeof DOMMatrix === 'function') {
  23861. var matrix = new DOMMatrix();
  23862. matrix.rotateSelf(0, 0, (pattern.rotation || 0) / Math.PI * 180);
  23863. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  23864. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  23865. canvasPattern.setTransform(matrix);
  23866. }
  23867. return canvasPattern;
  23868. }
  23869. }
  23870. function brushPath(ctx, el, style, inBatch) {
  23871. var hasStroke = styleHasStroke(style);
  23872. var hasFill = styleHasFill(style);
  23873. var strokePercent = style.strokePercent;
  23874. var strokePart = strokePercent < 1;
  23875. var firstDraw = !el.path;
  23876. if ((!el.silent || strokePart) && firstDraw) {
  23877. el.createPathProxy();
  23878. }
  23879. var path = el.path || pathProxyForDraw;
  23880. if (!inBatch) {
  23881. var fill = style.fill;
  23882. var stroke = style.stroke;
  23883. var hasFillGradient = hasFill && !!fill.colorStops;
  23884. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  23885. var hasFillPattern = hasFill && !!fill.image;
  23886. var hasStrokePattern = hasStroke && !!stroke.image;
  23887. var fillGradient = void 0;
  23888. var strokeGradient = void 0;
  23889. var fillPattern = void 0;
  23890. var strokePattern = void 0;
  23891. var rect = void 0;
  23892. if (hasFillGradient || hasStrokeGradient) {
  23893. rect = el.getBoundingRect();
  23894. }
  23895. if (hasFillGradient) {
  23896. fillGradient = el.__dirty
  23897. ? getCanvasGradient(ctx, fill, rect)
  23898. : el.__canvasFillGradient;
  23899. el.__canvasFillGradient = fillGradient;
  23900. }
  23901. if (hasStrokeGradient) {
  23902. strokeGradient = el.__dirty
  23903. ? getCanvasGradient(ctx, stroke, rect)
  23904. : el.__canvasStrokeGradient;
  23905. el.__canvasStrokeGradient = strokeGradient;
  23906. }
  23907. if (hasFillPattern) {
  23908. fillPattern = (el.__dirty || !el.__canvasFillPattern)
  23909. ? createCanvasPattern(ctx, fill, el)
  23910. : el.__canvasFillPattern;
  23911. el.__canvasFillPattern = fillPattern;
  23912. }
  23913. if (hasStrokePattern) {
  23914. strokePattern = (el.__dirty || !el.__canvasStrokePattern)
  23915. ? createCanvasPattern(ctx, stroke, el)
  23916. : el.__canvasStrokePattern;
  23917. el.__canvasStrokePattern = fillPattern;
  23918. }
  23919. if (hasFillGradient) {
  23920. ctx.fillStyle = fillGradient;
  23921. }
  23922. else if (hasFillPattern) {
  23923. if (fillPattern) {
  23924. ctx.fillStyle = fillPattern;
  23925. }
  23926. else {
  23927. hasFill = false;
  23928. }
  23929. }
  23930. if (hasStrokeGradient) {
  23931. ctx.strokeStyle = strokeGradient;
  23932. }
  23933. else if (hasStrokePattern) {
  23934. if (strokePattern) {
  23935. ctx.strokeStyle = strokePattern;
  23936. }
  23937. else {
  23938. hasStroke = false;
  23939. }
  23940. }
  23941. }
  23942. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  23943. var lineDashOffset = style.lineDashOffset;
  23944. var ctxLineDash = !!ctx.setLineDash;
  23945. var scale = el.getGlobalScale();
  23946. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  23947. if (lineDash) {
  23948. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  23949. if (lineScale_1 && lineScale_1 !== 1) {
  23950. lineDash = map(lineDash, function (rawVal) {
  23951. return rawVal / lineScale_1;
  23952. });
  23953. lineDashOffset /= lineScale_1;
  23954. }
  23955. }
  23956. var needsRebuild = true;
  23957. if (firstDraw || (el.__dirty & Path.SHAPE_CHANGED_BIT)
  23958. || (lineDash && !ctxLineDash && hasStroke)) {
  23959. path.setDPR(ctx.dpr);
  23960. if (strokePart) {
  23961. path.setContext(null);
  23962. }
  23963. else {
  23964. path.setContext(ctx);
  23965. needsRebuild = false;
  23966. }
  23967. path.reset();
  23968. if (lineDash && !ctxLineDash) {
  23969. path.setLineDash(lineDash);
  23970. path.setLineDashOffset(lineDashOffset);
  23971. }
  23972. el.buildPath(path, el.shape, inBatch);
  23973. path.toStatic();
  23974. el.pathUpdated();
  23975. }
  23976. if (needsRebuild) {
  23977. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  23978. }
  23979. if (lineDash && ctxLineDash) {
  23980. ctx.setLineDash(lineDash);
  23981. ctx.lineDashOffset = lineDashOffset;
  23982. }
  23983. if (!inBatch) {
  23984. if (style.strokeFirst) {
  23985. if (hasStroke) {
  23986. doStrokePath(ctx, style);
  23987. }
  23988. if (hasFill) {
  23989. doFillPath(ctx, style);
  23990. }
  23991. }
  23992. else {
  23993. if (hasFill) {
  23994. doFillPath(ctx, style);
  23995. }
  23996. if (hasStroke) {
  23997. doStrokePath(ctx, style);
  23998. }
  23999. }
  24000. }
  24001. if (lineDash && ctxLineDash) {
  24002. ctx.setLineDash([]);
  24003. }
  24004. }
  24005. function brushImage(ctx, el, style) {
  24006. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24007. if (!image || !isImageReady(image)) {
  24008. return;
  24009. }
  24010. var x = style.x || 0;
  24011. var y = style.y || 0;
  24012. var width = el.getWidth();
  24013. var height = el.getHeight();
  24014. var aspect = image.width / image.height;
  24015. if (width == null && height != null) {
  24016. width = height * aspect;
  24017. }
  24018. else if (height == null && width != null) {
  24019. height = width / aspect;
  24020. }
  24021. else if (width == null && height == null) {
  24022. width = image.width;
  24023. height = image.height;
  24024. }
  24025. if (style.sWidth && style.sHeight) {
  24026. var sx = style.sx || 0;
  24027. var sy = style.sy || 0;
  24028. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24029. }
  24030. else if (style.sx && style.sy) {
  24031. var sx = style.sx;
  24032. var sy = style.sy;
  24033. var sWidth = width - sx;
  24034. var sHeight = height - sy;
  24035. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24036. }
  24037. else {
  24038. ctx.drawImage(image, x, y, width, height);
  24039. }
  24040. }
  24041. function brushText(ctx, el, style) {
  24042. var text = style.text;
  24043. text != null && (text += '');
  24044. if (text) {
  24045. ctx.font = style.font || DEFAULT_FONT;
  24046. ctx.textAlign = style.textAlign;
  24047. ctx.textBaseline = style.textBaseline;
  24048. var hasLineDash = void 0;
  24049. if (ctx.setLineDash) {
  24050. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24051. var lineDashOffset = style.lineDashOffset;
  24052. if (lineDash) {
  24053. var lineScale_2 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24054. if (lineScale_2 && lineScale_2 !== 1) {
  24055. lineDash = map(lineDash, function (rawVal) {
  24056. return rawVal / lineScale_2;
  24057. });
  24058. lineDashOffset /= lineScale_2;
  24059. }
  24060. ctx.setLineDash(lineDash);
  24061. ctx.lineDashOffset = lineDashOffset;
  24062. hasLineDash = true;
  24063. }
  24064. }
  24065. if (style.strokeFirst) {
  24066. if (styleHasStroke(style)) {
  24067. ctx.strokeText(text, style.x, style.y);
  24068. }
  24069. if (styleHasFill(style)) {
  24070. ctx.fillText(text, style.x, style.y);
  24071. }
  24072. }
  24073. else {
  24074. if (styleHasFill(style)) {
  24075. ctx.fillText(text, style.x, style.y);
  24076. }
  24077. if (styleHasStroke(style)) {
  24078. ctx.strokeText(text, style.x, style.y);
  24079. }
  24080. }
  24081. if (hasLineDash) {
  24082. ctx.setLineDash([]);
  24083. }
  24084. }
  24085. }
  24086. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24087. var STROKE_PROPS = [
  24088. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24089. ];
  24090. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24091. var styleChanged = false;
  24092. if (!forceSetAll) {
  24093. prevStyle = prevStyle || {};
  24094. if (style === prevStyle) {
  24095. return false;
  24096. }
  24097. }
  24098. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24099. if (!styleChanged) {
  24100. flushPathDrawn(ctx, scope);
  24101. styleChanged = true;
  24102. }
  24103. ctx.globalAlpha = style.opacity == null ? DEFAULT_COMMON_STYLE.opacity : style.opacity;
  24104. }
  24105. if (forceSetAll || style.blend !== prevStyle.blend) {
  24106. if (!styleChanged) {
  24107. flushPathDrawn(ctx, scope);
  24108. styleChanged = true;
  24109. }
  24110. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24111. }
  24112. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24113. var propName = SHADOW_NUMBER_PROPS[i];
  24114. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24115. if (!styleChanged) {
  24116. flushPathDrawn(ctx, scope);
  24117. styleChanged = true;
  24118. }
  24119. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24120. }
  24121. }
  24122. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24123. if (!styleChanged) {
  24124. flushPathDrawn(ctx, scope);
  24125. styleChanged = true;
  24126. }
  24127. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24128. }
  24129. return styleChanged;
  24130. }
  24131. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24132. var style = getStyle(el, scope.inHover);
  24133. var prevStyle = forceSetAll
  24134. ? null
  24135. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24136. if (style === prevStyle) {
  24137. return false;
  24138. }
  24139. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24140. if (forceSetAll || style.fill !== prevStyle.fill) {
  24141. if (!styleChanged) {
  24142. flushPathDrawn(ctx, scope);
  24143. styleChanged = true;
  24144. }
  24145. ctx.fillStyle = style.fill;
  24146. }
  24147. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24148. if (!styleChanged) {
  24149. flushPathDrawn(ctx, scope);
  24150. styleChanged = true;
  24151. }
  24152. ctx.strokeStyle = style.stroke;
  24153. }
  24154. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24155. if (!styleChanged) {
  24156. flushPathDrawn(ctx, scope);
  24157. styleChanged = true;
  24158. }
  24159. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24160. }
  24161. if (el.hasStroke()) {
  24162. var lineWidth = style.lineWidth;
  24163. var newLineWidth = lineWidth / ((style.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1);
  24164. if (ctx.lineWidth !== newLineWidth) {
  24165. if (!styleChanged) {
  24166. flushPathDrawn(ctx, scope);
  24167. styleChanged = true;
  24168. }
  24169. ctx.lineWidth = newLineWidth;
  24170. }
  24171. }
  24172. for (var i = 0; i < STROKE_PROPS.length; i++) {
  24173. var prop = STROKE_PROPS[i];
  24174. var propName = prop[0];
  24175. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24176. if (!styleChanged) {
  24177. flushPathDrawn(ctx, scope);
  24178. styleChanged = true;
  24179. }
  24180. ctx[propName] = style[propName] || prop[1];
  24181. }
  24182. }
  24183. return styleChanged;
  24184. }
  24185. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  24186. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  24187. }
  24188. function setContextTransform(ctx, el) {
  24189. var m = el.transform;
  24190. var dpr = ctx.dpr || 1;
  24191. if (m) {
  24192. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  24193. }
  24194. else {
  24195. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  24196. }
  24197. }
  24198. function updateClipStatus(clipPaths, ctx, scope) {
  24199. var allClipped = false;
  24200. for (var i = 0; i < clipPaths.length; i++) {
  24201. var clipPath = clipPaths[i];
  24202. allClipped = allClipped || clipPath.isZeroArea();
  24203. setContextTransform(ctx, clipPath);
  24204. ctx.beginPath();
  24205. clipPath.buildPath(ctx, clipPath.shape);
  24206. ctx.clip();
  24207. }
  24208. scope.allClipped = allClipped;
  24209. }
  24210. function isTransformChanged(m0, m1) {
  24211. if (m0 && m1) {
  24212. return m0[0] !== m1[0]
  24213. || m0[1] !== m1[1]
  24214. || m0[2] !== m1[2]
  24215. || m0[3] !== m1[3]
  24216. || m0[4] !== m1[4]
  24217. || m0[5] !== m1[5];
  24218. }
  24219. else if (!m0 && !m1) {
  24220. return false;
  24221. }
  24222. return true;
  24223. }
  24224. var DRAW_TYPE_PATH = 1;
  24225. var DRAW_TYPE_IMAGE = 2;
  24226. var DRAW_TYPE_TEXT = 3;
  24227. var DRAW_TYPE_INCREMENTAL = 4;
  24228. function canPathBatch(style) {
  24229. var hasFill = styleHasFill(style);
  24230. var hasStroke = styleHasStroke(style);
  24231. return !(style.lineDash
  24232. || !(+hasFill ^ +hasStroke)
  24233. || (hasFill && typeof style.fill !== 'string')
  24234. || (hasStroke && typeof style.stroke !== 'string')
  24235. || style.strokePercent < 1
  24236. || style.strokeOpacity < 1
  24237. || style.fillOpacity < 1);
  24238. }
  24239. function flushPathDrawn(ctx, scope) {
  24240. scope.batchFill && ctx.fill();
  24241. scope.batchStroke && ctx.stroke();
  24242. scope.batchFill = '';
  24243. scope.batchStroke = '';
  24244. }
  24245. function getStyle(el, inHover) {
  24246. return inHover ? (el.__hoverStyle || el.style) : el.style;
  24247. }
  24248. function brushSingle(ctx, el) {
  24249. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  24250. }
  24251. function brush(ctx, el, scope, isLast) {
  24252. var m = el.transform;
  24253. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  24254. el.__dirty &= ~Element.REDARAW_BIT;
  24255. el.__isRendered = false;
  24256. return;
  24257. }
  24258. var clipPaths = el.__clipPaths;
  24259. var prevElClipPaths = scope.prevElClipPaths;
  24260. var forceSetTransform = false;
  24261. var forceSetStyle = false;
  24262. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  24263. if (prevElClipPaths && prevElClipPaths.length) {
  24264. flushPathDrawn(ctx, scope);
  24265. ctx.restore();
  24266. forceSetStyle = forceSetTransform = true;
  24267. scope.prevElClipPaths = null;
  24268. scope.allClipped = false;
  24269. scope.prevEl = null;
  24270. }
  24271. if (clipPaths && clipPaths.length) {
  24272. flushPathDrawn(ctx, scope);
  24273. ctx.save();
  24274. updateClipStatus(clipPaths, ctx, scope);
  24275. forceSetTransform = true;
  24276. }
  24277. scope.prevElClipPaths = clipPaths;
  24278. }
  24279. if (scope.allClipped) {
  24280. el.__isRendered = false;
  24281. return;
  24282. }
  24283. el.beforeBrush && el.beforeBrush();
  24284. el.innerBeforeBrush();
  24285. var prevEl = scope.prevEl;
  24286. if (!prevEl) {
  24287. forceSetStyle = forceSetTransform = true;
  24288. }
  24289. var canBatchPath = el instanceof Path
  24290. && el.autoBatch
  24291. && canPathBatch(el.style);
  24292. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  24293. flushPathDrawn(ctx, scope);
  24294. setContextTransform(ctx, el);
  24295. }
  24296. else if (!canBatchPath) {
  24297. flushPathDrawn(ctx, scope);
  24298. }
  24299. var style = getStyle(el, scope.inHover);
  24300. if (el instanceof Path) {
  24301. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  24302. forceSetStyle = true;
  24303. scope.lastDrawType = DRAW_TYPE_PATH;
  24304. }
  24305. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24306. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  24307. ctx.beginPath();
  24308. }
  24309. brushPath(ctx, el, style, canBatchPath);
  24310. if (canBatchPath) {
  24311. scope.batchFill = style.fill || '';
  24312. scope.batchStroke = style.stroke || '';
  24313. }
  24314. }
  24315. else {
  24316. if (el instanceof TSpan) {
  24317. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  24318. forceSetStyle = true;
  24319. scope.lastDrawType = DRAW_TYPE_TEXT;
  24320. }
  24321. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24322. brushText(ctx, el, style);
  24323. }
  24324. else if (el instanceof ZRImage) {
  24325. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  24326. forceSetStyle = true;
  24327. scope.lastDrawType = DRAW_TYPE_IMAGE;
  24328. }
  24329. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  24330. brushImage(ctx, el, style);
  24331. }
  24332. else if (el instanceof IncrementalDisplayable) {
  24333. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  24334. forceSetStyle = true;
  24335. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  24336. }
  24337. brushIncremental(ctx, el, scope);
  24338. }
  24339. }
  24340. if (canBatchPath && isLast) {
  24341. flushPathDrawn(ctx, scope);
  24342. }
  24343. el.innerAfterBrush();
  24344. el.afterBrush && el.afterBrush();
  24345. scope.prevEl = el;
  24346. el.__dirty = 0;
  24347. el.__isRendered = true;
  24348. }
  24349. function brushIncremental(ctx, el, scope) {
  24350. var displayables = el.getDisplayables();
  24351. var temporalDisplayables = el.getTemporalDisplayables();
  24352. ctx.save();
  24353. var innerScope = {
  24354. prevElClipPaths: null,
  24355. prevEl: null,
  24356. allClipped: false,
  24357. viewWidth: scope.viewWidth,
  24358. viewHeight: scope.viewHeight,
  24359. inHover: scope.inHover
  24360. };
  24361. var i;
  24362. var len;
  24363. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  24364. var displayable = displayables[i];
  24365. displayable.beforeBrush && displayable.beforeBrush();
  24366. displayable.innerBeforeBrush();
  24367. brush(ctx, displayable, innerScope, i === len - 1);
  24368. displayable.innerAfterBrush();
  24369. displayable.afterBrush && displayable.afterBrush();
  24370. innerScope.prevEl = displayable;
  24371. }
  24372. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  24373. var displayable = temporalDisplayables[i_1];
  24374. displayable.beforeBrush && displayable.beforeBrush();
  24375. displayable.innerBeforeBrush();
  24376. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  24377. displayable.innerAfterBrush();
  24378. displayable.afterBrush && displayable.afterBrush();
  24379. innerScope.prevEl = displayable;
  24380. }
  24381. el.clearTemporalDisplayables();
  24382. el.notClear = true;
  24383. ctx.restore();
  24384. }
  24385. var decalMap = new WeakMap();
  24386. var decalCache = new LRU(100);
  24387. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  24388. /**
  24389. * Create or update pattern image from decal options
  24390. *
  24391. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  24392. * @return {Pattern} pattern with generated image, null if no decal
  24393. */
  24394. function createOrUpdatePatternFromDecal(decalObject, api) {
  24395. if (decalObject === 'none') {
  24396. return null;
  24397. }
  24398. var dpr = api.getDevicePixelRatio();
  24399. var zr = api.getZr();
  24400. var isSVG = zr.painter.type === 'svg';
  24401. if (decalObject.dirty) {
  24402. decalMap["delete"](decalObject);
  24403. }
  24404. var oldPattern = decalMap.get(decalObject);
  24405. if (oldPattern) {
  24406. return oldPattern;
  24407. }
  24408. var decalOpt = defaults(decalObject, {
  24409. symbol: 'rect',
  24410. symbolSize: 1,
  24411. symbolKeepAspect: true,
  24412. color: 'rgba(0, 0, 0, 0.2)',
  24413. backgroundColor: null,
  24414. dashArrayX: 5,
  24415. dashArrayY: 5,
  24416. rotation: 0,
  24417. maxTileWidth: 512,
  24418. maxTileHeight: 512
  24419. });
  24420. if (decalOpt.backgroundColor === 'none') {
  24421. decalOpt.backgroundColor = null;
  24422. }
  24423. var pattern = {
  24424. repeat: 'repeat'
  24425. };
  24426. setPatternnSource(pattern);
  24427. pattern.rotation = decalOpt.rotation;
  24428. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  24429. decalMap.set(decalObject, pattern);
  24430. decalObject.dirty = false;
  24431. return pattern;
  24432. function setPatternnSource(pattern) {
  24433. var keys = [dpr];
  24434. var isValidKey = true;
  24435. for (var i = 0; i < decalKeys.length; ++i) {
  24436. var value = decalOpt[decalKeys[i]];
  24437. var valueType = typeof value;
  24438. if (value != null && !isArray(value) && valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') {
  24439. isValidKey = false;
  24440. break;
  24441. }
  24442. keys.push(value);
  24443. }
  24444. var cacheKey;
  24445. if (isValidKey) {
  24446. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  24447. var cache = decalCache.get(cacheKey);
  24448. if (cache) {
  24449. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  24450. }
  24451. }
  24452. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  24453. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  24454. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  24455. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  24456. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  24457. var canvas = !isSVG && createCanvas();
  24458. var svgRoot = isSVG && zr.painter.createSVGElement('g');
  24459. var pSize = getPatternSize();
  24460. var ctx;
  24461. if (canvas) {
  24462. canvas.width = pSize.width * dpr;
  24463. canvas.height = pSize.height * dpr;
  24464. ctx = canvas.getContext('2d');
  24465. }
  24466. brushDecal();
  24467. if (isValidKey) {
  24468. decalCache.put(cacheKey, canvas || svgRoot);
  24469. }
  24470. pattern.image = canvas;
  24471. pattern.svgElement = svgRoot;
  24472. pattern.svgWidth = pSize.width;
  24473. pattern.svgHeight = pSize.height;
  24474. /**
  24475. * Get minumum length that can make a repeatable pattern.
  24476. *
  24477. * @return {Object} pattern width and height
  24478. */
  24479. function getPatternSize() {
  24480. /**
  24481. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  24482. * |--- --- --- --- --- ...
  24483. * |-- -- -- -- -- -- -- -- ...
  24484. * |--- --- --- --- --- ...
  24485. * |-- -- -- -- -- -- -- -- ...
  24486. * So the minumum length of X is 15,
  24487. * which is the least common multiple of `3 + 2` and `2 + 1`
  24488. * |--- --- --- |--- --- ...
  24489. * |-- -- -- -- -- |-- -- -- ...
  24490. */
  24491. var width = 1;
  24492. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  24493. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  24494. }
  24495. var symbolRepeats = 1;
  24496. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  24497. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  24498. }
  24499. width *= symbolRepeats;
  24500. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  24501. if ("development" !== 'production') {
  24502. var warn = function (attrName) {
  24503. /* eslint-disable-next-line */
  24504. 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.");
  24505. };
  24506. if (width > decalOpt.maxTileWidth) {
  24507. warn('maxTileWidth');
  24508. }
  24509. if (height > decalOpt.maxTileHeight) {
  24510. warn('maxTileHeight');
  24511. }
  24512. }
  24513. return {
  24514. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  24515. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  24516. };
  24517. }
  24518. function brushDecal() {
  24519. if (ctx) {
  24520. ctx.clearRect(0, 0, canvas.width, canvas.height);
  24521. if (decalOpt.backgroundColor) {
  24522. ctx.fillStyle = decalOpt.backgroundColor;
  24523. ctx.fillRect(0, 0, canvas.width, canvas.height);
  24524. }
  24525. }
  24526. var ySum = 0;
  24527. for (var i = 0; i < dashArrayY.length; ++i) {
  24528. ySum += dashArrayY[i];
  24529. }
  24530. if (ySum <= 0) {
  24531. // dashArrayY is 0, draw nothing
  24532. return;
  24533. }
  24534. var y = -lineBlockLengthY;
  24535. var yId = 0;
  24536. var yIdTotal = 0;
  24537. var xId0 = 0;
  24538. while (y < pSize.height) {
  24539. if (yId % 2 === 0) {
  24540. var symbolYId = yIdTotal / 2 % symbolArray.length;
  24541. var x = 0;
  24542. var xId1 = 0;
  24543. var xId1Total = 0;
  24544. while (x < pSize.width * 2) {
  24545. var xSum = 0;
  24546. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  24547. xSum += dashArrayX[xId0][i];
  24548. }
  24549. if (xSum <= 0) {
  24550. // Skip empty line
  24551. break;
  24552. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  24553. if (xId1 % 2 === 0) {
  24554. var size = (1 - decalOpt.symbolSize) * 0.5;
  24555. var left = x + dashArrayX[xId0][xId1] * size;
  24556. var top_1 = y + dashArrayY[yId] * size;
  24557. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  24558. var height = dashArrayY[yId] * decalOpt.symbolSize;
  24559. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  24560. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  24561. }
  24562. x += dashArrayX[xId0][xId1];
  24563. ++xId1Total;
  24564. ++xId1;
  24565. if (xId1 === dashArrayX[xId0].length) {
  24566. xId1 = 0;
  24567. }
  24568. }
  24569. ++xId0;
  24570. if (xId0 === dashArrayX.length) {
  24571. xId0 = 0;
  24572. }
  24573. }
  24574. y += dashArrayY[yId];
  24575. ++yIdTotal;
  24576. ++yId;
  24577. if (yId === dashArrayY.length) {
  24578. yId = 0;
  24579. }
  24580. }
  24581. function brushSymbol(x, y, width, height, symbolType) {
  24582. var scale = isSVG ? 1 : dpr;
  24583. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  24584. if (isSVG) {
  24585. svgRoot.appendChild(zr.painter.paintOne(symbol));
  24586. } else {
  24587. // Paint to canvas for all other renderers.
  24588. brushSingle(ctx, symbol);
  24589. }
  24590. }
  24591. }
  24592. }
  24593. }
  24594. /**
  24595. * Convert symbol array into normalized array
  24596. *
  24597. * @param {string | (string | string[])[]} symbol symbol input
  24598. * @return {string[][]} normolized symbol array
  24599. */
  24600. function normalizeSymbolArray(symbol) {
  24601. if (!symbol || symbol.length === 0) {
  24602. return [['rect']];
  24603. }
  24604. if (typeof symbol === 'string') {
  24605. return [[symbol]];
  24606. }
  24607. var isAllString = true;
  24608. for (var i = 0; i < symbol.length; ++i) {
  24609. if (typeof symbol[i] !== 'string') {
  24610. isAllString = false;
  24611. break;
  24612. }
  24613. }
  24614. if (isAllString) {
  24615. return normalizeSymbolArray([symbol]);
  24616. }
  24617. var result = [];
  24618. for (var i = 0; i < symbol.length; ++i) {
  24619. if (typeof symbol[i] === 'string') {
  24620. result.push([symbol[i]]);
  24621. } else {
  24622. result.push(symbol[i]);
  24623. }
  24624. }
  24625. return result;
  24626. }
  24627. /**
  24628. * Convert dash input into dashArray
  24629. *
  24630. * @param {DecalDashArrayX} dash dash input
  24631. * @return {number[][]} normolized dash array
  24632. */
  24633. function normalizeDashArrayX(dash) {
  24634. if (!dash || dash.length === 0) {
  24635. return [[0, 0]];
  24636. }
  24637. if (typeof dash === 'number') {
  24638. var dashValue = Math.ceil(dash);
  24639. return [[dashValue, dashValue]];
  24640. }
  24641. /**
  24642. * [20, 5] should be normalized into [[20, 5]],
  24643. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  24644. */
  24645. var isAllNumber = true;
  24646. for (var i = 0; i < dash.length; ++i) {
  24647. if (typeof dash[i] !== 'number') {
  24648. isAllNumber = false;
  24649. break;
  24650. }
  24651. }
  24652. if (isAllNumber) {
  24653. return normalizeDashArrayX([dash]);
  24654. }
  24655. var result = [];
  24656. for (var i = 0; i < dash.length; ++i) {
  24657. if (typeof dash[i] === 'number') {
  24658. var dashValue = Math.ceil(dash[i]);
  24659. result.push([dashValue, dashValue]);
  24660. } else {
  24661. var dashValue = map(dash[i], function (n) {
  24662. return Math.ceil(n);
  24663. });
  24664. if (dashValue.length % 2 === 1) {
  24665. // [4, 2, 1] means |---- - -- |---- - -- |
  24666. // so normalize it to be [4, 2, 1, 4, 2, 1]
  24667. result.push(dashValue.concat(dashValue));
  24668. } else {
  24669. result.push(dashValue);
  24670. }
  24671. }
  24672. }
  24673. return result;
  24674. }
  24675. /**
  24676. * Convert dash input into dashArray
  24677. *
  24678. * @param {DecalDashArrayY} dash dash input
  24679. * @return {number[]} normolized dash array
  24680. */
  24681. function normalizeDashArrayY(dash) {
  24682. if (!dash || typeof dash === 'object' && dash.length === 0) {
  24683. return [0, 0];
  24684. }
  24685. if (typeof dash === 'number') {
  24686. var dashValue_1 = Math.ceil(dash);
  24687. return [dashValue_1, dashValue_1];
  24688. }
  24689. var dashValue = map(dash, function (n) {
  24690. return Math.ceil(n);
  24691. });
  24692. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  24693. }
  24694. /**
  24695. * Get block length of each line. A block is the length of dash line and space.
  24696. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  24697. * that, so the block length of this line is 5.
  24698. *
  24699. * @param {number[][]} dash dash arrary of X or Y
  24700. * @return {number[]} block length of each line
  24701. */
  24702. function getLineBlockLengthX(dash) {
  24703. return map(dash, function (line) {
  24704. return getLineBlockLengthY(line);
  24705. });
  24706. }
  24707. function getLineBlockLengthY(dash) {
  24708. var blockLength = 0;
  24709. for (var i = 0; i < dash.length; ++i) {
  24710. blockLength += dash[i];
  24711. }
  24712. if (dash.length % 2 === 1) {
  24713. // [4, 2, 1] means |---- - -- |---- - -- |
  24714. // So total length is (4 + 2 + 1) * 2
  24715. return blockLength * 2;
  24716. }
  24717. return blockLength;
  24718. }
  24719. function decalVisual(ecModel, api) {
  24720. ecModel.eachRawSeries(function (seriesModel) {
  24721. if (ecModel.isSeriesFiltered(seriesModel)) {
  24722. return;
  24723. }
  24724. var data = seriesModel.getData();
  24725. if (data.hasItemVisual()) {
  24726. data.each(function (idx) {
  24727. var decal = data.getItemVisual(idx, 'decal');
  24728. if (decal) {
  24729. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  24730. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  24731. }
  24732. });
  24733. }
  24734. var decal = data.getVisual('decal');
  24735. if (decal) {
  24736. var style = data.getVisual('style');
  24737. style.decal = createOrUpdatePatternFromDecal(decal, api);
  24738. }
  24739. });
  24740. }
  24741. var assert$1 = assert;
  24742. var each$3 = each;
  24743. var isFunction$1 = isFunction;
  24744. var isObject$2 = isObject;
  24745. var indexOf$1 = indexOf;
  24746. var hasWindow = typeof window !== 'undefined';
  24747. var version$1 = '5.0.2';
  24748. var dependencies = {
  24749. zrender: '5.0.4'
  24750. };
  24751. var TEST_FRAME_REMAIN_TIME = 1;
  24752. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  24753. // So data stack stage should be in front of data processing stage.
  24754. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  24755. // put at the begining of data processing.
  24756. var PRIORITY_PROCESSOR_FILTER = 1000;
  24757. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  24758. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24759. var PRIORITY_VISUAL_LAYOUT = 1000;
  24760. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24761. var PRIORITY_VISUAL_GLOBAL = 2000;
  24762. var PRIORITY_VISUAL_CHART = 3000;
  24763. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  24764. // overwrite the viusal result of component (like `visualMap`)
  24765. // using data item specific setting (like itemStyle.xxx on data item)
  24766. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  24767. // visual result like `symbolSize`.
  24768. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  24769. var PRIORITY_VISUAL_BRUSH = 5000;
  24770. var PRIORITY_VISUAL_ARIA = 6000;
  24771. var PRIORITY_VISUAL_DECAL = 7000;
  24772. var PRIORITY = {
  24773. PROCESSOR: {
  24774. FILTER: PRIORITY_PROCESSOR_FILTER,
  24775. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24776. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24777. },
  24778. VISUAL: {
  24779. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24780. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24781. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24782. CHART: PRIORITY_VISUAL_CHART,
  24783. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24784. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24785. BRUSH: PRIORITY_VISUAL_BRUSH,
  24786. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  24787. ARIA: PRIORITY_VISUAL_ARIA,
  24788. DECAL: PRIORITY_VISUAL_DECAL
  24789. }
  24790. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24791. // where they must not be invoked nestedly, except the only case: invoke
  24792. // dispatchAction with updateMethod "none" in main process.
  24793. // This flag is used to carry out this rule.
  24794. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24795. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  24796. var OPTION_UPDATED_KEY = '__optionUpdated';
  24797. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  24798. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24799. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  24800. var CONNECT_STATUS_PENDING = 0;
  24801. var CONNECT_STATUS_UPDATING = 1;
  24802. var CONNECT_STATUS_UPDATED = 2;
  24803. function createRegisterEventWithLowercaseECharts(method) {
  24804. return function () {
  24805. var args = [];
  24806. for (var _i = 0; _i < arguments.length; _i++) {
  24807. args[_i] = arguments[_i];
  24808. }
  24809. if (this.isDisposed()) {
  24810. disposedWarning(this.id);
  24811. return;
  24812. }
  24813. return toLowercaseNameAndCallEventful(this, method, args);
  24814. };
  24815. }
  24816. function createRegisterEventWithLowercaseMessageCenter(method) {
  24817. return function () {
  24818. var args = [];
  24819. for (var _i = 0; _i < arguments.length; _i++) {
  24820. args[_i] = arguments[_i];
  24821. }
  24822. return toLowercaseNameAndCallEventful(this, method, args);
  24823. };
  24824. }
  24825. function toLowercaseNameAndCallEventful(host, method, args) {
  24826. // `args[0]` is event name. Event name is all lowercase.
  24827. args[0] = args[0] && args[0].toLowerCase();
  24828. return Eventful.prototype[method].apply(host, args);
  24829. }
  24830. var MessageCenter =
  24831. /** @class */
  24832. function (_super) {
  24833. __extends(MessageCenter, _super);
  24834. function MessageCenter() {
  24835. return _super !== null && _super.apply(this, arguments) || this;
  24836. }
  24837. return MessageCenter;
  24838. }(Eventful);
  24839. var messageCenterProto = MessageCenter.prototype;
  24840. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  24841. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  24842. // Internal method names for class ECharts
  24843. // ---------------------------------------
  24844. var prepare;
  24845. var prepareView;
  24846. var updateDirectly;
  24847. var updateMethods;
  24848. var doConvertPixel;
  24849. var updateStreamModes;
  24850. var doDispatchAction;
  24851. var flushPendingActions;
  24852. var triggerUpdatedEvent;
  24853. var bindRenderedEvent;
  24854. var bindMouseEvent;
  24855. var clearColorPalette;
  24856. var render;
  24857. var renderComponents;
  24858. var renderSeries;
  24859. var performPostUpdateFuncs;
  24860. var createExtensionAPI;
  24861. var enableConnect;
  24862. var setTransitionOpt;
  24863. var markStatusToUpdate;
  24864. var applyChangedStates;
  24865. var ECharts =
  24866. /** @class */
  24867. function (_super) {
  24868. __extends(ECharts, _super);
  24869. function ECharts(dom, // Theme name or themeOption.
  24870. theme, opts) {
  24871. var _this = _super.call(this, new ECEventProcessor()) || this;
  24872. _this._chartsViews = [];
  24873. _this._chartsMap = {};
  24874. _this._componentsViews = [];
  24875. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  24876. _this._pendingActions = [];
  24877. opts = opts || {}; // Get theme by name
  24878. if (typeof theme === 'string') {
  24879. theme = themeStorage[theme];
  24880. }
  24881. _this._dom = dom;
  24882. var defaultRenderer = 'canvas';
  24883. var defaultUseDirtyRect = false;
  24884. if ("development" !== 'production') {
  24885. var root =
  24886. /* eslint-disable-next-line */
  24887. hasWindow ? window : global;
  24888. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24889. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  24890. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  24891. }
  24892. var zr = _this._zr = init(dom, {
  24893. renderer: opts.renderer || defaultRenderer,
  24894. devicePixelRatio: opts.devicePixelRatio,
  24895. width: opts.width,
  24896. height: opts.height,
  24897. useDirtyRect: opts.useDirtyRect == null ? defaultUseDirtyRect : opts.useDirtyRect
  24898. }); // Expect 60 fps.
  24899. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24900. theme = clone(theme);
  24901. theme && globalBackwardCompat(theme, true);
  24902. _this._theme = theme;
  24903. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  24904. _this._coordSysMgr = new CoordinateSystemManager();
  24905. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  24906. function prioritySortFunc(a, b) {
  24907. return a.__prio - b.__prio;
  24908. }
  24909. sort(visualFuncs, prioritySortFunc);
  24910. sort(dataProcessorFuncs, prioritySortFunc);
  24911. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  24912. _this._messageCenter = new MessageCenter();
  24913. _this._labelManager = new LabelManager(); // Init mouse events
  24914. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  24915. _this.resize = bind(_this.resize, _this);
  24916. zr.animation.on('frame', _this._onframe, _this);
  24917. bindRenderedEvent(zr, _this);
  24918. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  24919. setAsPrimitive(_this);
  24920. return _this;
  24921. }
  24922. ECharts.prototype._onframe = function () {
  24923. if (this._disposed) {
  24924. return;
  24925. }
  24926. applyChangedStates(this);
  24927. var scheduler = this._scheduler; // Lazy update
  24928. if (this[OPTION_UPDATED_KEY]) {
  24929. var silent = this[OPTION_UPDATED_KEY].silent;
  24930. this[IN_MAIN_PROCESS_KEY] = true;
  24931. prepare(this);
  24932. updateMethods.update.call(this); // At present, in each frame, zrender performs:
  24933. // (1) animation step forward.
  24934. // (2) trigger('frame') (where this `_onframe` is called)
  24935. // (3) zrender flush (render).
  24936. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  24937. // will render the final state of the elements before the real animation started.
  24938. this._zr.flush();
  24939. this[IN_MAIN_PROCESS_KEY] = false;
  24940. this[OPTION_UPDATED_KEY] = false;
  24941. flushPendingActions.call(this, silent);
  24942. triggerUpdatedEvent.call(this, silent);
  24943. } // Avoid do both lazy update and progress in one frame.
  24944. else if (scheduler.unfinished) {
  24945. // Stream progress.
  24946. var remainTime = TEST_FRAME_REMAIN_TIME;
  24947. var ecModel = this._model;
  24948. var api = this._api;
  24949. scheduler.unfinished = false;
  24950. do {
  24951. var startTime = +new Date();
  24952. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  24953. scheduler.performDataProcessorTasks(ecModel);
  24954. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  24955. // each frame is not a good user experience. So we follow the rule that
  24956. // the extent of the coordinate system is determin in the first frame (the
  24957. // frame is executed immedietely after task reset.
  24958. // this._coordSysMgr.update(ecModel, api);
  24959. // console.log('--- ec frame visual ---', remainTime);
  24960. scheduler.performVisualTasks(ecModel);
  24961. renderSeries(this, this._model, api, 'remain');
  24962. remainTime -= +new Date() - startTime;
  24963. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  24964. if (!scheduler.unfinished) {
  24965. this._zr.flush();
  24966. } // Else, zr flushing be ensue within the same frame,
  24967. // because zr flushing is after onframe event.
  24968. }
  24969. };
  24970. ECharts.prototype.getDom = function () {
  24971. return this._dom;
  24972. };
  24973. ECharts.prototype.getId = function () {
  24974. return this.id;
  24975. };
  24976. ECharts.prototype.getZr = function () {
  24977. return this._zr;
  24978. };
  24979. /* eslint-disable-next-line */
  24980. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  24981. if ("development" !== 'production') {
  24982. assert$1(!this[IN_MAIN_PROCESS_KEY], '`setOption` should not be called during main process.');
  24983. }
  24984. if (this._disposed) {
  24985. disposedWarning(this.id);
  24986. return;
  24987. }
  24988. var silent;
  24989. var replaceMerge;
  24990. var transitionOpt;
  24991. if (isObject$2(notMerge)) {
  24992. lazyUpdate = notMerge.lazyUpdate;
  24993. silent = notMerge.silent;
  24994. replaceMerge = notMerge.replaceMerge;
  24995. transitionOpt = notMerge.transition;
  24996. notMerge = notMerge.notMerge;
  24997. }
  24998. this[IN_MAIN_PROCESS_KEY] = true;
  24999. if (!this._model || notMerge) {
  25000. var optionManager = new OptionManager(this._api);
  25001. var theme = this._theme;
  25002. var ecModel = this._model = new GlobalModel();
  25003. ecModel.scheduler = this._scheduler;
  25004. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25005. }
  25006. this._model.setOption(option, {
  25007. replaceMerge: replaceMerge
  25008. }, optionPreprocessorFuncs);
  25009. setTransitionOpt(this, transitionOpt);
  25010. if (lazyUpdate) {
  25011. this[OPTION_UPDATED_KEY] = {
  25012. silent: silent
  25013. };
  25014. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25015. // It should wake it up to make sure zrender start to render at the next frame.
  25016. this.getZr().wakeUp();
  25017. } else {
  25018. prepare(this);
  25019. updateMethods.update.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be
  25020. // fetched after `setOption`.
  25021. this._zr.flush();
  25022. this[OPTION_UPDATED_KEY] = false;
  25023. this[IN_MAIN_PROCESS_KEY] = false;
  25024. flushPendingActions.call(this, silent);
  25025. triggerUpdatedEvent.call(this, silent);
  25026. }
  25027. };
  25028. /**
  25029. * @DEPRECATED
  25030. */
  25031. ECharts.prototype.setTheme = function () {
  25032. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25033. }; // We don't want developers to use getModel directly.
  25034. ECharts.prototype.getModel = function () {
  25035. return this._model;
  25036. };
  25037. ECharts.prototype.getOption = function () {
  25038. return this._model && this._model.getOption();
  25039. };
  25040. ECharts.prototype.getWidth = function () {
  25041. return this._zr.getWidth();
  25042. };
  25043. ECharts.prototype.getHeight = function () {
  25044. return this._zr.getHeight();
  25045. };
  25046. ECharts.prototype.getDevicePixelRatio = function () {
  25047. return this._zr.painter.dpr
  25048. /* eslint-disable-next-line */
  25049. || hasWindow && window.devicePixelRatio || 1;
  25050. };
  25051. /**
  25052. * Get canvas which has all thing rendered
  25053. */
  25054. ECharts.prototype.getRenderedCanvas = function (opts) {
  25055. if (!env.canvasSupported) {
  25056. return;
  25057. }
  25058. opts = extend({}, opts || {});
  25059. opts.pixelRatio = opts.pixelRatio || this.getDevicePixelRatio();
  25060. opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor');
  25061. var zr = this._zr; // let list = zr.storage.getDisplayList();
  25062. // Stop animations
  25063. // Never works before in init animation, so remove it.
  25064. // zrUtil.each(list, function (el) {
  25065. // el.stopAnimation(true);
  25066. // });
  25067. return zr.painter.getRenderedCanvas(opts);
  25068. };
  25069. /**
  25070. * Get svg data url
  25071. */
  25072. ECharts.prototype.getSvgDataURL = function () {
  25073. if (!env.svgSupported) {
  25074. return;
  25075. }
  25076. var zr = this._zr;
  25077. var list = zr.storage.getDisplayList(); // Stop animations
  25078. each(list, function (el) {
  25079. el.stopAnimation(null, true);
  25080. });
  25081. return zr.painter.toDataURL();
  25082. };
  25083. ECharts.prototype.getDataURL = function (opts) {
  25084. if (this._disposed) {
  25085. disposedWarning(this.id);
  25086. return;
  25087. }
  25088. opts = opts || {};
  25089. var excludeComponents = opts.excludeComponents;
  25090. var ecModel = this._model;
  25091. var excludesComponentViews = [];
  25092. var self = this;
  25093. each$3(excludeComponents, function (componentType) {
  25094. ecModel.eachComponent({
  25095. mainType: componentType
  25096. }, function (component) {
  25097. var view = self._componentsMap[component.__viewId];
  25098. if (!view.group.ignore) {
  25099. excludesComponentViews.push(view);
  25100. view.group.ignore = true;
  25101. }
  25102. });
  25103. });
  25104. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  25105. each$3(excludesComponentViews, function (view) {
  25106. view.group.ignore = false;
  25107. });
  25108. return url;
  25109. };
  25110. ECharts.prototype.getConnectedDataURL = function (opts) {
  25111. if (this._disposed) {
  25112. disposedWarning(this.id);
  25113. return;
  25114. }
  25115. if (!env.canvasSupported) {
  25116. return;
  25117. }
  25118. var isSvg = opts.type === 'svg';
  25119. var groupId = this.group;
  25120. var mathMin = Math.min;
  25121. var mathMax = Math.max;
  25122. var MAX_NUMBER = Infinity;
  25123. if (connectedGroups[groupId]) {
  25124. var left_1 = MAX_NUMBER;
  25125. var top_1 = MAX_NUMBER;
  25126. var right_1 = -MAX_NUMBER;
  25127. var bottom_1 = -MAX_NUMBER;
  25128. var canvasList_1 = [];
  25129. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  25130. each(instances$1, function (chart, id) {
  25131. if (chart.group === groupId) {
  25132. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.getRenderedCanvas(clone(opts));
  25133. var boundingRect = chart.getDom().getBoundingClientRect();
  25134. left_1 = mathMin(boundingRect.left, left_1);
  25135. top_1 = mathMin(boundingRect.top, top_1);
  25136. right_1 = mathMax(boundingRect.right, right_1);
  25137. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  25138. canvasList_1.push({
  25139. dom: canvas,
  25140. left: boundingRect.left,
  25141. top: boundingRect.top
  25142. });
  25143. }
  25144. });
  25145. left_1 *= dpr_1;
  25146. top_1 *= dpr_1;
  25147. right_1 *= dpr_1;
  25148. bottom_1 *= dpr_1;
  25149. var width = right_1 - left_1;
  25150. var height = bottom_1 - top_1;
  25151. var targetCanvas = createCanvas();
  25152. var zr_1 = init(targetCanvas, {
  25153. renderer: isSvg ? 'svg' : 'canvas'
  25154. });
  25155. zr_1.resize({
  25156. width: width,
  25157. height: height
  25158. });
  25159. if (isSvg) {
  25160. var content_1 = '';
  25161. each$3(canvasList_1, function (item) {
  25162. var x = item.left - left_1;
  25163. var y = item.top - top_1;
  25164. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  25165. });
  25166. zr_1.painter.getSvgRoot().innerHTML = content_1;
  25167. if (opts.connectedBackgroundColor) {
  25168. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  25169. }
  25170. zr_1.refreshImmediately();
  25171. return zr_1.painter.toDataURL();
  25172. } else {
  25173. // Background between the charts
  25174. if (opts.connectedBackgroundColor) {
  25175. zr_1.add(new Rect({
  25176. shape: {
  25177. x: 0,
  25178. y: 0,
  25179. width: width,
  25180. height: height
  25181. },
  25182. style: {
  25183. fill: opts.connectedBackgroundColor
  25184. }
  25185. }));
  25186. }
  25187. each$3(canvasList_1, function (item) {
  25188. var img = new ZRImage({
  25189. style: {
  25190. x: item.left * dpr_1 - left_1,
  25191. y: item.top * dpr_1 - top_1,
  25192. image: item.dom
  25193. }
  25194. });
  25195. zr_1.add(img);
  25196. });
  25197. zr_1.refreshImmediately();
  25198. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  25199. }
  25200. } else {
  25201. return this.getDataURL(opts);
  25202. }
  25203. };
  25204. ECharts.prototype.convertToPixel = function (finder, value) {
  25205. return doConvertPixel(this, 'convertToPixel', finder, value);
  25206. };
  25207. ECharts.prototype.convertFromPixel = function (finder, value) {
  25208. return doConvertPixel(this, 'convertFromPixel', finder, value);
  25209. };
  25210. /**
  25211. * Is the specified coordinate systems or components contain the given pixel point.
  25212. * @param {Array|number} value
  25213. * @return {boolean} result
  25214. */
  25215. ECharts.prototype.containPixel = function (finder, value) {
  25216. if (this._disposed) {
  25217. disposedWarning(this.id);
  25218. return;
  25219. }
  25220. var ecModel = this._model;
  25221. var result;
  25222. var findResult = parseFinder(ecModel, finder);
  25223. each(findResult, function (models, key) {
  25224. key.indexOf('Models') >= 0 && each(models, function (model) {
  25225. var coordSys = model.coordinateSystem;
  25226. if (coordSys && coordSys.containPoint) {
  25227. result = result || !!coordSys.containPoint(value);
  25228. } else if (key === 'seriesModels') {
  25229. var view = this._chartsMap[model.__viewId];
  25230. if (view && view.containPoint) {
  25231. result = result || view.containPoint(value, model);
  25232. } else {
  25233. if ("development" !== 'production') {
  25234. console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  25235. }
  25236. }
  25237. } else {
  25238. if ("development" !== 'production') {
  25239. console.warn(key + ': containPoint is not supported');
  25240. }
  25241. }
  25242. }, this);
  25243. }, this);
  25244. return !!result;
  25245. };
  25246. /**
  25247. * Get visual from series or data.
  25248. * @param finder
  25249. * If string, e.g., 'series', means {seriesIndex: 0}.
  25250. * If Object, could contain some of these properties below:
  25251. * {
  25252. * seriesIndex / seriesId / seriesName,
  25253. * dataIndex / dataIndexInside
  25254. * }
  25255. * If dataIndex is not specified, series visual will be fetched,
  25256. * but not data item visual.
  25257. * If all of seriesIndex, seriesId, seriesName are not specified,
  25258. * visual will be fetched from first series.
  25259. * @param visualType 'color', 'symbol', 'symbolSize'
  25260. */
  25261. ECharts.prototype.getVisual = function (finder, visualType) {
  25262. var ecModel = this._model;
  25263. var parsedFinder = parseFinder(ecModel, finder, {
  25264. defaultMainType: 'series'
  25265. });
  25266. var seriesModel = parsedFinder.seriesModel;
  25267. if ("development" !== 'production') {
  25268. if (!seriesModel) {
  25269. console.warn('There is no specified seires model');
  25270. }
  25271. }
  25272. var data = seriesModel.getData();
  25273. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  25274. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  25275. };
  25276. /**
  25277. * Get view of corresponding component model
  25278. */
  25279. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  25280. return this._componentsMap[componentModel.__viewId];
  25281. };
  25282. /**
  25283. * Get view of corresponding series model
  25284. */
  25285. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  25286. return this._chartsMap[seriesModel.__viewId];
  25287. };
  25288. ECharts.prototype._initEvents = function () {
  25289. var _this = this;
  25290. each$3(MOUSE_EVENT_NAMES, function (eveName) {
  25291. var handler = function (e) {
  25292. var ecModel = _this.getModel();
  25293. var el = e.target;
  25294. var params;
  25295. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  25296. if (isGlobalOut) {
  25297. params = {};
  25298. } else {
  25299. el && findEventDispatcher(el, function (parent) {
  25300. var ecData = getECData(parent);
  25301. if (ecData && ecData.dataIndex != null) {
  25302. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  25303. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  25304. return true;
  25305. } // If element has custom eventData of components
  25306. else if (ecData.eventData) {
  25307. params = extend({}, ecData.eventData);
  25308. return true;
  25309. }
  25310. }, true);
  25311. } // Contract: if params prepared in mouse event,
  25312. // these properties must be specified:
  25313. // {
  25314. // componentType: string (component main type)
  25315. // componentIndex: number
  25316. // }
  25317. // Otherwise event query can not work.
  25318. if (params) {
  25319. var componentType = params.componentType;
  25320. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  25321. // markLine/markPoint/markArea, the componentType is
  25322. // 'markLine'/'markPoint'/'markArea', but we should better
  25323. // enable them to be queried by seriesIndex, since their
  25324. // option is set in each series.
  25325. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  25326. componentType = 'series';
  25327. componentIndex = params.seriesIndex;
  25328. }
  25329. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  25330. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  25331. if ("development" !== 'production') {
  25332. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25333. // be missed, otherwise there is no way to distinguish source component.
  25334. // See `dataFormat.getDataParams`.
  25335. if (!isGlobalOut && !(model && view)) {
  25336. console.warn('model or view can not be found by params');
  25337. }
  25338. }
  25339. params.event = e;
  25340. params.type = eveName;
  25341. _this._$eventProcessor.eventInfo = {
  25342. targetEl: el,
  25343. packedEvent: params,
  25344. model: model,
  25345. view: view
  25346. };
  25347. _this.trigger(eveName, params);
  25348. }
  25349. }; // Consider that some component (like tooltip, brush, ...)
  25350. // register zr event handler, but user event handler might
  25351. // do anything, such as call `setOption` or `dispatchAction`,
  25352. // which probably update any of the content and probably
  25353. // cause problem if it is called previous other inner handlers.
  25354. handler.zrEventfulCallAtLast = true;
  25355. _this._zr.on(eveName, handler, _this);
  25356. });
  25357. each$3(eventActionMap, function (actionType, eventType) {
  25358. _this._messageCenter.on(eventType, function (event) {
  25359. this.trigger(eventType, event);
  25360. }, _this);
  25361. }); // Extra events
  25362. // TODO register?
  25363. each$3(['selectchanged'], function (eventType) {
  25364. _this._messageCenter.on(eventType, function (event) {
  25365. this.trigger(eventType, event);
  25366. }, _this);
  25367. });
  25368. handleLegacySelectEvents(this._messageCenter, this, this._api);
  25369. };
  25370. ECharts.prototype.isDisposed = function () {
  25371. return this._disposed;
  25372. };
  25373. ECharts.prototype.clear = function () {
  25374. if (this._disposed) {
  25375. disposedWarning(this.id);
  25376. return;
  25377. }
  25378. this.setOption({
  25379. series: []
  25380. }, true);
  25381. };
  25382. ECharts.prototype.dispose = function () {
  25383. if (this._disposed) {
  25384. disposedWarning(this.id);
  25385. return;
  25386. }
  25387. this._disposed = true;
  25388. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25389. var api = this._api;
  25390. var ecModel = this._model;
  25391. each$3(this._componentsViews, function (component) {
  25392. component.dispose(ecModel, api);
  25393. });
  25394. each$3(this._chartsViews, function (chart) {
  25395. chart.dispose(ecModel, api);
  25396. }); // Dispose after all views disposed
  25397. this._zr.dispose();
  25398. delete instances$1[this.id];
  25399. };
  25400. /**
  25401. * Resize the chart
  25402. */
  25403. ECharts.prototype.resize = function (opts) {
  25404. if ("development" !== 'production') {
  25405. assert$1(!this[IN_MAIN_PROCESS_KEY], '`resize` should not be called during main process.');
  25406. }
  25407. if (this._disposed) {
  25408. disposedWarning(this.id);
  25409. return;
  25410. }
  25411. this._zr.resize(opts);
  25412. var ecModel = this._model; // Resize loading effect
  25413. this._loadingFX && this._loadingFX.resize();
  25414. if (!ecModel) {
  25415. return;
  25416. }
  25417. var optionChanged = ecModel.resetOption('media');
  25418. var silent = opts && opts.silent;
  25419. this[IN_MAIN_PROCESS_KEY] = true;
  25420. optionChanged && prepare(this);
  25421. updateMethods.update.call(this, {
  25422. type: 'resize',
  25423. animation: {
  25424. // Disable animation
  25425. duration: 0
  25426. }
  25427. });
  25428. this[IN_MAIN_PROCESS_KEY] = false;
  25429. flushPendingActions.call(this, silent);
  25430. triggerUpdatedEvent.call(this, silent);
  25431. };
  25432. ECharts.prototype.showLoading = function (name, cfg) {
  25433. if (this._disposed) {
  25434. disposedWarning(this.id);
  25435. return;
  25436. }
  25437. if (isObject$2(name)) {
  25438. cfg = name;
  25439. name = '';
  25440. }
  25441. name = name || 'default';
  25442. this.hideLoading();
  25443. if (!loadingEffects[name]) {
  25444. if ("development" !== 'production') {
  25445. console.warn('Loading effects ' + name + ' not exists.');
  25446. }
  25447. return;
  25448. }
  25449. var el = loadingEffects[name](this._api, cfg);
  25450. var zr = this._zr;
  25451. this._loadingFX = el;
  25452. zr.add(el);
  25453. };
  25454. /**
  25455. * Hide loading effect
  25456. */
  25457. ECharts.prototype.hideLoading = function () {
  25458. if (this._disposed) {
  25459. disposedWarning(this.id);
  25460. return;
  25461. }
  25462. this._loadingFX && this._zr.remove(this._loadingFX);
  25463. this._loadingFX = null;
  25464. };
  25465. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  25466. var payload = extend({}, eventObj);
  25467. payload.type = eventActionMap[eventObj.type];
  25468. return payload;
  25469. };
  25470. /**
  25471. * @param opt If pass boolean, means opt.silent
  25472. * @param opt.silent Default `false`. Whether trigger events.
  25473. * @param opt.flush Default `undefined`.
  25474. * true: Flush immediately, and then pixel in canvas can be fetched
  25475. * immediately. Caution: it might affect performance.
  25476. * false: Not flush.
  25477. * undefined: Auto decide whether perform flush.
  25478. */
  25479. ECharts.prototype.dispatchAction = function (payload, opt) {
  25480. if (this._disposed) {
  25481. disposedWarning(this.id);
  25482. return;
  25483. }
  25484. if (!isObject$2(opt)) {
  25485. opt = {
  25486. silent: !!opt
  25487. };
  25488. }
  25489. if (!actions[payload.type]) {
  25490. return;
  25491. } // Avoid dispatch action before setOption. Especially in `connect`.
  25492. if (!this._model) {
  25493. return;
  25494. } // May dispatchAction in rendering procedure
  25495. if (this[IN_MAIN_PROCESS_KEY]) {
  25496. this._pendingActions.push(payload);
  25497. return;
  25498. }
  25499. var silent = opt.silent;
  25500. doDispatchAction.call(this, payload, silent);
  25501. var flush = opt.flush;
  25502. if (flush) {
  25503. this._zr.flush();
  25504. } else if (flush !== false && env.browser.weChat) {
  25505. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25506. // hang when sliding page (on touch event), which cause that zr does not
  25507. // refresh util user interaction finished, which is not expected.
  25508. // But `dispatchAction` may be called too frequently when pan on touch
  25509. // screen, which impacts performance if do not throttle them.
  25510. this._throttledZrFlush();
  25511. }
  25512. flushPendingActions.call(this, silent);
  25513. triggerUpdatedEvent.call(this, silent);
  25514. };
  25515. ECharts.prototype.updateLabelLayout = function () {
  25516. var labelManager = this._labelManager;
  25517. labelManager.updateLayoutConfig(this._api);
  25518. labelManager.layout(this._api);
  25519. labelManager.processLabelsOverall();
  25520. };
  25521. ECharts.prototype.appendData = function (params) {
  25522. if (this._disposed) {
  25523. disposedWarning(this.id);
  25524. return;
  25525. }
  25526. var seriesIndex = params.seriesIndex;
  25527. var ecModel = this.getModel();
  25528. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25529. if ("development" !== 'production') {
  25530. assert$1(params.data && seriesModel);
  25531. }
  25532. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  25533. // system, util some scenario require that. In the expected usage of
  25534. // `appendData`, the initial extent of coordinate system should better
  25535. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25536. // the extent changed while `appendData`, the location of the painted
  25537. // graphic elements have to be changed, which make the usage of
  25538. // `appendData` meaningless.
  25539. this._scheduler.unfinished = true;
  25540. this.getZr().wakeUp();
  25541. }; // A work around for no `internal` modifier in ts yet but
  25542. // need to strictly hide private methods to JS users.
  25543. ECharts.internalField = function () {
  25544. prepare = function (ecIns) {
  25545. var scheduler = ecIns._scheduler;
  25546. scheduler.restorePipelines(ecIns._model);
  25547. scheduler.prepareStageTasks();
  25548. prepareView(ecIns, true);
  25549. prepareView(ecIns, false);
  25550. scheduler.plan();
  25551. };
  25552. /**
  25553. * Prepare view instances of charts and components
  25554. */
  25555. prepareView = function (ecIns, isComponent) {
  25556. var ecModel = ecIns._model;
  25557. var scheduler = ecIns._scheduler;
  25558. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25559. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25560. var zr = ecIns._zr;
  25561. var api = ecIns._api;
  25562. for (var i = 0; i < viewList.length; i++) {
  25563. viewList[i].__alive = false;
  25564. }
  25565. isComponent ? ecModel.eachComponent(function (componentType, model) {
  25566. componentType !== 'series' && doPrepare(model);
  25567. }) : ecModel.eachSeries(doPrepare);
  25568. function doPrepare(model) {
  25569. // By defaut view will be reused if possible for the case that `setOption` with "notMerge"
  25570. // mode and need to enable transition animation. (Usually, when they have the same id, or
  25571. // especially no id but have the same type & name & index. See the `model.id` generation
  25572. // rule in `makeIdAndName` and `viewId` generation rule here).
  25573. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  25574. // the new model has nothing to do with the old model.
  25575. var requireNewView = model.__requireNewView; // This command should not work twice.
  25576. model.__requireNewView = false; // Consider: id same and type changed.
  25577. var viewId = '_ec_' + model.id + '_' + model.type;
  25578. var view = !requireNewView && viewMap[viewId];
  25579. if (!view) {
  25580. var classType = parseClassType(model.type);
  25581. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  25582. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  25583. // For backward compat, still support a chart type declared as only subType
  25584. // like "liquidfill", but recommend "series.liquidfill"
  25585. // But need a base class to make a type series.
  25586. ChartView.getClass(classType.sub);
  25587. if ("development" !== 'production') {
  25588. assert$1(Clazz, classType.sub + ' does not exist.');
  25589. }
  25590. view = new Clazz();
  25591. view.init(ecModel, api);
  25592. viewMap[viewId] = view;
  25593. viewList.push(view);
  25594. zr.add(view.group);
  25595. }
  25596. model.__viewId = view.__id = viewId;
  25597. view.__alive = true;
  25598. view.__model = model;
  25599. view.group.__ecComponentInfo = {
  25600. mainType: model.mainType,
  25601. index: model.componentIndex
  25602. };
  25603. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25604. }
  25605. for (var i = 0; i < viewList.length;) {
  25606. var view = viewList[i];
  25607. if (!view.__alive) {
  25608. !isComponent && view.renderTask.dispose();
  25609. zr.remove(view.group);
  25610. view.dispose(ecModel, api);
  25611. viewList.splice(i, 1);
  25612. if (viewMap[view.__id] === view) {
  25613. delete viewMap[view.__id];
  25614. }
  25615. view.__id = view.group.__ecComponentInfo = null;
  25616. } else {
  25617. i++;
  25618. }
  25619. }
  25620. };
  25621. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  25622. var ecModel = ecIns._model;
  25623. ecModel.setUpdatePayload(payload); // broadcast
  25624. if (!mainType) {
  25625. // FIXME
  25626. // Chart will not be update directly here, except set dirty.
  25627. // But there is no such scenario now.
  25628. each$3([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  25629. return;
  25630. }
  25631. var query = {};
  25632. query[mainType + 'Id'] = payload[mainType + 'Id'];
  25633. query[mainType + 'Index'] = payload[mainType + 'Index'];
  25634. query[mainType + 'Name'] = payload[mainType + 'Name'];
  25635. var condition = {
  25636. mainType: mainType,
  25637. query: query
  25638. };
  25639. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  25640. var excludeSeriesId = payload.excludeSeriesId;
  25641. var excludeSeriesIdMap;
  25642. if (excludeSeriesId != null) {
  25643. excludeSeriesIdMap = createHashMap();
  25644. each$3(normalizeToArray(excludeSeriesId), function (id) {
  25645. var modelId = convertOptionIdName(id, null);
  25646. if (modelId != null) {
  25647. excludeSeriesIdMap.set(modelId, true);
  25648. }
  25649. });
  25650. } // If dispatchAction before setOption, do nothing.
  25651. ecModel && ecModel.eachComponent(condition, function (model) {
  25652. if (!excludeSeriesIdMap || excludeSeriesIdMap.get(model.id) == null) {
  25653. if (isHighDownPayload(payload) && !payload.notBlur) {
  25654. if (model instanceof SeriesModel) {
  25655. toggleSeriesBlurStateFromPayload(model, payload, ecIns._api);
  25656. }
  25657. } else if (isSelectChangePayload(payload)) {
  25658. // TODO geo
  25659. if (model instanceof SeriesModel) {
  25660. toggleSelectionFromPayload(model, payload, ecIns._api);
  25661. updateSeriesElementSelection(model);
  25662. markStatusToUpdate(ecIns);
  25663. }
  25664. }
  25665. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  25666. }
  25667. }, ecIns);
  25668. function callView(view) {
  25669. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  25670. }
  25671. };
  25672. updateMethods = {
  25673. prepareAndUpdate: function (payload) {
  25674. prepare(this);
  25675. updateMethods.update.call(this, payload);
  25676. },
  25677. update: function (payload) {
  25678. // console.profile && console.profile('update');
  25679. var ecModel = this._model;
  25680. var api = this._api;
  25681. var zr = this._zr;
  25682. var coordSysMgr = this._coordSysMgr;
  25683. var scheduler = this._scheduler; // update before setOption
  25684. if (!ecModel) {
  25685. return;
  25686. }
  25687. ecModel.setUpdatePayload(payload);
  25688. scheduler.restoreData(ecModel, payload);
  25689. scheduler.performSeriesTasks(ecModel); // TODO
  25690. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  25691. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  25692. // Create new coordinate system each update
  25693. // In LineView may save the old coordinate system and use it to get the orignal point
  25694. coordSysMgr.create(ecModel, api);
  25695. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  25696. // stream modes after data processing, where the filtered data is used to
  25697. // deteming whether use progressive rendering.
  25698. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  25699. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  25700. // the drawback is the full coord info can not be fetched. Fortunately this full
  25701. // coord is not requied in stream mode updater currently.
  25702. coordSysMgr.update(ecModel, api);
  25703. clearColorPalette(ecModel);
  25704. scheduler.performVisualTasks(ecModel, payload);
  25705. render(this, ecModel, api, payload); // Set background
  25706. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  25707. var darkMode = ecModel.get('darkMode'); // In IE8
  25708. if (!env.canvasSupported) {
  25709. var colorArr = parse(backgroundColor);
  25710. backgroundColor = stringify(colorArr, 'rgb');
  25711. if (colorArr[3] === 0) {
  25712. backgroundColor = 'transparent';
  25713. }
  25714. } else {
  25715. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  25716. if (darkMode != null && darkMode !== 'auto') {
  25717. zr.setDarkMode(darkMode);
  25718. }
  25719. }
  25720. performPostUpdateFuncs(ecModel, api); // console.profile && console.profileEnd('update');
  25721. },
  25722. updateTransform: function (payload) {
  25723. var _this = this;
  25724. var ecModel = this._model;
  25725. var api = this._api; // update before setOption
  25726. if (!ecModel) {
  25727. return;
  25728. }
  25729. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  25730. var componentDirtyList = [];
  25731. ecModel.eachComponent(function (componentType, componentModel) {
  25732. if (componentType === 'series') {
  25733. return;
  25734. }
  25735. var componentView = _this.getViewOfComponentModel(componentModel);
  25736. if (componentView && componentView.__alive) {
  25737. if (componentView.updateTransform) {
  25738. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  25739. result && result.update && componentDirtyList.push(componentView);
  25740. } else {
  25741. componentDirtyList.push(componentView);
  25742. }
  25743. }
  25744. });
  25745. var seriesDirtyMap = createHashMap();
  25746. ecModel.eachSeries(function (seriesModel) {
  25747. var chartView = _this._chartsMap[seriesModel.__viewId];
  25748. if (chartView.updateTransform) {
  25749. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  25750. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  25751. } else {
  25752. seriesDirtyMap.set(seriesModel.uid, 1);
  25753. }
  25754. });
  25755. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25756. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  25757. this._scheduler.performVisualTasks(ecModel, payload, {
  25758. setDirty: true,
  25759. dirtyMap: seriesDirtyMap
  25760. }); // Currently, not call render of components. Geo render cost a lot.
  25761. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  25762. renderSeries(this, ecModel, api, payload, seriesDirtyMap);
  25763. performPostUpdateFuncs(ecModel, this._api);
  25764. },
  25765. updateView: function (payload) {
  25766. var ecModel = this._model; // update before setOption
  25767. if (!ecModel) {
  25768. return;
  25769. }
  25770. ecModel.setUpdatePayload(payload);
  25771. ChartView.markUpdateMethod(payload, 'updateView');
  25772. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25773. this._scheduler.performVisualTasks(ecModel, payload, {
  25774. setDirty: true
  25775. });
  25776. render(this, this._model, this._api, payload);
  25777. performPostUpdateFuncs(ecModel, this._api);
  25778. },
  25779. updateVisual: function (payload) {
  25780. // updateMethods.update.call(this, payload);
  25781. var _this = this;
  25782. var ecModel = this._model; // update before setOption
  25783. if (!ecModel) {
  25784. return;
  25785. }
  25786. ecModel.setUpdatePayload(payload); // clear all visual
  25787. ecModel.eachSeries(function (seriesModel) {
  25788. seriesModel.getData().clearAllVisual();
  25789. }); // Perform visual
  25790. ChartView.markUpdateMethod(payload, 'updateVisual');
  25791. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25792. this._scheduler.performVisualTasks(ecModel, payload, {
  25793. visualType: 'visual',
  25794. setDirty: true
  25795. });
  25796. ecModel.eachComponent(function (componentType, componentModel) {
  25797. if (componentType !== 'series') {
  25798. var componentView = _this.getViewOfComponentModel(componentModel);
  25799. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  25800. }
  25801. });
  25802. ecModel.eachSeries(function (seriesModel) {
  25803. var chartView = _this._chartsMap[seriesModel.__viewId];
  25804. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  25805. });
  25806. performPostUpdateFuncs(ecModel, this._api);
  25807. },
  25808. updateLayout: function (payload) {
  25809. updateMethods.update.call(this, payload);
  25810. }
  25811. };
  25812. doConvertPixel = function (ecIns, methodName, finder, value) {
  25813. if (ecIns._disposed) {
  25814. disposedWarning(ecIns.id);
  25815. return;
  25816. }
  25817. var ecModel = ecIns._model;
  25818. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  25819. var result;
  25820. var parsedFinder = parseFinder(ecModel, finder);
  25821. for (var i = 0; i < coordSysList.length; i++) {
  25822. var coordSys = coordSysList[i];
  25823. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  25824. return result;
  25825. }
  25826. }
  25827. if ("development" !== 'production') {
  25828. console.warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  25829. }
  25830. };
  25831. updateStreamModes = function (ecIns, ecModel) {
  25832. var chartsMap = ecIns._chartsMap;
  25833. var scheduler = ecIns._scheduler;
  25834. ecModel.eachSeries(function (seriesModel) {
  25835. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25836. });
  25837. };
  25838. doDispatchAction = function (payload, silent) {
  25839. var _this = this;
  25840. var ecModel = this.getModel();
  25841. var payloadType = payload.type;
  25842. var escapeConnect = payload.escapeConnect;
  25843. var actionWrap = actions[payloadType];
  25844. var actionInfo = actionWrap.actionInfo;
  25845. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  25846. var updateMethod = cptTypeTmp.pop();
  25847. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  25848. this[IN_MAIN_PROCESS_KEY] = true;
  25849. var payloads = [payload];
  25850. var batched = false; // Batch action
  25851. if (payload.batch) {
  25852. batched = true;
  25853. payloads = map(payload.batch, function (item) {
  25854. item = defaults(extend({}, item), payload);
  25855. item.batch = null;
  25856. return item;
  25857. });
  25858. }
  25859. var eventObjBatch = [];
  25860. var eventObj;
  25861. var isSelectChange = isSelectChangePayload(payload);
  25862. var isStatusChange = isHighDownPayload(payload) || isSelectChange;
  25863. each$3(payloads, function (batchItem) {
  25864. // Action can specify the event by return it.
  25865. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  25866. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  25867. eventObj.type = actionInfo.event || eventObj.type;
  25868. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  25869. if (isStatusChange) {
  25870. // method, payload, mainType, subType
  25871. updateDirectly(_this, updateMethod, batchItem, 'series'); // Mark status to update
  25872. markStatusToUpdate(_this);
  25873. } else if (cptType) {
  25874. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  25875. }
  25876. });
  25877. if (updateMethod !== 'none' && !isStatusChange && !cptType) {
  25878. // Still dirty
  25879. if (this[OPTION_UPDATED_KEY]) {
  25880. prepare(this);
  25881. updateMethods.update.call(this, payload);
  25882. this[OPTION_UPDATED_KEY] = false;
  25883. } else {
  25884. updateMethods[updateMethod].call(this, payload);
  25885. }
  25886. } // Follow the rule of action batch
  25887. if (batched) {
  25888. eventObj = {
  25889. type: actionInfo.event || payloadType,
  25890. escapeConnect: escapeConnect,
  25891. batch: eventObjBatch
  25892. };
  25893. } else {
  25894. eventObj = eventObjBatch[0];
  25895. }
  25896. this[IN_MAIN_PROCESS_KEY] = false;
  25897. if (!silent) {
  25898. var messageCenter = this._messageCenter;
  25899. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  25900. if (isSelectChange) {
  25901. var newObj = {
  25902. type: 'selectchanged',
  25903. escapeConnect: escapeConnect,
  25904. selected: getAllSelectedIndices(ecModel),
  25905. isFromClick: payload.isFromClick || false,
  25906. fromAction: payload.type,
  25907. fromActionPayload: payload
  25908. };
  25909. messageCenter.trigger(newObj.type, newObj);
  25910. }
  25911. }
  25912. };
  25913. flushPendingActions = function (silent) {
  25914. var pendingActions = this._pendingActions;
  25915. while (pendingActions.length) {
  25916. var payload = pendingActions.shift();
  25917. doDispatchAction.call(this, payload, silent);
  25918. }
  25919. };
  25920. triggerUpdatedEvent = function (silent) {
  25921. !silent && this.trigger('updated');
  25922. };
  25923. /**
  25924. * Event `rendered` is triggered when zr
  25925. * rendered. It is useful for realtime
  25926. * snapshot (reflect animation).
  25927. *
  25928. * Event `finished` is triggered when:
  25929. * (1) zrender rendering finished.
  25930. * (2) initial animation finished.
  25931. * (3) progressive rendering finished.
  25932. * (4) no pending action.
  25933. * (5) no delayed setOption needs to be processed.
  25934. */
  25935. bindRenderedEvent = function (zr, ecIns) {
  25936. zr.on('rendered', function (params) {
  25937. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatly,
  25938. // so it should only be triggered when rendering indeed happend
  25939. // in zrender. (Consider the case that dipatchAction is keep
  25940. // triggering when mouse move).
  25941. if ( // Although zr is dirty if initial animation is not finished
  25942. // and this checking is called on frame, we also check
  25943. // animation finished for robustness.
  25944. zr.animation.isFinished() && !ecIns[OPTION_UPDATED_KEY] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  25945. ecIns.trigger('finished');
  25946. }
  25947. });
  25948. };
  25949. bindMouseEvent = function (zr, ecIns) {
  25950. zr.on('mouseover', function (e) {
  25951. var el = e.target;
  25952. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  25953. if (dispatcher) {
  25954. var ecData = getECData(dispatcher); // Try blur all in the related series. Then emphasis the hoverred.
  25955. // TODO. progressive mode.
  25956. toggleSeriesBlurState(ecData.seriesIndex, ecData.focus, ecData.blurScope, ecIns._api, true);
  25957. enterEmphasisWhenMouseOver(dispatcher, e);
  25958. markStatusToUpdate(ecIns);
  25959. }
  25960. }).on('mouseout', function (e) {
  25961. var el = e.target;
  25962. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  25963. if (dispatcher) {
  25964. var ecData = getECData(dispatcher);
  25965. toggleSeriesBlurState(ecData.seriesIndex, ecData.focus, ecData.blurScope, ecIns._api, false);
  25966. leaveEmphasisWhenMouseOut(dispatcher, e);
  25967. markStatusToUpdate(ecIns);
  25968. }
  25969. }).on('click', function (e) {
  25970. var el = e.target;
  25971. var dispatcher = findEventDispatcher(el, function (target) {
  25972. return getECData(target).dataIndex != null;
  25973. }, true);
  25974. if (dispatcher) {
  25975. var actionType = dispatcher.selected ? 'unselect' : 'select';
  25976. var ecData = getECData(dispatcher);
  25977. ecIns._api.dispatchAction({
  25978. type: actionType,
  25979. dataType: ecData.dataType,
  25980. dataIndexInside: ecData.dataIndex,
  25981. seriesIndex: ecData.seriesIndex,
  25982. isFromClick: true
  25983. });
  25984. }
  25985. });
  25986. };
  25987. clearColorPalette = function (ecModel) {
  25988. ecModel.clearColorPalette();
  25989. ecModel.eachSeries(function (seriesModel) {
  25990. seriesModel.clearColorPalette();
  25991. });
  25992. };
  25993. render = function (ecIns, ecModel, api, payload) {
  25994. renderComponents(ecIns, ecModel, api, payload);
  25995. each$3(ecIns._chartsViews, function (chart) {
  25996. chart.__alive = false;
  25997. });
  25998. renderSeries(ecIns, ecModel, api, payload); // Remove groups of unrendered charts
  25999. each$3(ecIns._chartsViews, function (chart) {
  26000. if (!chart.__alive) {
  26001. chart.remove(ecModel, api);
  26002. }
  26003. });
  26004. };
  26005. renderComponents = function (ecIns, ecModel, api, payload, dirtyList) {
  26006. each$3(dirtyList || ecIns._componentsViews, function (componentView) {
  26007. var componentModel = componentView.__model;
  26008. clearStates(componentModel, componentView);
  26009. componentView.render(componentModel, ecModel, api, payload);
  26010. updateZ(componentModel, componentView);
  26011. updateStates(componentModel, componentView);
  26012. });
  26013. };
  26014. /**
  26015. * Render each chart and component
  26016. */
  26017. renderSeries = function (ecIns, ecModel, api, payload, dirtyMap) {
  26018. // Render all charts
  26019. var scheduler = ecIns._scheduler;
  26020. var labelManager = ecIns._labelManager;
  26021. labelManager.clearLabels();
  26022. var unfinished = false;
  26023. ecModel.eachSeries(function (seriesModel) {
  26024. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26025. chartView.__alive = true;
  26026. var renderTask = chartView.renderTask;
  26027. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  26028. clearStates(seriesModel, chartView);
  26029. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  26030. renderTask.dirty();
  26031. }
  26032. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  26033. unfinished = true;
  26034. }
  26035. seriesModel.__transientTransitionOpt = null;
  26036. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  26037. // increamental render (alway render from the __startIndex each frame)
  26038. // chartView.group.markRedraw();
  26039. updateBlend(seriesModel, chartView);
  26040. updateSeriesElementSelection(seriesModel); // Add labels.
  26041. labelManager.addLabelsOfSeries(chartView);
  26042. });
  26043. scheduler.unfinished = unfinished || scheduler.unfinished;
  26044. labelManager.updateLayoutConfig(api);
  26045. labelManager.layout(api);
  26046. labelManager.processLabelsOverall();
  26047. ecModel.eachSeries(function (seriesModel) {
  26048. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  26049. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  26050. // label should be in normal status when layouting.
  26051. updateStates(seriesModel, chartView);
  26052. }); // If use hover layer
  26053. updateHoverLayerStatus(ecIns, ecModel);
  26054. };
  26055. performPostUpdateFuncs = function (ecModel, api) {
  26056. each$3(postUpdateFuncs, function (func) {
  26057. func(ecModel, api);
  26058. });
  26059. };
  26060. markStatusToUpdate = function (ecIns) {
  26061. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  26062. ecIns.getZr().wakeUp();
  26063. };
  26064. applyChangedStates = function (ecIns) {
  26065. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  26066. return;
  26067. }
  26068. ecIns.getZr().storage.traverse(function (el) {
  26069. // Not applied on removed elements, it may still in fading.
  26070. if (isElementRemoved(el)) {
  26071. return;
  26072. }
  26073. applyElementStates(el);
  26074. });
  26075. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  26076. };
  26077. function applyElementStates(el) {
  26078. var newStates = [];
  26079. var oldStates = el.currentStates; // Keep other states.
  26080. for (var i = 0; i < oldStates.length; i++) {
  26081. var stateName = oldStates[i];
  26082. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  26083. newStates.push(stateName);
  26084. }
  26085. } // Only use states when it's exists.
  26086. if (el.selected && el.states.select) {
  26087. newStates.push('select');
  26088. }
  26089. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  26090. newStates.push('emphasis');
  26091. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  26092. newStates.push('blur');
  26093. }
  26094. el.useStates(newStates);
  26095. }
  26096. function updateHoverLayerStatus(ecIns, ecModel) {
  26097. var zr = ecIns._zr;
  26098. var storage = zr.storage;
  26099. var elCount = 0;
  26100. storage.traverse(function (el) {
  26101. if (!el.isGroup) {
  26102. elCount++;
  26103. }
  26104. });
  26105. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  26106. ecModel.eachSeries(function (seriesModel) {
  26107. if (seriesModel.preventUsingHoverLayer) {
  26108. return;
  26109. }
  26110. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26111. if (chartView.__alive) {
  26112. chartView.group.traverse(function (el) {
  26113. if (el.states.emphasis) {
  26114. el.states.emphasis.hoverLayer = true;
  26115. }
  26116. });
  26117. }
  26118. });
  26119. }
  26120. }
  26121. /**
  26122. * Update chart and blend.
  26123. */
  26124. function updateBlend(seriesModel, chartView) {
  26125. var blendMode = seriesModel.get('blendMode') || null;
  26126. if ("development" !== 'production') {
  26127. if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
  26128. console.warn('Only canvas support blendMode');
  26129. }
  26130. }
  26131. chartView.group.traverse(function (el) {
  26132. // FIXME marker and other components
  26133. if (!el.isGroup) {
  26134. // DONT mark the element dirty. In case element is incremental and don't wan't to rerender.
  26135. el.style.blend = blendMode;
  26136. }
  26137. if (el.eachPendingDisplayable) {
  26138. el.eachPendingDisplayable(function (displayable) {
  26139. displayable.style.blend = blendMode;
  26140. });
  26141. }
  26142. });
  26143. }
  26144. function updateZ(model, view) {
  26145. if (model.preventAutoZ) {
  26146. return;
  26147. }
  26148. var z = model.get('z');
  26149. var zlevel = model.get('zlevel'); // Set z and zlevel
  26150. view.group.traverse(function (el) {
  26151. if (!el.isGroup) {
  26152. z != null && (el.z = z);
  26153. zlevel != null && (el.zlevel = zlevel); // TODO if textContent is on group.
  26154. var label = el.getTextContent();
  26155. var labelLine = el.getTextGuideLine();
  26156. if (label) {
  26157. label.z = el.z;
  26158. label.zlevel = el.zlevel; // lift z2 of text content
  26159. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  26160. label.z2 = el.z2 + 2;
  26161. }
  26162. if (labelLine) {
  26163. var showAbove = el.textGuideLineConfig && el.textGuideLineConfig.showAbove;
  26164. labelLine.z = el.z;
  26165. labelLine.zlevel = el.zlevel;
  26166. labelLine.z2 = el.z2 + (showAbove ? 1 : -1);
  26167. }
  26168. }
  26169. });
  26170. }
  26171. // TODO States on component.
  26172. function clearStates(model, view) {
  26173. view.group.traverse(function (el) {
  26174. // Not applied on removed elements, it may still in fading.
  26175. if (isElementRemoved(el)) {
  26176. return;
  26177. }
  26178. var textContent = el.getTextContent();
  26179. var textGuide = el.getTextGuideLine();
  26180. if (el.stateTransition) {
  26181. el.stateTransition = null;
  26182. }
  26183. if (textContent && textContent.stateTransition) {
  26184. textContent.stateTransition = null;
  26185. }
  26186. if (textGuide && textGuide.stateTransition) {
  26187. textGuide.stateTransition = null;
  26188. } // TODO If el is incremental.
  26189. if (el.hasState()) {
  26190. el.prevStates = el.currentStates;
  26191. el.clearStates();
  26192. } else if (el.prevStates) {
  26193. el.prevStates = null;
  26194. }
  26195. });
  26196. }
  26197. function updateStates(model, view) {
  26198. var stateAnimationModel = model.getModel('stateAnimation');
  26199. var enableAnimation = model.isAnimationEnabled();
  26200. var duration = stateAnimationModel.get('duration');
  26201. var stateTransition = duration > 0 ? {
  26202. duration: duration,
  26203. delay: stateAnimationModel.get('delay'),
  26204. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  26205. } : null;
  26206. view.group.traverse(function (el) {
  26207. if (el.states && el.states.emphasis) {
  26208. // Not applied on removed elements, it may still in fading.
  26209. if (isElementRemoved(el)) {
  26210. return;
  26211. }
  26212. if (el instanceof Path) {
  26213. savePathStates(el);
  26214. } // Only updated on changed element. In case element is incremental and don't wan't to rerender.
  26215. // TODO, a more proper way?
  26216. if (el.__dirty) {
  26217. var prevStates = el.prevStates; // Restore states without animation
  26218. if (prevStates) {
  26219. el.useStates(prevStates);
  26220. }
  26221. } // Update state transition and enable animation again.
  26222. if (enableAnimation) {
  26223. el.stateTransition = stateTransition;
  26224. var textContent = el.getTextContent();
  26225. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  26226. if (textContent) {
  26227. textContent.stateTransition = stateTransition;
  26228. }
  26229. if (textGuide) {
  26230. textGuide.stateTransition = stateTransition;
  26231. }
  26232. } // The use higlighted and selected flag to toggle states.
  26233. if (el.__dirty) {
  26234. applyElementStates(el);
  26235. }
  26236. }
  26237. });
  26238. }
  26239. createExtensionAPI = function (ecIns) {
  26240. return new (
  26241. /** @class */
  26242. function (_super) {
  26243. __extends(class_1, _super);
  26244. function class_1() {
  26245. return _super !== null && _super.apply(this, arguments) || this;
  26246. }
  26247. class_1.prototype.getCoordinateSystems = function () {
  26248. return ecIns._coordSysMgr.getCoordinateSystems();
  26249. };
  26250. class_1.prototype.getComponentByElement = function (el) {
  26251. while (el) {
  26252. var modelInfo = el.__ecComponentInfo;
  26253. if (modelInfo != null) {
  26254. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  26255. }
  26256. el = el.parent;
  26257. }
  26258. };
  26259. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  26260. enterEmphasis(el, highlightDigit);
  26261. markStatusToUpdate(ecIns);
  26262. };
  26263. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  26264. leaveEmphasis(el, highlightDigit);
  26265. markStatusToUpdate(ecIns);
  26266. };
  26267. class_1.prototype.enterBlur = function (el) {
  26268. enterBlur(el);
  26269. markStatusToUpdate(ecIns);
  26270. };
  26271. class_1.prototype.leaveBlur = function (el) {
  26272. leaveBlur(el);
  26273. markStatusToUpdate(ecIns);
  26274. };
  26275. class_1.prototype.enterSelect = function (el) {
  26276. enterSelect(el);
  26277. markStatusToUpdate(ecIns);
  26278. };
  26279. class_1.prototype.leaveSelect = function (el) {
  26280. leaveSelect(el);
  26281. markStatusToUpdate(ecIns);
  26282. };
  26283. class_1.prototype.getModel = function () {
  26284. return ecIns.getModel();
  26285. };
  26286. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  26287. return ecIns.getViewOfComponentModel(componentModel);
  26288. };
  26289. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  26290. return ecIns.getViewOfSeriesModel(seriesModel);
  26291. };
  26292. return class_1;
  26293. }(ExtensionAPI))(ecIns);
  26294. };
  26295. enableConnect = function (chart) {
  26296. function updateConnectedChartsStatus(charts, status) {
  26297. for (var i = 0; i < charts.length; i++) {
  26298. var otherChart = charts[i];
  26299. otherChart[CONNECT_STATUS_KEY] = status;
  26300. }
  26301. }
  26302. each$3(eventActionMap, function (actionType, eventType) {
  26303. chart._messageCenter.on(eventType, function (event) {
  26304. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  26305. if (event && event.escapeConnect) {
  26306. return;
  26307. }
  26308. var action_1 = chart.makeActionFromEvent(event);
  26309. var otherCharts_1 = [];
  26310. each$3(instances$1, function (otherChart) {
  26311. if (otherChart !== chart && otherChart.group === chart.group) {
  26312. otherCharts_1.push(otherChart);
  26313. }
  26314. });
  26315. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  26316. each$3(otherCharts_1, function (otherChart) {
  26317. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  26318. otherChart.dispatchAction(action_1);
  26319. }
  26320. });
  26321. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  26322. }
  26323. });
  26324. });
  26325. };
  26326. setTransitionOpt = function (chart, transitionOpt) {
  26327. var ecModel = chart._model;
  26328. each(normalizeToArray(transitionOpt), function (transOpt) {
  26329. var errMsg;
  26330. var fromOpt = transOpt.from;
  26331. var toOpt = transOpt.to;
  26332. if (toOpt == null) {
  26333. if ("development" !== 'production') {
  26334. errMsg = '`transition.to` must be specified.';
  26335. }
  26336. throwError(errMsg);
  26337. }
  26338. var finderOpt = {
  26339. includeMainTypes: ['series'],
  26340. enableAll: false,
  26341. enableNone: false
  26342. };
  26343. var fromResult = fromOpt ? parseFinder(ecModel, fromOpt, finderOpt) : null;
  26344. var toResult = parseFinder(ecModel, toOpt, finderOpt);
  26345. var toSeries = toResult.seriesModel;
  26346. if (toSeries == null) {
  26347. errMsg = '';
  26348. if ("development" !== 'production') {
  26349. errMsg = '`transition` is only supported on series.';
  26350. }
  26351. }
  26352. if (fromResult && fromResult.seriesModel !== toSeries) {
  26353. errMsg = '';
  26354. if ("development" !== 'production') {
  26355. errMsg = '`transition.from` and `transition.to` must be specified to the same series.';
  26356. }
  26357. }
  26358. if (errMsg != null) {
  26359. throwError(errMsg);
  26360. } // Just a temp solution: mount them on series.
  26361. toSeries.__transientTransitionOpt = {
  26362. from: fromOpt ? fromOpt.dimension : null,
  26363. to: toOpt.dimension,
  26364. dividingMethod: transOpt.dividingMethod
  26365. };
  26366. });
  26367. };
  26368. }();
  26369. return ECharts;
  26370. }(Eventful);
  26371. var echartsProto = ECharts.prototype;
  26372. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  26373. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  26374. /**
  26375. * @deprecated
  26376. */
  26377. // @ts-ignore
  26378. echartsProto.one = function (eventName, cb, ctx) {
  26379. var self = this;
  26380. deprecateLog('ECharts#one is deprecated.');
  26381. function wrapped() {
  26382. var args2 = [];
  26383. for (var _i = 0; _i < arguments.length; _i++) {
  26384. args2[_i] = arguments[_i];
  26385. }
  26386. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  26387. self.off(eventName, wrapped);
  26388. }
  26389. this.on.call(this, eventName, wrapped, ctx);
  26390. }; // /**
  26391. // * Encode visual infomation from data after data processing
  26392. // *
  26393. // * @param {module:echarts/model/Global} ecModel
  26394. // * @param {object} layout
  26395. // * @param {boolean} [layoutFilter] `true`: only layout,
  26396. // * `false`: only not layout,
  26397. // * `null`/`undefined`: all.
  26398. // * @param {string} taskBaseTag
  26399. // * @private
  26400. // */
  26401. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  26402. // each(visualFuncs, function (visual, index) {
  26403. // let isLayout = visual.isLayout;
  26404. // if (layoutFilter == null
  26405. // || (layoutFilter === false && !isLayout)
  26406. // || (layoutFilter === true && isLayout)
  26407. // ) {
  26408. // visual.func(ecModel, api, payload);
  26409. // }
  26410. // });
  26411. // }
  26412. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  26413. function disposedWarning(id) {
  26414. if ("development" !== 'production') {
  26415. console.warn('Instance ' + id + ' has been disposed');
  26416. }
  26417. }
  26418. var actions = {};
  26419. /**
  26420. * Map eventType to actionType
  26421. */
  26422. var eventActionMap = {};
  26423. var dataProcessorFuncs = [];
  26424. var optionPreprocessorFuncs = [];
  26425. var postInitFuncs = [];
  26426. var postUpdateFuncs = [];
  26427. var visualFuncs = [];
  26428. var themeStorage = {};
  26429. var loadingEffects = {};
  26430. var instances$1 = {};
  26431. var connectedGroups = {};
  26432. var idBase = +new Date() - 0;
  26433. var groupIdBase = +new Date() - 0;
  26434. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  26435. /**
  26436. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  26437. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  26438. * @param opts.width Use clientWidth of the input `dom` by default.
  26439. * Can be 'auto' (the same as null/undefined)
  26440. * @param opts.height Use clientHeight of the input `dom` by default.
  26441. * Can be 'auto' (the same as null/undefined)
  26442. */
  26443. function init$1(dom, theme, opts) {
  26444. if ("development" !== 'production') {
  26445. if (!dom) {
  26446. throw new Error('Initialize failed: invalid dom.');
  26447. }
  26448. }
  26449. var existInstance = getInstanceByDom(dom);
  26450. if (existInstance) {
  26451. if ("development" !== 'production') {
  26452. console.warn('There is a chart instance already initialized on the dom.');
  26453. }
  26454. return existInstance;
  26455. }
  26456. if ("development" !== 'production') {
  26457. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  26458. 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.');
  26459. }
  26460. }
  26461. var chart = new ECharts(dom, theme, opts);
  26462. chart.id = 'ec_' + idBase++;
  26463. instances$1[chart.id] = chart;
  26464. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  26465. enableConnect(chart);
  26466. each$3(postInitFuncs, function (postInitFunc) {
  26467. postInitFunc(chart);
  26468. });
  26469. return chart;
  26470. }
  26471. /**
  26472. * @usage
  26473. * (A)
  26474. * ```js
  26475. * let chart1 = echarts.init(dom1);
  26476. * let chart2 = echarts.init(dom2);
  26477. * chart1.group = 'xxx';
  26478. * chart2.group = 'xxx';
  26479. * echarts.connect('xxx');
  26480. * ```
  26481. * (B)
  26482. * ```js
  26483. * let chart1 = echarts.init(dom1);
  26484. * let chart2 = echarts.init(dom2);
  26485. * echarts.connect('xxx', [chart1, chart2]);
  26486. * ```
  26487. */
  26488. function connect(groupId) {
  26489. // Is array of charts
  26490. if (isArray(groupId)) {
  26491. var charts = groupId;
  26492. groupId = null; // If any chart has group
  26493. each$3(charts, function (chart) {
  26494. if (chart.group != null) {
  26495. groupId = chart.group;
  26496. }
  26497. });
  26498. groupId = groupId || 'g_' + groupIdBase++;
  26499. each$3(charts, function (chart) {
  26500. chart.group = groupId;
  26501. });
  26502. }
  26503. connectedGroups[groupId] = true;
  26504. return groupId;
  26505. }
  26506. /**
  26507. * @deprecated
  26508. */
  26509. function disConnect(groupId) {
  26510. connectedGroups[groupId] = false;
  26511. }
  26512. /**
  26513. * Alias and backword compat
  26514. */
  26515. var disconnect = disConnect;
  26516. /**
  26517. * Dispose a chart instance
  26518. */
  26519. function dispose$1(chart) {
  26520. if (typeof chart === 'string') {
  26521. chart = instances$1[chart];
  26522. } else if (!(chart instanceof ECharts)) {
  26523. // Try to treat as dom
  26524. chart = getInstanceByDom(chart);
  26525. }
  26526. if (chart instanceof ECharts && !chart.isDisposed()) {
  26527. chart.dispose();
  26528. }
  26529. }
  26530. function getInstanceByDom(dom) {
  26531. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  26532. }
  26533. function getInstanceById(key) {
  26534. return instances$1[key];
  26535. }
  26536. /**
  26537. * Register theme
  26538. */
  26539. function registerTheme(name, theme) {
  26540. themeStorage[name] = theme;
  26541. }
  26542. /**
  26543. * Register option preprocessor
  26544. */
  26545. function registerPreprocessor(preprocessorFunc) {
  26546. if (indexOf$1(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  26547. optionPreprocessorFuncs.push(preprocessorFunc);
  26548. }
  26549. }
  26550. function registerProcessor(priority, processor) {
  26551. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  26552. }
  26553. /**
  26554. * Register postIniter
  26555. * @param {Function} postInitFunc
  26556. */
  26557. function registerPostInit(postInitFunc) {
  26558. if (indexOf$1(postInitFuncs, postInitFunc) < 0) {
  26559. postInitFunc && postInitFuncs.push(postInitFunc);
  26560. }
  26561. }
  26562. /**
  26563. * Register postUpdater
  26564. * @param {Function} postUpdateFunc
  26565. */
  26566. function registerPostUpdate(postUpdateFunc) {
  26567. if (indexOf$1(postUpdateFuncs, postUpdateFunc) < 0) {
  26568. postUpdateFunc && postUpdateFuncs.push(postUpdateFunc);
  26569. }
  26570. }
  26571. function registerAction(actionInfo, eventName, action) {
  26572. if (typeof eventName === 'function') {
  26573. action = eventName;
  26574. eventName = '';
  26575. }
  26576. var actionType = isObject$2(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  26577. event: eventName
  26578. }][0]; // Event name is all lowercase
  26579. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  26580. eventName = actionInfo.event;
  26581. if (eventActionMap[eventName]) {
  26582. // Already registered.
  26583. return;
  26584. } // Validate action type and event name.
  26585. assert$1(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  26586. if (!actions[actionType]) {
  26587. actions[actionType] = {
  26588. action: action,
  26589. actionInfo: actionInfo
  26590. };
  26591. }
  26592. eventActionMap[eventName] = actionType;
  26593. }
  26594. function registerCoordinateSystem(type, coordSysCreator) {
  26595. CoordinateSystemManager.register(type, coordSysCreator);
  26596. }
  26597. /**
  26598. * Get dimensions of specified coordinate system.
  26599. * @param {string} type
  26600. * @return {Array.<string|Object>}
  26601. */
  26602. function getCoordinateSystemDimensions(type) {
  26603. var coordSysCreator = CoordinateSystemManager.get(type);
  26604. if (coordSysCreator) {
  26605. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  26606. }
  26607. }
  26608. function registerLayout(priority, layoutTask) {
  26609. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26610. }
  26611. function registerVisual(priority, visualTask) {
  26612. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26613. }
  26614. var registeredTasks = [];
  26615. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26616. if (isFunction$1(priority) || isObject$2(priority)) {
  26617. fn = priority;
  26618. priority = defaultPriority;
  26619. }
  26620. if ("development" !== 'production') {
  26621. if (isNaN(priority) || priority == null) {
  26622. throw new Error('Illegal priority');
  26623. } // Check duplicate
  26624. each$3(targetList, function (wrap) {
  26625. assert$1(wrap.__raw !== fn);
  26626. });
  26627. } // Already registered
  26628. if (indexOf$1(registeredTasks, fn) >= 0) {
  26629. return;
  26630. }
  26631. registeredTasks.push(fn);
  26632. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26633. stageHandler.__prio = priority;
  26634. stageHandler.__raw = fn;
  26635. targetList.push(stageHandler);
  26636. }
  26637. function registerLoading(name, loadingFx) {
  26638. loadingEffects[name] = loadingFx;
  26639. }
  26640. /**
  26641. * ZRender need a canvas context to do measureText.
  26642. * But in node environment canvas may be created by node-canvas.
  26643. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26644. *
  26645. * Be careful of using it in the browser.
  26646. *
  26647. * @example
  26648. * let Canvas = require('canvas');
  26649. * let echarts = require('echarts');
  26650. * echarts.setCanvasCreator(function () {
  26651. * // Small size is enough.
  26652. * return new Canvas(32, 32);
  26653. * });
  26654. */
  26655. function setCanvasCreator(creator) {
  26656. $override('createCanvas', creator);
  26657. }
  26658. /**
  26659. * The parameters and usage: see `mapDataStorage.registerMap`.
  26660. * Compatible with previous `echarts.registerMap`.
  26661. */
  26662. function registerMap(mapName, geoJson, specialAreas) {
  26663. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26664. }
  26665. function getMap(mapName) {
  26666. // For backward compatibility, only return the first one.
  26667. var records = mapDataStorage.retrieveMap(mapName); // FIXME support SVG, where return not only records[0].
  26668. return records && records[0] && {
  26669. // @ts-ignore
  26670. geoJson: records[0].geoJSON,
  26671. specialAreas: records[0].specialAreas
  26672. };
  26673. }
  26674. var registerTransform = registerExternalTransform;
  26675. /**
  26676. * Globa dispatchAction to a specified chart instance.
  26677. */
  26678. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  26679. // if (!payload || !payload.chartId) {
  26680. // // Must have chartId to find chart
  26681. // return;
  26682. // }
  26683. // const chart = instances[payload.chartId];
  26684. // if (chart) {
  26685. // chart.dispatchAction(payload, opt);
  26686. // }
  26687. // }
  26688. // Buitlin global visual
  26689. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  26690. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  26691. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  26692. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  26693. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  26694. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  26695. registerPreprocessor(globalBackwardCompat);
  26696. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26697. registerLoading('default', defaultLoading); // Default actions
  26698. registerAction({
  26699. type: HIGHLIGHT_ACTION_TYPE,
  26700. event: HIGHLIGHT_ACTION_TYPE,
  26701. update: HIGHLIGHT_ACTION_TYPE
  26702. }, noop);
  26703. registerAction({
  26704. type: DOWNPLAY_ACTION_TYPE,
  26705. event: DOWNPLAY_ACTION_TYPE,
  26706. update: DOWNPLAY_ACTION_TYPE
  26707. }, noop);
  26708. registerAction({
  26709. type: SELECT_ACTION_TYPE,
  26710. event: SELECT_ACTION_TYPE,
  26711. update: SELECT_ACTION_TYPE
  26712. }, noop);
  26713. registerAction({
  26714. type: UNSELECT_ACTION_TYPE,
  26715. event: UNSELECT_ACTION_TYPE,
  26716. update: UNSELECT_ACTION_TYPE
  26717. }, noop);
  26718. registerAction({
  26719. type: TOGGLE_SELECT_ACTION_TYPE,
  26720. event: TOGGLE_SELECT_ACTION_TYPE,
  26721. update: TOGGLE_SELECT_ACTION_TYPE
  26722. }, noop); // Default theme
  26723. registerTheme('light', lightTheme);
  26724. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  26725. // be mounted on `echarts` is the extension `dataTool` is imported.
  26726. var dataTool = {};
  26727. var extensions = [];
  26728. var extensionRegisters = {
  26729. registerPreprocessor: registerPreprocessor,
  26730. registerProcessor: registerProcessor,
  26731. registerPostInit: registerPostInit,
  26732. registerPostUpdate: registerPostUpdate,
  26733. registerAction: registerAction,
  26734. registerCoordinateSystem: registerCoordinateSystem,
  26735. registerLayout: registerLayout,
  26736. registerVisual: registerVisual,
  26737. registerTransform: registerTransform,
  26738. registerLoading: registerLoading,
  26739. registerMap: registerMap,
  26740. PRIORITY: PRIORITY,
  26741. ComponentModel: ComponentModel,
  26742. ComponentView: ComponentView,
  26743. SeriesModel: SeriesModel,
  26744. ChartView: ChartView,
  26745. // TODO Use ComponentModel and SeriesModel instead of Constructor
  26746. registerComponentModel: function (ComponentModelClass) {
  26747. ComponentModel.registerClass(ComponentModelClass);
  26748. },
  26749. registerComponentView: function (ComponentViewClass) {
  26750. ComponentView.registerClass(ComponentViewClass);
  26751. },
  26752. registerSeriesModel: function (SeriesModelClass) {
  26753. SeriesModel.registerClass(SeriesModelClass);
  26754. },
  26755. registerChartView: function (ChartViewClass) {
  26756. ChartView.registerClass(ChartViewClass);
  26757. },
  26758. registerSubTypeDefaulter: function (componentType, defaulter) {
  26759. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  26760. },
  26761. registerPainter: function (painterType, PainterCtor) {
  26762. registerPainter(painterType, PainterCtor);
  26763. }
  26764. };
  26765. function use(ext) {
  26766. if (isArray(ext)) {
  26767. // use([ChartLine, ChartBar]);
  26768. each(ext, function (singleExt) {
  26769. use(singleExt);
  26770. });
  26771. return;
  26772. }
  26773. if (indexOf(extensions, ext) >= 0) {
  26774. return;
  26775. }
  26776. extensions.push(ext);
  26777. if (isFunction(ext)) {
  26778. ext = {
  26779. install: ext
  26780. };
  26781. }
  26782. ext.install(extensionRegisters);
  26783. }
  26784. /*
  26785. * Licensed to the Apache Software Foundation (ASF) under one
  26786. * or more contributor license agreements. See the NOTICE file
  26787. * distributed with this work for additional information
  26788. * regarding copyright ownership. The ASF licenses this file
  26789. * to you under the Apache License, Version 2.0 (the
  26790. * "License"); you may not use this file except in compliance
  26791. * with the License. You may obtain a copy of the License at
  26792. *
  26793. * http://www.apache.org/licenses/LICENSE-2.0
  26794. *
  26795. * Unless required by applicable law or agreed to in writing,
  26796. * software distributed under the License is distributed on an
  26797. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26798. * KIND, either express or implied. See the License for the
  26799. * specific language governing permissions and limitations
  26800. * under the License.
  26801. */
  26802. /**
  26803. * AUTO-GENERATED FILE. DO NOT MODIFY.
  26804. */
  26805. /*
  26806. * Licensed to the Apache Software Foundation (ASF) under one
  26807. * or more contributor license agreements. See the NOTICE file
  26808. * distributed with this work for additional information
  26809. * regarding copyright ownership. The ASF licenses this file
  26810. * to you under the Apache License, Version 2.0 (the
  26811. * "License"); you may not use this file except in compliance
  26812. * with the License. You may obtain a copy of the License at
  26813. *
  26814. * http://www.apache.org/licenses/LICENSE-2.0
  26815. *
  26816. * Unless required by applicable law or agreed to in writing,
  26817. * software distributed under the License is distributed on an
  26818. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26819. * KIND, either express or implied. See the License for the
  26820. * specific language governing permissions and limitations
  26821. * under the License.
  26822. */
  26823. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  26824. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  26825. }
  26826. function defaultKeyGetter(item) {
  26827. return item;
  26828. }
  26829. var DataDiffer =
  26830. /** @class */
  26831. function () {
  26832. /**
  26833. * @param context Can be visited by this.context in callback.
  26834. */
  26835. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  26836. diffMode) {
  26837. this._old = oldArr;
  26838. this._new = newArr;
  26839. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26840. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  26841. this.context = context;
  26842. this._diffModeMultiple = diffMode === 'multiple';
  26843. }
  26844. /**
  26845. * Callback function when add a data
  26846. */
  26847. DataDiffer.prototype.add = function (func) {
  26848. this._add = func;
  26849. return this;
  26850. };
  26851. /**
  26852. * Callback function when update a data
  26853. */
  26854. DataDiffer.prototype.update = function (func) {
  26855. this._update = func;
  26856. return this;
  26857. };
  26858. /**
  26859. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  26860. */
  26861. DataDiffer.prototype.updateManyToOne = function (func) {
  26862. this._updateManyToOne = func;
  26863. return this;
  26864. };
  26865. /**
  26866. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  26867. */
  26868. DataDiffer.prototype.updateOneToMany = function (func) {
  26869. this._updateOneToMany = func;
  26870. return this;
  26871. };
  26872. /**
  26873. * Callback function when remove a data
  26874. */
  26875. DataDiffer.prototype.remove = function (func) {
  26876. this._remove = func;
  26877. return this;
  26878. };
  26879. DataDiffer.prototype.execute = function () {
  26880. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  26881. };
  26882. DataDiffer.prototype._executeOneToOne = function () {
  26883. var oldArr = this._old;
  26884. var newArr = this._new;
  26885. var newDataIndexMap = {};
  26886. var oldDataKeyArr = new Array(oldArr.length);
  26887. var newDataKeyArr = new Array(newArr.length);
  26888. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  26889. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  26890. for (var i = 0; i < oldArr.length; i++) {
  26891. var oldKey = oldDataKeyArr[i];
  26892. var newIdxMapVal = newDataIndexMap[oldKey];
  26893. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  26894. if (newIdxMapValLen > 1) {
  26895. // Consider there is duplicate key (for example, use dataItem.name as key).
  26896. // We should make sure every item in newArr and oldArr can be visited.
  26897. var newIdx = newIdxMapVal.shift();
  26898. if (newIdxMapVal.length === 1) {
  26899. newDataIndexMap[oldKey] = newIdxMapVal[0];
  26900. }
  26901. this._update && this._update(newIdx, i);
  26902. } else if (newIdxMapValLen === 1) {
  26903. newDataIndexMap[oldKey] = null;
  26904. this._update && this._update(newIdxMapVal, i);
  26905. } else {
  26906. this._remove && this._remove(i);
  26907. }
  26908. }
  26909. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  26910. };
  26911. /**
  26912. * For example, consider the case:
  26913. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  26914. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  26915. * Where:
  26916. * o0, o1, n0 has key 'a' (many to one)
  26917. * o5, n4, n5, n6 has key 'b' (one to many)
  26918. * o2, n1 has key 'c' (one to one)
  26919. * n2, n3 has key 'd' (add)
  26920. * o3, o4 has key 'e' (remove)
  26921. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  26922. * Then:
  26923. * (The order of the following directives are not ensured.)
  26924. * this._updateManyToOne(n0, [o0, o1]);
  26925. * this._updateOneToMany([n4, n5, n6], o5);
  26926. * this._update(n1, o2);
  26927. * this._remove(o3);
  26928. * this._remove(o4);
  26929. * this._remove(o6);
  26930. * this._remove(o7);
  26931. * this._add(n2);
  26932. * this._add(n3);
  26933. * this._add(n7);
  26934. * this._add(n8);
  26935. */
  26936. DataDiffer.prototype._executeMultiple = function () {
  26937. var oldArr = this._old;
  26938. var newArr = this._new;
  26939. var oldDataIndexMap = {};
  26940. var newDataIndexMap = {};
  26941. var oldDataKeyArr = [];
  26942. var newDataKeyArr = [];
  26943. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  26944. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  26945. for (var i = 0; i < oldDataKeyArr.length; i++) {
  26946. var oldKey = oldDataKeyArr[i];
  26947. var oldIdxMapVal = oldDataIndexMap[oldKey];
  26948. var newIdxMapVal = newDataIndexMap[oldKey];
  26949. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  26950. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  26951. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  26952. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  26953. newDataIndexMap[oldKey] = null;
  26954. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  26955. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  26956. newDataIndexMap[oldKey] = null;
  26957. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  26958. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  26959. newDataIndexMap[oldKey] = null;
  26960. } else if (oldIdxMapValLen > 1) {
  26961. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  26962. this._remove && this._remove(oldIdxMapVal[i_1]);
  26963. }
  26964. } else {
  26965. this._remove && this._remove(oldIdxMapVal);
  26966. }
  26967. }
  26968. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  26969. };
  26970. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  26971. for (var i = 0; i < newDataKeyArr.length; i++) {
  26972. var newKey = newDataKeyArr[i];
  26973. var newIdxMapVal = newDataIndexMap[newKey];
  26974. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  26975. if (idxMapValLen > 1) {
  26976. for (var j = 0; j < idxMapValLen; j++) {
  26977. this._add && this._add(newIdxMapVal[j]);
  26978. }
  26979. } else if (idxMapValLen === 1) {
  26980. this._add && this._add(newIdxMapVal);
  26981. } // Support both `newDataKeyArr` are duplication removed or not removed.
  26982. newDataIndexMap[newKey] = null;
  26983. }
  26984. };
  26985. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  26986. map, // In 'byKey', the output `keyArr` is duplication removed.
  26987. // In 'byIndex', the output `keyArr` is not duplication removed and
  26988. // its indices are accurately corresponding to `arr`.
  26989. keyArr, keyGetterName) {
  26990. var cbModeMultiple = this._diffModeMultiple;
  26991. for (var i = 0; i < arr.length; i++) {
  26992. // Add prefix to avoid conflict with Object.prototype.
  26993. var key = '_ec_' + this[keyGetterName](arr[i], i);
  26994. if (!cbModeMultiple) {
  26995. keyArr[i] = key;
  26996. }
  26997. if (!map) {
  26998. continue;
  26999. }
  27000. var idxMapVal = map[key];
  27001. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27002. if (idxMapValLen === 0) {
  27003. // Simple optimize: in most cases, one index has one key,
  27004. // do not need array.
  27005. map[key] = i;
  27006. if (cbModeMultiple) {
  27007. keyArr.push(key);
  27008. }
  27009. } else if (idxMapValLen === 1) {
  27010. map[key] = [idxMapVal, i];
  27011. } else {
  27012. idxMapVal.push(i);
  27013. }
  27014. }
  27015. };
  27016. return DataDiffer;
  27017. }();
  27018. function summarizeDimensions(data) {
  27019. var summary = {};
  27020. var encode = summary.encode = {};
  27021. var notExtraCoordDimMap = createHashMap();
  27022. var defaultedLabel = [];
  27023. var defaultedTooltip = []; // See the comment of `List.js#userOutput`.
  27024. var userOutput = summary.userOutput = {
  27025. dimensionNames: data.dimensions.slice(),
  27026. encode: {}
  27027. };
  27028. each(data.dimensions, function (dimName) {
  27029. var dimItem = data.getDimensionInfo(dimName);
  27030. var coordDim = dimItem.coordDim;
  27031. if (coordDim) {
  27032. if ("development" !== 'production') {
  27033. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  27034. }
  27035. var coordDimIndex = dimItem.coordDimIndex;
  27036. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  27037. if (!dimItem.isExtraCoord) {
  27038. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  27039. // because when dataset is used, it is hard to guess which dimension
  27040. // can be value dimension. If both show x, y on label is not look good,
  27041. // and conventionally y axis is focused more.
  27042. if (mayLabelDimType(dimItem.type)) {
  27043. defaultedLabel[0] = dimName;
  27044. } // User output encode do not contain generated coords.
  27045. // And it only has index. User can use index to retrieve value from the raw item array.
  27046. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  27047. }
  27048. if (dimItem.defaultTooltip) {
  27049. defaultedTooltip.push(dimName);
  27050. }
  27051. }
  27052. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  27053. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  27054. var dimIndex = dimItem.otherDims[otherDim];
  27055. if (dimIndex != null && dimIndex !== false) {
  27056. encodeArr[dimIndex] = dimItem.name;
  27057. }
  27058. });
  27059. });
  27060. var dataDimsOnCoord = [];
  27061. var encodeFirstDimNotExtra = {};
  27062. notExtraCoordDimMap.each(function (v, coordDim) {
  27063. var dimArr = encode[coordDim];
  27064. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  27065. // dim canot on more than one coordDim.
  27066. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  27067. });
  27068. summary.dataDimsOnCoord = dataDimsOnCoord;
  27069. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  27070. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  27071. // in this way. Use label.formatter instead. May be remove this approach someday.
  27072. if (encodeLabel && encodeLabel.length) {
  27073. defaultedLabel = encodeLabel.slice();
  27074. }
  27075. var encodeTooltip = encode.tooltip;
  27076. if (encodeTooltip && encodeTooltip.length) {
  27077. defaultedTooltip = encodeTooltip.slice();
  27078. } else if (!defaultedTooltip.length) {
  27079. defaultedTooltip = defaultedLabel.slice();
  27080. }
  27081. encode.defaultedLabel = defaultedLabel;
  27082. encode.defaultedTooltip = defaultedTooltip;
  27083. return summary;
  27084. }
  27085. function getOrCreateEncodeArr(encode, dim) {
  27086. if (!encode.hasOwnProperty(dim)) {
  27087. encode[dim] = [];
  27088. }
  27089. return encode[dim];
  27090. } // FIXME:TS should be type `AxisType`
  27091. function getDimensionTypeByAxis(axisType) {
  27092. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  27093. }
  27094. function mayLabelDimType(dimType) {
  27095. // In most cases, ordinal and time do not suitable for label.
  27096. // Ordinal info can be displayed on axis. Time is too long.
  27097. return !(dimType === 'ordinal' || dimType === 'time');
  27098. } // function findTheLastDimMayLabel(data) {
  27099. // // Get last value dim
  27100. // let dimensions = data.dimensions.slice();
  27101. // let valueType;
  27102. // let valueDim;
  27103. // while (dimensions.length && (
  27104. // valueDim = dimensions.pop(),
  27105. // valueType = data.getDimensionInfo(valueDim).type,
  27106. // valueType === 'ordinal' || valueType === 'time'
  27107. // )) {} // jshint ignore:line
  27108. // return valueDim;
  27109. // }
  27110. var DataDimensionInfo =
  27111. /** @class */
  27112. function () {
  27113. /**
  27114. * @param opt All of the fields will be shallow copied.
  27115. */
  27116. function DataDimensionInfo(opt) {
  27117. /**
  27118. * The format of `otherDims` is:
  27119. * ```js
  27120. * {
  27121. * tooltip: number optional,
  27122. * label: number optional,
  27123. * itemName: number optional,
  27124. * seriesName: number optional,
  27125. * }
  27126. * ```
  27127. *
  27128. * A `series.encode` can specified these fields:
  27129. * ```js
  27130. * encode: {
  27131. * // "3, 1, 5" is the index of data dimension.
  27132. * tooltip: [3, 1, 5],
  27133. * label: [0, 3],
  27134. * ...
  27135. * }
  27136. * ```
  27137. * `otherDims` is the parse result of the `series.encode` above, like:
  27138. * ```js
  27139. * // Suppose the index of this data dimension is `3`.
  27140. * this.otherDims = {
  27141. * // `3` is at the index `0` of the `encode.tooltip`
  27142. * tooltip: 0,
  27143. * // `3` is at the index `1` of the `encode.tooltip`
  27144. * label: 1
  27145. * };
  27146. * ```
  27147. *
  27148. * This prop should never be `null`/`undefined` after initialized.
  27149. */
  27150. this.otherDims = {};
  27151. if (opt != null) {
  27152. extend(this, opt);
  27153. }
  27154. }
  27155. return DataDimensionInfo;
  27156. }();
  27157. var mathFloor = Math.floor;
  27158. var isObject$3 = isObject;
  27159. var map$1 = map;
  27160. var UNDEFINED = 'undefined';
  27161. var INDEX_NOT_FOUND = -1; // Use prefix to avoid index to be the same as otherIdList[idx],
  27162. // which will cause weird udpate animation.
  27163. var ID_PREFIX = 'e\0\0';
  27164. var dataCtors = {
  27165. 'float': typeof Float64Array === UNDEFINED ? Array : Float64Array,
  27166. 'int': typeof Int32Array === UNDEFINED ? Array : Int32Array,
  27167. // Ordinal data type can be string or int
  27168. 'ordinal': Array,
  27169. 'number': Array,
  27170. 'time': Array
  27171. }; // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  27172. // different from the Ctor of typed array.
  27173. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  27174. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  27175. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  27176. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_rawData', '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  27177. var CLONE_PROPERTIES = ['_extent', '_approximateExtent', '_rawExtent']; // -----------------------------
  27178. // Internal method declarations:
  27179. // -----------------------------
  27180. var defaultDimValueGetters;
  27181. var prepareInvertedIndex;
  27182. var getIndicesCtor;
  27183. var prepareStorage;
  27184. var getRawIndexWithoutIndices;
  27185. var getRawIndexWithIndices;
  27186. var getId;
  27187. var getIdNameFromStore;
  27188. var makeIdFromName;
  27189. var normalizeDimensions;
  27190. var validateDimensions;
  27191. var cloneListForMapAndSample;
  27192. var getInitialExtent;
  27193. var setItemDataAndSeriesIndex;
  27194. var transferProperties;
  27195. var List =
  27196. /** @class */
  27197. function () {
  27198. /**
  27199. * @param dimensions
  27200. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  27201. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  27202. */
  27203. function List(dimensions, hostModel) {
  27204. this.type = 'list';
  27205. this._count = 0;
  27206. this._rawCount = 0;
  27207. this._storage = {}; // We have an extra array store here. It's faster to be acessed than KV structured `_storage`.
  27208. // We profile the code `storage[dim]` and it seems to be KeyedLoadIC_Megamorphic instead of fast property access.
  27209. // Not sure why this happens. But using an extra array seems leads to faster `initData`
  27210. // See https://github.com/apache/incubator-echarts/pull/13314 for more explanation.
  27211. this._storageArr = [];
  27212. this._nameList = [];
  27213. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  27214. // Never used yet (not used yet).
  27215. // private _optionModels: Model[] = [];
  27216. // Global visual properties after visual coding
  27217. this._visual = {}; // Globel layout properties.
  27218. this._layout = {}; // Item visual properties after visual coding
  27219. this._itemVisuals = []; // Item layout properties after layout
  27220. this._itemLayouts = []; // Graphic elemnents
  27221. this._graphicEls = []; // Raw extent will not be cloned, but only transfered.
  27222. // It will not be calculated util needed.
  27223. this._rawExtent = {};
  27224. this._extent = {}; // key: dim, value: extent
  27225. this._approximateExtent = {};
  27226. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  27227. // (in type `OptionDataItemObject`).
  27228. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  27229. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  27230. this.hasItemOption = true; // Methods that create a new list based on this list should be listed here.
  27231. // Notice that those method should `RETURN` the new list.
  27232. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  27233. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27234. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  27235. /**
  27236. * Get raw data index.
  27237. * Do not initialize.
  27238. * Default `getRawIndex`. And it can be changed.
  27239. */
  27240. this.getRawIndex = getRawIndexWithoutIndices;
  27241. dimensions = dimensions || ['x', 'y'];
  27242. var dimensionInfos = {};
  27243. var dimensionNames = [];
  27244. var invertedIndicesMap = {};
  27245. for (var i = 0; i < dimensions.length; i++) {
  27246. // Use the original dimensions[i], where other flag props may exists.
  27247. var dimInfoInput = dimensions[i];
  27248. var dimensionInfo = isString(dimInfoInput) ? new DataDimensionInfo({
  27249. name: dimInfoInput
  27250. }) : !(dimInfoInput instanceof DataDimensionInfo) ? new DataDimensionInfo(dimInfoInput) : dimInfoInput;
  27251. var dimensionName = dimensionInfo.name;
  27252. dimensionInfo.type = dimensionInfo.type || 'float';
  27253. if (!dimensionInfo.coordDim) {
  27254. dimensionInfo.coordDim = dimensionName;
  27255. dimensionInfo.coordDimIndex = 0;
  27256. }
  27257. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  27258. dimensionNames.push(dimensionName);
  27259. dimensionInfos[dimensionName] = dimensionInfo;
  27260. dimensionInfo.index = i;
  27261. if (dimensionInfo.createInvertedIndices) {
  27262. invertedIndicesMap[dimensionName] = [];
  27263. }
  27264. if (otherDims.itemName === 0) {
  27265. this._nameDimIdx = i;
  27266. this._nameOrdinalMeta = dimensionInfo.ordinalMeta;
  27267. }
  27268. if (otherDims.itemId === 0) {
  27269. this._idDimIdx = i;
  27270. this._idOrdinalMeta = dimensionInfo.ordinalMeta;
  27271. }
  27272. }
  27273. this.dimensions = dimensionNames;
  27274. this._dimensionInfos = dimensionInfos;
  27275. this.hostModel = hostModel; // Cache summary info for fast visit. See "dimensionHelper".
  27276. this._dimensionsSummary = summarizeDimensions(this);
  27277. this._invertedIndicesMap = invertedIndicesMap;
  27278. this.userOutput = this._dimensionsSummary.userOutput;
  27279. }
  27280. /**
  27281. * The meanings of the input parameter `dim`:
  27282. *
  27283. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  27284. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  27285. * + If dim is a number-like string (e.g., `"1"`):
  27286. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  27287. * + If not, it will be converted to a number, which means the index of the dimension.
  27288. * (why? because of the backward compatbility. We have been tolerating number-like string in
  27289. * dimension setting, although now it seems that it is not a good idea.)
  27290. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  27291. * if no dimension name is defined as `"1"`.
  27292. * + If dim is a not-number-like string, it means the concrete dim name.
  27293. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  27294. * or customized in `dimensions` property of option like `"age"`.
  27295. *
  27296. * Get dimension name
  27297. * @param dim See above.
  27298. * @return Concrete dim name.
  27299. */
  27300. List.prototype.getDimension = function (dim) {
  27301. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  27302. || !isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim)) {
  27303. dim = this.dimensions[dim];
  27304. }
  27305. return dim;
  27306. };
  27307. /**
  27308. * Get type and calculation info of particular dimension
  27309. * @param dim
  27310. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  27311. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  27312. */
  27313. List.prototype.getDimensionInfo = function (dim) {
  27314. // Do not clone, because there may be categories in dimInfo.
  27315. return this._dimensionInfos[this.getDimension(dim)];
  27316. };
  27317. /**
  27318. * concrete dimension name list on coord.
  27319. */
  27320. List.prototype.getDimensionsOnCoord = function () {
  27321. return this._dimensionsSummary.dataDimsOnCoord.slice();
  27322. };
  27323. List.prototype.mapDimension = function (coordDim, idx) {
  27324. var dimensionsSummary = this._dimensionsSummary;
  27325. if (idx == null) {
  27326. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  27327. }
  27328. var dims = dimensionsSummary.encode[coordDim];
  27329. return dims ? dims[idx] : null;
  27330. };
  27331. List.prototype.mapDimensionsAll = function (coordDim) {
  27332. var dimensionsSummary = this._dimensionsSummary;
  27333. var dims = dimensionsSummary.encode[coordDim];
  27334. return (dims || []).slice();
  27335. };
  27336. /**
  27337. * Initialize from data
  27338. * @param data source or data or data provider.
  27339. * @param nameList The name of a datum is used on data diff and
  27340. * default label/tooltip.
  27341. * A name can be specified in encode.itemName,
  27342. * or dataItem.name (only for series option data),
  27343. * or provided in nameList from outside.
  27344. */
  27345. List.prototype.initData = function (data, nameList, dimValueGetter) {
  27346. var notProvider = isSourceInstance(data) || isArrayLike(data);
  27347. var provider = notProvider ? new DefaultDataProvider(data, this.dimensions.length) : data;
  27348. if ("development" !== 'production') {
  27349. assert(notProvider || isFunction(provider.getItem) && isFunction(provider.count), 'Inavlid data provider.');
  27350. }
  27351. this._rawData = provider;
  27352. var sourceFormat = provider.getSource().sourceFormat; // Clear
  27353. this._storage = {};
  27354. this._indices = null;
  27355. this._dontMakeIdFromName = this._idDimIdx != null || sourceFormat === SOURCE_FORMAT_TYPED_ARRAY // Cosndier performance.
  27356. || !!provider.fillStorage;
  27357. this._nameList = (nameList || []).slice();
  27358. this._idList = [];
  27359. this._nameRepeatCount = {};
  27360. if (!dimValueGetter) {
  27361. this.hasItemOption = false;
  27362. }
  27363. this.defaultDimValueGetter = defaultDimValueGetters[sourceFormat]; // Default dim value getter
  27364. this._dimValueGetter = dimValueGetter = dimValueGetter || this.defaultDimValueGetter;
  27365. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows; // Reset raw extent.
  27366. this._rawExtent = {};
  27367. this._initDataFromProvider(0, provider.count()); // If data has no item option.
  27368. if (provider.pure) {
  27369. this.hasItemOption = false;
  27370. }
  27371. };
  27372. List.prototype.getProvider = function () {
  27373. return this._rawData;
  27374. };
  27375. /**
  27376. * Caution: Can be only called on raw data (before `this._indices` created).
  27377. */
  27378. List.prototype.appendData = function (data) {
  27379. if ("development" !== 'production') {
  27380. assert(!this._indices, 'appendData can only be called on raw data.');
  27381. }
  27382. var rawData = this._rawData;
  27383. var start = this.count();
  27384. rawData.appendData(data);
  27385. var end = rawData.count();
  27386. if (!rawData.persistent) {
  27387. end += start;
  27388. }
  27389. this._initDataFromProvider(start, end, true);
  27390. };
  27391. /**
  27392. * Caution: Can be only called on raw data (before `this._indices` created).
  27393. * This method does not modify `rawData` (`dataProvider`), but only
  27394. * add values to storage.
  27395. *
  27396. * The final count will be increased by `Math.max(values.length, names.length)`.
  27397. *
  27398. * @param values That is the SourceType: 'arrayRows', like
  27399. * [
  27400. * [12, 33, 44],
  27401. * [NaN, 43, 1],
  27402. * ['-', 'asdf', 0]
  27403. * ]
  27404. * Each item is exaclty cooresponding to a dimension.
  27405. */
  27406. List.prototype.appendValues = function (values, names) {
  27407. var storage = this._storage;
  27408. var dimensions = this.dimensions;
  27409. var dimLen = dimensions.length;
  27410. var rawExtent = this._rawExtent;
  27411. var start = this.count();
  27412. var end = start + Math.max(values.length, names ? names.length : 0);
  27413. for (var i = 0; i < dimLen; i++) {
  27414. var dim = dimensions[i];
  27415. if (!rawExtent[dim]) {
  27416. rawExtent[dim] = getInitialExtent();
  27417. }
  27418. prepareStorage(storage, this._dimensionInfos[dim], end, true);
  27419. }
  27420. var rawExtentArr = map$1(dimensions, function (dim) {
  27421. return rawExtent[dim];
  27422. });
  27423. var storageArr = this._storageArr = map$1(dimensions, function (dim) {
  27424. return storage[dim];
  27425. });
  27426. var emptyDataItem = [];
  27427. for (var idx = start; idx < end; idx++) {
  27428. var sourceIdx = idx - start; // Store the data by dimensions
  27429. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  27430. var dim = dimensions[dimIdx];
  27431. var val = this._dimValueGetterArrayRows(values[sourceIdx] || emptyDataItem, dim, sourceIdx, dimIdx);
  27432. storageArr[dimIdx][idx] = val;
  27433. var dimRawExtent = rawExtentArr[dimIdx];
  27434. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27435. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27436. }
  27437. if (names) {
  27438. this._nameList[idx] = names[sourceIdx];
  27439. if (!this._dontMakeIdFromName) {
  27440. makeIdFromName(this, idx);
  27441. }
  27442. }
  27443. }
  27444. this._rawCount = this._count = end; // Reset data extent
  27445. this._extent = {};
  27446. prepareInvertedIndex(this);
  27447. };
  27448. List.prototype._initDataFromProvider = function (start, end, append) {
  27449. if (start >= end) {
  27450. return;
  27451. }
  27452. var rawData = this._rawData;
  27453. var storage = this._storage;
  27454. var dimensions = this.dimensions;
  27455. var dimLen = dimensions.length;
  27456. var dimensionInfoMap = this._dimensionInfos;
  27457. var nameList = this._nameList;
  27458. var idList = this._idList;
  27459. var rawExtent = this._rawExtent;
  27460. var sourceFormat = rawData.getSource().sourceFormat;
  27461. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL;
  27462. for (var i = 0; i < dimLen; i++) {
  27463. var dim = dimensions[i];
  27464. if (!rawExtent[dim]) {
  27465. rawExtent[dim] = getInitialExtent();
  27466. }
  27467. prepareStorage(storage, dimensionInfoMap[dim], end, append);
  27468. }
  27469. var storageArr = this._storageArr = map$1(dimensions, function (dim) {
  27470. return storage[dim];
  27471. });
  27472. var rawExtentArr = map$1(dimensions, function (dim) {
  27473. return rawExtent[dim];
  27474. });
  27475. if (rawData.fillStorage) {
  27476. rawData.fillStorage(start, end, storageArr, rawExtentArr);
  27477. } else {
  27478. var dataItem = [];
  27479. for (var idx = start; idx < end; idx++) {
  27480. // NOTICE: Try not to write things into dataItem
  27481. dataItem = rawData.getItem(idx, dataItem); // Each data item is value
  27482. // [1, 2]
  27483. // 2
  27484. // Bar chart, line chart which uses category axis
  27485. // only gives the 'y' value. 'x' value is the indices of category
  27486. // Use a tempValue to normalize the value to be a (x, y) value
  27487. // Store the data by dimensions
  27488. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  27489. var dim = dimensions[dimIdx];
  27490. var dimStorage = storageArr[dimIdx]; // PENDING NULL is empty or zero
  27491. var val = this._dimValueGetter(dataItem, dim, idx, dimIdx);
  27492. dimStorage[idx] = val;
  27493. var dimRawExtent = rawExtentArr[dimIdx];
  27494. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27495. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27496. } // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  27497. // This kind of ids and names are always stored `_nameList` and `_idList`.
  27498. if (isFormatOriginal && !rawData.pure && dataItem) {
  27499. var itemName = dataItem.name;
  27500. if (nameList[idx] == null && itemName != null) {
  27501. nameList[idx] = convertOptionIdName(itemName, null);
  27502. }
  27503. var itemId = dataItem.id;
  27504. if (idList[idx] == null && itemId != null) {
  27505. idList[idx] = convertOptionIdName(itemId, null);
  27506. }
  27507. }
  27508. if (!this._dontMakeIdFromName) {
  27509. makeIdFromName(this, idx);
  27510. }
  27511. }
  27512. }
  27513. if (!rawData.persistent && rawData.clean) {
  27514. // Clean unused data if data source is typed array.
  27515. rawData.clean();
  27516. }
  27517. this._rawCount = this._count = end; // Reset data extent
  27518. this._extent = {};
  27519. prepareInvertedIndex(this);
  27520. };
  27521. List.prototype.count = function () {
  27522. return this._count;
  27523. };
  27524. List.prototype.getIndices = function () {
  27525. var newIndices;
  27526. var indices = this._indices;
  27527. if (indices) {
  27528. var Ctor = indices.constructor;
  27529. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27530. if (Ctor === Array) {
  27531. newIndices = new Ctor(thisCount);
  27532. for (var i = 0; i < thisCount; i++) {
  27533. newIndices[i] = indices[i];
  27534. }
  27535. } else {
  27536. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27537. }
  27538. } else {
  27539. var Ctor = getIndicesCtor(this);
  27540. newIndices = new Ctor(this.count());
  27541. for (var i = 0; i < newIndices.length; i++) {
  27542. newIndices[i] = i;
  27543. }
  27544. }
  27545. return newIndices;
  27546. }; // Get data by index of dimension.
  27547. // Because in v8 access array by number variable is faster than access object by string variable
  27548. // Not sure why but the optimization just works.
  27549. List.prototype.getByDimIdx = function (dimIdx, idx) {
  27550. if (!(idx >= 0 && idx < this._count)) {
  27551. return NaN;
  27552. }
  27553. var dimStore = this._storageArr[dimIdx];
  27554. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  27555. };
  27556. /**
  27557. * Get value. Return NaN if idx is out of range.
  27558. * @param dim Dim must be concrete name.
  27559. */
  27560. List.prototype.get = function (dim, idx) {
  27561. if (!(idx >= 0 && idx < this._count)) {
  27562. return NaN;
  27563. }
  27564. var dimStore = this._storage[dim];
  27565. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  27566. };
  27567. /**
  27568. * @param dim concrete dim
  27569. */
  27570. List.prototype.getByRawIndex = function (dim, rawIdx) {
  27571. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27572. return NaN;
  27573. }
  27574. var dimStore = this._storage[dim];
  27575. return dimStore ? dimStore[rawIdx] : NaN;
  27576. };
  27577. List.prototype.getValues = function (dimensions, idx) {
  27578. var values = [];
  27579. if (!isArray(dimensions)) {
  27580. // stack = idx;
  27581. idx = dimensions;
  27582. dimensions = this.dimensions;
  27583. }
  27584. for (var i = 0, len = dimensions.length; i < len; i++) {
  27585. values.push(this.get(dimensions[i], idx
  27586. /*, stack */
  27587. ));
  27588. }
  27589. return values;
  27590. };
  27591. /**
  27592. * If value is NaN. Inlcuding '-'
  27593. * Only check the coord dimensions.
  27594. */
  27595. List.prototype.hasValue = function (idx) {
  27596. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27597. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27598. // Ordinal type originally can be string or number.
  27599. // But when an ordinal type is used on coord, it can
  27600. // not be string but only number. So we can also use isNaN.
  27601. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27602. return false;
  27603. }
  27604. }
  27605. return true;
  27606. };
  27607. /**
  27608. * Get extent of data in one dimension
  27609. */
  27610. List.prototype.getDataExtent = function (dim) {
  27611. // Make sure use concrete dim as cache name.
  27612. dim = this.getDimension(dim);
  27613. var dimData = this._storage[dim];
  27614. var initialExtent = getInitialExtent(); // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27615. if (!dimData) {
  27616. return initialExtent;
  27617. } // Make more strict checkings to ensure hitting cache.
  27618. var currEnd = this.count(); // let cacheName = [dim, !!stack].join('_');
  27619. // let cacheName = dim;
  27620. // Consider the most cases when using data zoom, `getDataExtent`
  27621. // happened before filtering. We cache raw extent, which is not
  27622. // necessary to be cleared and recalculated when restore data.
  27623. var useRaw = !this._indices; // && !stack;
  27624. var dimExtent;
  27625. if (useRaw) {
  27626. return this._rawExtent[dim].slice();
  27627. }
  27628. dimExtent = this._extent[dim];
  27629. if (dimExtent) {
  27630. return dimExtent.slice();
  27631. }
  27632. dimExtent = initialExtent;
  27633. var min = dimExtent[0];
  27634. var max = dimExtent[1];
  27635. for (var i = 0; i < currEnd; i++) {
  27636. var rawIdx = this.getRawIndex(i);
  27637. var value = dimData[rawIdx];
  27638. value < min && (min = value);
  27639. value > max && (max = value);
  27640. }
  27641. dimExtent = [min, max];
  27642. this._extent[dim] = dimExtent;
  27643. return dimExtent;
  27644. };
  27645. /**
  27646. * PENDING: In fact currently this function is only used to short-circuit
  27647. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  27648. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  27649. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  27650. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  27651. * But if we add "custom data filter" in future, which is not "axis related", this method may
  27652. * be still needed.
  27653. *
  27654. * Optimize for the scenario that data is filtered by a given extent.
  27655. * Consider that if data amount is more than hundreds of thousand,
  27656. * extent calculation will cost more than 10ms and the cache will
  27657. * be erased because of the filtering.
  27658. */
  27659. List.prototype.getApproximateExtent = function (dim) {
  27660. dim = this.getDimension(dim);
  27661. return this._approximateExtent[dim] || this.getDataExtent(dim);
  27662. };
  27663. /**
  27664. * Calculate extent on a filtered data might be time consuming.
  27665. * Approximate extent is only used for: calculte extent of filtered data outside.
  27666. */
  27667. List.prototype.setApproximateExtent = function (extent, dim) {
  27668. dim = this.getDimension(dim);
  27669. this._approximateExtent[dim] = extent.slice();
  27670. };
  27671. List.prototype.getCalculationInfo = function (key) {
  27672. return this._calculationInfo[key];
  27673. };
  27674. List.prototype.setCalculationInfo = function (key, value) {
  27675. isObject$3(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  27676. };
  27677. /**
  27678. * Get sum of data in one dimension
  27679. */
  27680. List.prototype.getSum = function (dim) {
  27681. var dimData = this._storage[dim];
  27682. var sum = 0;
  27683. if (dimData) {
  27684. for (var i = 0, len = this.count(); i < len; i++) {
  27685. var value = this.get(dim, i);
  27686. if (!isNaN(value)) {
  27687. sum += value;
  27688. }
  27689. }
  27690. }
  27691. return sum;
  27692. };
  27693. /**
  27694. * Get median of data in one dimension
  27695. */
  27696. List.prototype.getMedian = function (dim) {
  27697. var dimDataArray = []; // map all data of one dimension
  27698. this.each(dim, function (val) {
  27699. if (!isNaN(val)) {
  27700. dimDataArray.push(val);
  27701. }
  27702. }); // TODO
  27703. // Use quick select?
  27704. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  27705. return a - b;
  27706. });
  27707. var len = this.count(); // calculate median
  27708. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27709. }; // /**
  27710. // * Retreive the index with given value
  27711. // * @param {string} dim Concrete dimension.
  27712. // * @param {number} value
  27713. // * @return {number}
  27714. // */
  27715. // Currently incorrect: should return dataIndex but not rawIndex.
  27716. // Do not fix it until this method is to be used somewhere.
  27717. // FIXME Precision of float value
  27718. // indexOf(dim, value) {
  27719. // let storage = this._storage;
  27720. // let dimData = storage[dim];
  27721. // let chunkSize = this._chunkSize;
  27722. // if (dimData) {
  27723. // for (let i = 0, len = this.count(); i < len; i++) {
  27724. // let chunkIndex = mathFloor(i / chunkSize);
  27725. // let chunkOffset = i % chunkSize;
  27726. // if (dimData[chunkIndex][chunkOffset] === value) {
  27727. // return i;
  27728. // }
  27729. // }
  27730. // }
  27731. // return -1;
  27732. // }
  27733. /**
  27734. * Only support the dimension which inverted index created.
  27735. * Do not support other cases until required.
  27736. * @param dim concrete dim
  27737. * @param value ordinal index
  27738. * @return rawIndex
  27739. */
  27740. List.prototype.rawIndexOf = function (dim, value) {
  27741. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27742. if ("development" !== 'production') {
  27743. if (!invertedIndices) {
  27744. throw new Error('Do not supported yet');
  27745. }
  27746. }
  27747. var rawIndex = invertedIndices[value];
  27748. if (rawIndex == null || isNaN(rawIndex)) {
  27749. return INDEX_NOT_FOUND;
  27750. }
  27751. return rawIndex;
  27752. };
  27753. /**
  27754. * Retreive the index with given name
  27755. */
  27756. List.prototype.indexOfName = function (name) {
  27757. for (var i = 0, len = this.count(); i < len; i++) {
  27758. if (this.getName(i) === name) {
  27759. return i;
  27760. }
  27761. }
  27762. return -1;
  27763. };
  27764. /**
  27765. * Retreive the index with given raw data index
  27766. */
  27767. List.prototype.indexOfRawIndex = function (rawIndex) {
  27768. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27769. return -1;
  27770. }
  27771. if (!this._indices) {
  27772. return rawIndex;
  27773. } // Indices are ascending
  27774. var indices = this._indices; // If rawIndex === dataIndex
  27775. var rawDataIndex = indices[rawIndex];
  27776. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27777. return rawIndex;
  27778. }
  27779. var left = 0;
  27780. var right = this._count - 1;
  27781. while (left <= right) {
  27782. var mid = (left + right) / 2 | 0;
  27783. if (indices[mid] < rawIndex) {
  27784. left = mid + 1;
  27785. } else if (indices[mid] > rawIndex) {
  27786. right = mid - 1;
  27787. } else {
  27788. return mid;
  27789. }
  27790. }
  27791. return -1;
  27792. };
  27793. /**
  27794. * Retreive the index of nearest value
  27795. * @param dim
  27796. * @param value
  27797. * @param [maxDistance=Infinity]
  27798. * @return If and only if multiple indices has
  27799. * the same value, they are put to the result.
  27800. */
  27801. List.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  27802. var storage = this._storage;
  27803. var dimData = storage[dim];
  27804. var nearestIndices = [];
  27805. if (!dimData) {
  27806. return nearestIndices;
  27807. }
  27808. if (maxDistance == null) {
  27809. maxDistance = Infinity;
  27810. }
  27811. var minDist = Infinity;
  27812. var minDiff = -1;
  27813. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/List.js`.
  27814. for (var i = 0, len = this.count(); i < len; i++) {
  27815. var dataIndex = this.getRawIndex(i);
  27816. var diff = value - dimData[dataIndex];
  27817. var dist = Math.abs(diff);
  27818. if (dist <= maxDistance) {
  27819. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27820. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27821. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27822. // So we chose the one that `diff >= 0` in this csae.
  27823. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27824. // should be push to `nearestIndices`.
  27825. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  27826. minDist = dist;
  27827. minDiff = diff;
  27828. nearestIndicesLen = 0;
  27829. }
  27830. if (diff === minDiff) {
  27831. nearestIndices[nearestIndicesLen++] = i;
  27832. }
  27833. }
  27834. }
  27835. nearestIndices.length = nearestIndicesLen;
  27836. return nearestIndices;
  27837. };
  27838. /**
  27839. * Get raw data item
  27840. */
  27841. List.prototype.getRawDataItem = function (idx) {
  27842. if (!this._rawData.persistent) {
  27843. var val = [];
  27844. for (var i = 0; i < this.dimensions.length; i++) {
  27845. var dim = this.dimensions[i];
  27846. val.push(this.get(dim, idx));
  27847. }
  27848. return val;
  27849. } else {
  27850. return this._rawData.getItem(this.getRawIndex(idx));
  27851. }
  27852. };
  27853. /**
  27854. * @return Never be null/undefined. `number` will be converted to string. Becuase:
  27855. * In most cases, name is used in display, where returning a string is more convenient.
  27856. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  27857. * rule that name `2` equals to name `'2'`.
  27858. */
  27859. List.prototype.getName = function (idx) {
  27860. var rawIndex = this.getRawIndex(idx);
  27861. var name = this._nameList[rawIndex];
  27862. if (name == null && this._nameDimIdx != null) {
  27863. name = getIdNameFromStore(this, this._nameDimIdx, this._nameOrdinalMeta, rawIndex);
  27864. }
  27865. if (name == null) {
  27866. name = '';
  27867. }
  27868. return name;
  27869. };
  27870. /**
  27871. * @return Never null/undefined. `number` will be converted to string. Becuase:
  27872. * In all cases having encountered at present, id is used in making diff comparison, which
  27873. * are usually based on hash map. We can keep the rule that the internal id are always string
  27874. * (treat `2` is the same as `'2'`) to make the related logic simple.
  27875. */
  27876. List.prototype.getId = function (idx) {
  27877. return getId(this, this.getRawIndex(idx));
  27878. };
  27879. List.prototype.each = function (dims, cb, ctx, ctxCompat) {
  27880. var _this = this;
  27881. if (!this._count) {
  27882. return;
  27883. }
  27884. if (typeof dims === 'function') {
  27885. ctxCompat = ctx;
  27886. ctx = cb;
  27887. cb = dims;
  27888. dims = [];
  27889. } // ctxCompat just for compat echarts3
  27890. var fCtx = ctx || ctxCompat || this;
  27891. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  27892. if ("development" !== 'production') {
  27893. validateDimensions(this, dimNames);
  27894. }
  27895. var dimSize = dimNames.length;
  27896. var dimIndices = map$1(dimNames, function (dimName) {
  27897. return _this._dimensionInfos[dimName].index;
  27898. });
  27899. var storageArr = this._storageArr;
  27900. for (var i = 0, len = this.count(); i < len; i++) {
  27901. var rawIdx = this.getRawIndex(i); // Simple optimization
  27902. switch (dimSize) {
  27903. case 0:
  27904. cb.call(fCtx, i);
  27905. break;
  27906. case 1:
  27907. cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], i);
  27908. break;
  27909. case 2:
  27910. cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], storageArr[dimIndices[1]][rawIdx], i);
  27911. break;
  27912. default:
  27913. var k = 0;
  27914. var value = [];
  27915. for (; k < dimSize; k++) {
  27916. value[k] = storageArr[dimIndices[k]][rawIdx];
  27917. } // Index
  27918. value[k] = i;
  27919. cb.apply(fCtx, value);
  27920. }
  27921. }
  27922. };
  27923. List.prototype.filterSelf = function (dims, cb, ctx, ctxCompat) {
  27924. var _this = this;
  27925. if (!this._count) {
  27926. return;
  27927. }
  27928. if (typeof dims === 'function') {
  27929. ctxCompat = ctx;
  27930. ctx = cb;
  27931. cb = dims;
  27932. dims = [];
  27933. } // ctxCompat just for compat echarts3
  27934. var fCtx = ctx || ctxCompat || this;
  27935. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  27936. if ("development" !== 'production') {
  27937. validateDimensions(this, dimNames);
  27938. }
  27939. var count = this.count();
  27940. var Ctor = getIndicesCtor(this);
  27941. var newIndices = new Ctor(count);
  27942. var value = [];
  27943. var dimSize = dimNames.length;
  27944. var offset = 0;
  27945. var dimIndices = map$1(dimNames, function (dimName) {
  27946. return _this._dimensionInfos[dimName].index;
  27947. });
  27948. var dim0 = dimIndices[0];
  27949. var storageArr = this._storageArr;
  27950. for (var i = 0; i < count; i++) {
  27951. var keep = void 0;
  27952. var rawIdx = this.getRawIndex(i); // Simple optimization
  27953. if (dimSize === 0) {
  27954. keep = cb.call(fCtx, i);
  27955. } else if (dimSize === 1) {
  27956. var val = storageArr[dim0][rawIdx];
  27957. keep = cb.call(fCtx, val, i);
  27958. } else {
  27959. var k = 0;
  27960. for (; k < dimSize; k++) {
  27961. value[k] = storageArr[dimIndices[k]][rawIdx];
  27962. }
  27963. value[k] = i;
  27964. keep = cb.apply(fCtx, value);
  27965. }
  27966. if (keep) {
  27967. newIndices[offset++] = rawIdx;
  27968. }
  27969. } // Set indices after filtered.
  27970. if (offset < count) {
  27971. this._indices = newIndices;
  27972. }
  27973. this._count = offset; // Reset data extent
  27974. this._extent = {};
  27975. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27976. return this;
  27977. };
  27978. /**
  27979. * Select data in range. (For optimization of filter)
  27980. * (Manually inline code, support 5 million data filtering in data zoom.)
  27981. */
  27982. List.prototype.selectRange = function (range) {
  27983. var _this = this;
  27984. var len = this._count;
  27985. if (!len) {
  27986. return;
  27987. }
  27988. var dimensions = [];
  27989. for (var dim in range) {
  27990. if (range.hasOwnProperty(dim)) {
  27991. dimensions.push(dim);
  27992. }
  27993. }
  27994. if ("development" !== 'production') {
  27995. validateDimensions(this, dimensions);
  27996. }
  27997. var dimSize = dimensions.length;
  27998. if (!dimSize) {
  27999. return;
  28000. }
  28001. var originalCount = this.count();
  28002. var Ctor = getIndicesCtor(this);
  28003. var newIndices = new Ctor(originalCount);
  28004. var offset = 0;
  28005. var dim0 = dimensions[0];
  28006. var dimIndices = map$1(dimensions, function (dimName) {
  28007. return _this._dimensionInfos[dimName].index;
  28008. });
  28009. var min = range[dim0][0];
  28010. var max = range[dim0][1];
  28011. var storageArr = this._storageArr;
  28012. var quickFinished = false;
  28013. if (!this._indices) {
  28014. // Extreme optimization for common case. About 2x faster in chrome.
  28015. var idx = 0;
  28016. if (dimSize === 1) {
  28017. var dimStorage = storageArr[dimIndices[0]];
  28018. for (var i = 0; i < len; i++) {
  28019. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  28020. // value indicates the line should be broken. But for the case like
  28021. // scatter plot, a data item with empty value will not be rendered,
  28022. // but the axis extent may be effected if some other dim of the data
  28023. // item has value. Fortunately it is not a significant negative effect.
  28024. if (val >= min && val <= max || isNaN(val)) {
  28025. newIndices[offset++] = idx;
  28026. }
  28027. idx++;
  28028. }
  28029. quickFinished = true;
  28030. } else if (dimSize === 2) {
  28031. var dimStorage = storageArr[dimIndices[0]];
  28032. var dimStorage2 = storageArr[dimIndices[1]];
  28033. var min2 = range[dimensions[1]][0];
  28034. var max2 = range[dimensions[1]][1];
  28035. for (var i = 0; i < len; i++) {
  28036. var val = dimStorage[i];
  28037. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  28038. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  28039. newIndices[offset++] = idx;
  28040. }
  28041. idx++;
  28042. }
  28043. quickFinished = true;
  28044. }
  28045. }
  28046. if (!quickFinished) {
  28047. if (dimSize === 1) {
  28048. for (var i = 0; i < originalCount; i++) {
  28049. var rawIndex = this.getRawIndex(i);
  28050. var val = storageArr[dimIndices[0]][rawIndex]; // Do not filter NaN, see comment above.
  28051. if (val >= min && val <= max || isNaN(val)) {
  28052. newIndices[offset++] = rawIndex;
  28053. }
  28054. }
  28055. } else {
  28056. for (var i = 0; i < originalCount; i++) {
  28057. var keep = true;
  28058. var rawIndex = this.getRawIndex(i);
  28059. for (var k = 0; k < dimSize; k++) {
  28060. var dimk = dimensions[k];
  28061. var val = storageArr[dimIndices[k]][rawIndex]; // Do not filter NaN, see comment above.
  28062. if (val < range[dimk][0] || val > range[dimk][1]) {
  28063. keep = false;
  28064. }
  28065. }
  28066. if (keep) {
  28067. newIndices[offset++] = this.getRawIndex(i);
  28068. }
  28069. }
  28070. }
  28071. } // Set indices after filtered.
  28072. if (offset < originalCount) {
  28073. this._indices = newIndices;
  28074. }
  28075. this._count = offset; // Reset data extent
  28076. this._extent = {};
  28077. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28078. return this;
  28079. };
  28080. /* eslint-enable */
  28081. List.prototype.mapArray = function (dims, cb, ctx, ctxCompat) {
  28082. if (typeof dims === 'function') {
  28083. ctxCompat = ctx;
  28084. ctx = cb;
  28085. cb = dims;
  28086. dims = [];
  28087. } // ctxCompat just for compat echarts3
  28088. ctx = ctx || ctxCompat || this;
  28089. var result = [];
  28090. this.each(dims, function () {
  28091. result.push(cb && cb.apply(this, arguments));
  28092. }, ctx);
  28093. return result;
  28094. };
  28095. List.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28096. var fCtx = ctx || ctxCompat || this;
  28097. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  28098. if ("development" !== 'production') {
  28099. validateDimensions(this, dimNames);
  28100. }
  28101. var list = cloneListForMapAndSample(this, dimNames);
  28102. var storage = list._storage; // Following properties are all immutable.
  28103. // So we can reference to the same value
  28104. list._indices = this._indices;
  28105. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28106. var tmpRetValue = [];
  28107. var dimSize = dimNames.length;
  28108. var dataCount = this.count();
  28109. var values = [];
  28110. var rawExtent = list._rawExtent;
  28111. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  28112. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  28113. values[dimIndex] = this.get(dimNames[dimIndex], dataIndex);
  28114. }
  28115. values[dimSize] = dataIndex;
  28116. var retValue = cb && cb.apply(fCtx, values);
  28117. if (retValue != null) {
  28118. // a number or string (in oridinal dimension)?
  28119. if (typeof retValue !== 'object') {
  28120. tmpRetValue[0] = retValue;
  28121. retValue = tmpRetValue;
  28122. }
  28123. var rawIndex = this.getRawIndex(dataIndex);
  28124. for (var i = 0; i < retValue.length; i++) {
  28125. var dim = dimNames[i];
  28126. var val = retValue[i];
  28127. var rawExtentOnDim = rawExtent[dim];
  28128. var dimStore = storage[dim];
  28129. if (dimStore) {
  28130. dimStore[rawIndex] = val;
  28131. }
  28132. if (val < rawExtentOnDim[0]) {
  28133. rawExtentOnDim[0] = val;
  28134. }
  28135. if (val > rawExtentOnDim[1]) {
  28136. rawExtentOnDim[1] = val;
  28137. }
  28138. }
  28139. }
  28140. }
  28141. return list;
  28142. };
  28143. /**
  28144. * Large data down sampling on given dimension
  28145. * @param sampleIndex Sample index for name and id
  28146. */
  28147. List.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28148. var list = cloneListForMapAndSample(this, [dimension]);
  28149. var targetStorage = list._storage;
  28150. var frameValues = [];
  28151. var frameSize = mathFloor(1 / rate);
  28152. var dimStore = targetStorage[dimension];
  28153. var len = this.count();
  28154. var rawExtentOnDim = list._rawExtent[dimension];
  28155. var newIndices = new (getIndicesCtor(this))(len);
  28156. var offset = 0;
  28157. for (var i = 0; i < len; i += frameSize) {
  28158. // Last frame
  28159. if (frameSize > len - i) {
  28160. frameSize = len - i;
  28161. frameValues.length = frameSize;
  28162. }
  28163. for (var k = 0; k < frameSize; k++) {
  28164. var dataIdx = this.getRawIndex(i + k);
  28165. frameValues[k] = dimStore[dataIdx];
  28166. }
  28167. var value = sampleValue(frameValues);
  28168. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  28169. dimStore[sampleFrameIdx] = value;
  28170. if (value < rawExtentOnDim[0]) {
  28171. rawExtentOnDim[0] = value;
  28172. }
  28173. if (value > rawExtentOnDim[1]) {
  28174. rawExtentOnDim[1] = value;
  28175. }
  28176. newIndices[offset++] = sampleFrameIdx;
  28177. }
  28178. list._count = offset;
  28179. list._indices = newIndices;
  28180. list.getRawIndex = getRawIndexWithIndices;
  28181. return list;
  28182. };
  28183. /**
  28184. * Large data down sampling using largest-triangle-three-buckets
  28185. * @param {string} valueDimension
  28186. * @param {number} targetCount
  28187. */
  28188. List.prototype.lttbDownSample = function (valueDimension, rate) {
  28189. var list = cloneListForMapAndSample(this, []);
  28190. var targetStorage = list._storage;
  28191. var dimStore = targetStorage[valueDimension];
  28192. var len = this.count();
  28193. var newIndices = new (getIndicesCtor(this))(len);
  28194. var sampledIndex = 0;
  28195. var frameSize = mathFloor(1 / rate);
  28196. var currentRawIndex = this.getRawIndex(0);
  28197. var maxArea;
  28198. var area;
  28199. var nextRawIndex; // First frame use the first data.
  28200. newIndices[sampledIndex++] = currentRawIndex;
  28201. for (var i = 1; i < len - 1; i += frameSize) {
  28202. var nextFrameStart = Math.min(i + frameSize, len - 1);
  28203. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  28204. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  28205. var avgY = 0;
  28206. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  28207. var rawIndex = this.getRawIndex(idx);
  28208. var y = dimStore[rawIndex];
  28209. if (isNaN(y)) {
  28210. continue;
  28211. }
  28212. avgY += y;
  28213. }
  28214. avgY /= nextFrameEnd - nextFrameStart;
  28215. var frameStart = i;
  28216. var frameEnd = Math.min(i + frameSize, len);
  28217. var pointAX = i - 1;
  28218. var pointAY = dimStore[currentRawIndex];
  28219. maxArea = -1;
  28220. nextRawIndex = frameStart; // Find a point from current frame that construct a triangel with largest area with previous selected point
  28221. // And the average of next frame.
  28222. for (var idx = frameStart; idx < frameEnd; idx++) {
  28223. var rawIndex = this.getRawIndex(idx);
  28224. var y = dimStore[rawIndex];
  28225. if (isNaN(y)) {
  28226. continue;
  28227. } // Calculate triangle area over three buckets
  28228. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  28229. if (area > maxArea) {
  28230. maxArea = area;
  28231. nextRawIndex = rawIndex; // Next a is this b
  28232. }
  28233. }
  28234. newIndices[sampledIndex++] = nextRawIndex;
  28235. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  28236. } // First frame use the last data.
  28237. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  28238. list._count = sampledIndex;
  28239. list._indices = newIndices;
  28240. list.getRawIndex = getRawIndexWithIndices;
  28241. return list;
  28242. };
  28243. /**
  28244. * Get model of one data item.
  28245. */
  28246. // TODO: Type of data item
  28247. List.prototype.getItemModel = function (idx) {
  28248. var hostModel = this.hostModel;
  28249. var dataItem = this.getRawDataItem(idx);
  28250. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28251. };
  28252. /**
  28253. * Create a data differ
  28254. */
  28255. List.prototype.diff = function (otherList) {
  28256. var thisList = this;
  28257. return new DataDiffer(otherList ? otherList.getIndices() : [], this.getIndices(), function (idx) {
  28258. return getId(otherList, idx);
  28259. }, function (idx) {
  28260. return getId(thisList, idx);
  28261. });
  28262. };
  28263. /**
  28264. * Get visual property.
  28265. */
  28266. List.prototype.getVisual = function (key) {
  28267. var visual = this._visual;
  28268. return visual && visual[key];
  28269. };
  28270. List.prototype.setVisual = function (kvObj, val) {
  28271. this._visual = this._visual || {};
  28272. if (isObject$3(kvObj)) {
  28273. extend(this._visual, kvObj);
  28274. } else {
  28275. this._visual[kvObj] = val;
  28276. }
  28277. };
  28278. /**
  28279. * Get visual property of single data item
  28280. */
  28281. // eslint-disable-next-line
  28282. List.prototype.getItemVisual = function (idx, key) {
  28283. var itemVisual = this._itemVisuals[idx];
  28284. var val = itemVisual && itemVisual[key];
  28285. if (val == null) {
  28286. // Use global visual property
  28287. return this.getVisual(key);
  28288. }
  28289. return val;
  28290. };
  28291. /**
  28292. * If exists visual property of single data item
  28293. */
  28294. List.prototype.hasItemVisual = function () {
  28295. return this._itemVisuals.length > 0;
  28296. };
  28297. /**
  28298. * Make sure itemVisual property is unique
  28299. */
  28300. // TODO: use key to save visual to reduce memory.
  28301. List.prototype.ensureUniqueItemVisual = function (idx, key) {
  28302. var itemVisuals = this._itemVisuals;
  28303. var itemVisual = itemVisuals[idx];
  28304. if (!itemVisual) {
  28305. itemVisual = itemVisuals[idx] = {};
  28306. }
  28307. var val = itemVisual[key];
  28308. if (val == null) {
  28309. val = this.getVisual(key); // TODO Performance?
  28310. if (isArray(val)) {
  28311. val = val.slice();
  28312. } else if (isObject$3(val)) {
  28313. val = extend({}, val);
  28314. }
  28315. itemVisual[key] = val;
  28316. }
  28317. return val;
  28318. }; // eslint-disable-next-line
  28319. List.prototype.setItemVisual = function (idx, key, value) {
  28320. var itemVisual = this._itemVisuals[idx] || {};
  28321. this._itemVisuals[idx] = itemVisual;
  28322. if (isObject$3(key)) {
  28323. extend(itemVisual, key);
  28324. } else {
  28325. itemVisual[key] = value;
  28326. }
  28327. };
  28328. /**
  28329. * Clear itemVisuals and list visual.
  28330. */
  28331. List.prototype.clearAllVisual = function () {
  28332. this._visual = {};
  28333. this._itemVisuals = [];
  28334. };
  28335. List.prototype.setLayout = function (key, val) {
  28336. if (isObject$3(key)) {
  28337. for (var name_1 in key) {
  28338. if (key.hasOwnProperty(name_1)) {
  28339. this.setLayout(name_1, key[name_1]);
  28340. }
  28341. }
  28342. return;
  28343. }
  28344. this._layout[key] = val;
  28345. };
  28346. /**
  28347. * Get layout property.
  28348. */
  28349. List.prototype.getLayout = function (key) {
  28350. return this._layout[key];
  28351. };
  28352. /**
  28353. * Get layout of single data item
  28354. */
  28355. List.prototype.getItemLayout = function (idx) {
  28356. return this._itemLayouts[idx];
  28357. };
  28358. /**
  28359. * Set layout of single data item
  28360. */
  28361. List.prototype.setItemLayout = function (idx, layout, merge) {
  28362. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  28363. };
  28364. /**
  28365. * Clear all layout of single data item
  28366. */
  28367. List.prototype.clearItemLayouts = function () {
  28368. this._itemLayouts.length = 0;
  28369. };
  28370. /**
  28371. * Set graphic element relative to data. It can be set as null
  28372. */
  28373. List.prototype.setItemGraphicEl = function (idx, el) {
  28374. var hostModel = this.hostModel;
  28375. if (el) {
  28376. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  28377. // Useful in tooltip
  28378. ecData.dataIndex = idx;
  28379. ecData.dataType = this.dataType;
  28380. ecData.seriesIndex = hostModel && hostModel.seriesIndex; // TODO: not store dataIndex on children.
  28381. if (el.type === 'group') {
  28382. el.traverse(setItemDataAndSeriesIndex, el);
  28383. }
  28384. }
  28385. this._graphicEls[idx] = el;
  28386. };
  28387. List.prototype.getItemGraphicEl = function (idx) {
  28388. return this._graphicEls[idx];
  28389. };
  28390. List.prototype.eachItemGraphicEl = function (cb, context) {
  28391. each(this._graphicEls, function (el, idx) {
  28392. if (el) {
  28393. cb && cb.call(context, el, idx);
  28394. }
  28395. });
  28396. };
  28397. /**
  28398. * Shallow clone a new list except visual and layout properties, and graph elements.
  28399. * New list only change the indices.
  28400. */
  28401. List.prototype.cloneShallow = function (list) {
  28402. if (!list) {
  28403. var dimensionInfoList = map$1(this.dimensions, this.getDimensionInfo, this);
  28404. list = new List(dimensionInfoList, this.hostModel);
  28405. } // FIXME
  28406. list._storage = this._storage;
  28407. list._storageArr = this._storageArr;
  28408. transferProperties(list, this); // Clone will not change the data extent and indices
  28409. if (this._indices) {
  28410. var Ctor = this._indices.constructor;
  28411. if (Ctor === Array) {
  28412. var thisCount = this._indices.length;
  28413. list._indices = new Ctor(thisCount);
  28414. for (var i = 0; i < thisCount; i++) {
  28415. list._indices[i] = this._indices[i];
  28416. }
  28417. } else {
  28418. list._indices = new Ctor(this._indices);
  28419. }
  28420. } else {
  28421. list._indices = null;
  28422. }
  28423. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28424. return list;
  28425. };
  28426. /**
  28427. * Wrap some method to add more feature
  28428. */
  28429. List.prototype.wrapMethod = function (methodName, injectFunction) {
  28430. var originalMethod = this[methodName];
  28431. if (typeof originalMethod !== 'function') {
  28432. return;
  28433. }
  28434. this.__wrappedMethods = this.__wrappedMethods || [];
  28435. this.__wrappedMethods.push(methodName);
  28436. this[methodName] = function () {
  28437. var res = originalMethod.apply(this, arguments);
  28438. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28439. };
  28440. }; // ----------------------------------------------------------
  28441. // A work around for internal method visiting private member.
  28442. // ----------------------------------------------------------
  28443. List.internalField = function () {
  28444. defaultDimValueGetters = {
  28445. arrayRows: getDimValueSimply,
  28446. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  28447. return parseDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  28448. },
  28449. keyedColumns: getDimValueSimply,
  28450. original: function (dataItem, dimName, dataIndex, dimIndex) {
  28451. // Performance sensitive, do not use modelUtil.getDataItemValue.
  28452. // If dataItem is an plain object with no value field, the let `value`
  28453. // will be assigned with the object, but it will be tread correctly
  28454. // in the `convertValue`.
  28455. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value); // If any dataItem is like { value: 10 }
  28456. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  28457. this.hasItemOption = true;
  28458. }
  28459. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  28460. : value, this._dimensionInfos[dimName]);
  28461. },
  28462. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  28463. return dataItem[dimIndex];
  28464. }
  28465. };
  28466. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  28467. return parseDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  28468. }
  28469. prepareInvertedIndex = function (list) {
  28470. var invertedIndicesMap = list._invertedIndicesMap;
  28471. each(invertedIndicesMap, function (invertedIndices, dim) {
  28472. var dimInfo = list._dimensionInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  28473. var ordinalMeta = dimInfo.ordinalMeta;
  28474. if (ordinalMeta) {
  28475. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  28476. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  28477. for (var i = 0; i < invertedIndices.length; i++) {
  28478. invertedIndices[i] = INDEX_NOT_FOUND;
  28479. }
  28480. for (var i = 0; i < list._count; i++) {
  28481. // Only support the case that all values are distinct.
  28482. invertedIndices[list.get(dim, i)] = i;
  28483. }
  28484. }
  28485. });
  28486. };
  28487. getIdNameFromStore = function (list, dimIdx, ordinalMeta, rawIndex) {
  28488. var val;
  28489. var chunk = list._storageArr[dimIdx];
  28490. if (chunk) {
  28491. val = chunk[rawIndex];
  28492. if (ordinalMeta && ordinalMeta.categories.length) {
  28493. val = ordinalMeta.categories[val];
  28494. }
  28495. }
  28496. return convertOptionIdName(val, null);
  28497. };
  28498. getIndicesCtor = function (list) {
  28499. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  28500. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  28501. };
  28502. prepareStorage = function (storage, dimInfo, end, append) {
  28503. var DataCtor = dataCtors[dimInfo.type];
  28504. var dim = dimInfo.name;
  28505. if (append) {
  28506. var oldStore = storage[dim];
  28507. var oldLen = oldStore && oldStore.length;
  28508. if (!(oldLen === end)) {
  28509. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  28510. // within the initial chunkSize.
  28511. for (var j = 0; j < oldLen; j++) {
  28512. newStore[j] = oldStore[j];
  28513. }
  28514. storage[dim] = newStore;
  28515. }
  28516. } else {
  28517. storage[dim] = new DataCtor(end);
  28518. }
  28519. };
  28520. getRawIndexWithoutIndices = function (idx) {
  28521. return idx;
  28522. };
  28523. getRawIndexWithIndices = function (idx) {
  28524. if (idx < this._count && idx >= 0) {
  28525. return this._indices[idx];
  28526. }
  28527. return -1;
  28528. };
  28529. /**
  28530. * @see the comment of `List['getId']`.
  28531. */
  28532. getId = function (list, rawIndex) {
  28533. var id = list._idList[rawIndex];
  28534. if (id == null && list._idDimIdx != null) {
  28535. id = getIdNameFromStore(list, list._idDimIdx, list._idOrdinalMeta, rawIndex);
  28536. }
  28537. if (id == null) {
  28538. id = ID_PREFIX + rawIndex;
  28539. }
  28540. return id;
  28541. };
  28542. normalizeDimensions = function (dimensions) {
  28543. if (!isArray(dimensions)) {
  28544. dimensions = dimensions != null ? [dimensions] : [];
  28545. }
  28546. return dimensions;
  28547. };
  28548. validateDimensions = function (list, dims) {
  28549. for (var i = 0; i < dims.length; i++) {
  28550. // stroage may be empty when no data, so use
  28551. // dimensionInfos to check.
  28552. if (!list._dimensionInfos[dims[i]]) {
  28553. console.error('Unkown dimension ' + dims[i]);
  28554. }
  28555. }
  28556. }; // Data in excludeDimensions is copied, otherwise transfered.
  28557. cloneListForMapAndSample = function (original, excludeDimensions) {
  28558. var allDimensions = original.dimensions;
  28559. var list = new List(map$1(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  28560. transferProperties(list, original);
  28561. var storage = list._storage = {};
  28562. var originalStorage = original._storage;
  28563. var storageArr = list._storageArr = []; // Init storage
  28564. for (var i = 0; i < allDimensions.length; i++) {
  28565. var dim = allDimensions[i];
  28566. if (originalStorage[dim]) {
  28567. // Notice that we do not reset invertedIndicesMap here, becuase
  28568. // there is no scenario of mapping or sampling ordinal dimension.
  28569. if (indexOf(excludeDimensions, dim) >= 0) {
  28570. storage[dim] = cloneChunk(originalStorage[dim]);
  28571. list._rawExtent[dim] = getInitialExtent();
  28572. list._extent[dim] = null;
  28573. } else {
  28574. // Direct reference for other dimensions
  28575. storage[dim] = originalStorage[dim];
  28576. }
  28577. storageArr.push(storage[dim]);
  28578. }
  28579. }
  28580. return list;
  28581. };
  28582. function cloneChunk(originalChunk) {
  28583. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  28584. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  28585. }
  28586. getInitialExtent = function () {
  28587. return [Infinity, -Infinity];
  28588. };
  28589. setItemDataAndSeriesIndex = function (child) {
  28590. var childECData = getECData(child);
  28591. var thisECData = getECData(this);
  28592. childECData.seriesIndex = thisECData.seriesIndex;
  28593. childECData.dataIndex = thisECData.dataIndex;
  28594. childECData.dataType = thisECData.dataType;
  28595. };
  28596. transferProperties = function (target, source) {
  28597. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  28598. if (source.hasOwnProperty(propName)) {
  28599. target[propName] = source[propName];
  28600. }
  28601. });
  28602. target.__wrappedMethods = source.__wrappedMethods;
  28603. each(CLONE_PROPERTIES, function (propName) {
  28604. target[propName] = clone(source[propName]);
  28605. });
  28606. target._calculationInfo = extend({}, source._calculationInfo);
  28607. };
  28608. makeIdFromName = function (list, idx) {
  28609. var nameList = list._nameList;
  28610. var idList = list._idList;
  28611. var nameDimIdx = list._nameDimIdx;
  28612. var idDimIdx = list._idDimIdx;
  28613. var name = nameList[idx];
  28614. var id = idList[idx];
  28615. if (name == null && nameDimIdx != null) {
  28616. nameList[idx] = name = getIdNameFromStore(list, nameDimIdx, list._nameOrdinalMeta, idx);
  28617. }
  28618. if (id == null && idDimIdx != null) {
  28619. idList[idx] = id = getIdNameFromStore(list, idDimIdx, list._idOrdinalMeta, idx);
  28620. }
  28621. if (id == null && name != null) {
  28622. var nameRepeatCount = list._nameRepeatCount;
  28623. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  28624. id = name;
  28625. if (nmCnt > 1) {
  28626. id += '__ec__' + nmCnt;
  28627. }
  28628. idList[idx] = id;
  28629. }
  28630. };
  28631. }();
  28632. return List;
  28633. }();
  28634. /**
  28635. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28636. *
  28637. * This method builds the relationship between:
  28638. * + "what the coord sys or series requires (see `sysDims`)",
  28639. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28640. * + "what the data source provids (see `source`)".
  28641. *
  28642. * Some guess strategy will be adapted if user does not define something.
  28643. * If no 'value' dimension specified, the first no-named dimension will be
  28644. * named as 'value'.
  28645. *
  28646. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28647. * provides not only dim template, but also default order.
  28648. * properties: 'name', 'type', 'displayName'.
  28649. * `name` of each item provides default coord name.
  28650. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28651. * provide dims count that the sysDim required.
  28652. * [{ordinalMeta}] can be specified.
  28653. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28654. * @param {Object} [opt]
  28655. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28656. * For example: ['asdf', {name, type}, ...].
  28657. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28658. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28659. * If not specified, auto find the next available data dim.
  28660. * param source {module:data/Source}
  28661. * param dimCount {number}
  28662. * return {Object} encode Never be `null/undefined`.
  28663. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28664. * If not specified, extra dim names will be:
  28665. * 'value', 'value0', 'value1', ...
  28666. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28667. * If `generateCoordCount` specified, the generated dim names will be:
  28668. * `generateCoord` + 0, `generateCoord` + 1, ...
  28669. * can be Infinity, indicate that use all of the remain columns.
  28670. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28671. * @return {Array.<module:data/DataDimensionInfo>}
  28672. */
  28673. function completeDimensions(sysDims, source, opt) {
  28674. if (!isSourceInstance(source)) {
  28675. source = createSourceFromSeriesDataOption(source);
  28676. }
  28677. opt = opt || {};
  28678. sysDims = (sysDims || []).slice();
  28679. var dimsDef = (opt.dimsDef || []).slice();
  28680. var dataDimNameMap = createHashMap();
  28681. var coordDimNameMap = createHashMap(); // let valueCandidate;
  28682. var result = [];
  28683. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount); // Apply user defined dims (`name` and `type`) and init result.
  28684. for (var i = 0; i < dimCount; i++) {
  28685. var dimDefItemRaw = dimsDef[i];
  28686. var dimDefItem = dimsDef[i] = extend({}, isObject(dimDefItemRaw) ? dimDefItemRaw : {
  28687. name: dimDefItemRaw
  28688. });
  28689. var userDimName = dimDefItem.name;
  28690. var resultItem = result[i] = new DataDimensionInfo(); // Name will be applied later for avoiding duplication.
  28691. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28692. // Only if `series.dimensions` is defined in option
  28693. // displayName, will be set, and dimension will be diplayed vertically in
  28694. // tooltip by default.
  28695. resultItem.name = resultItem.displayName = userDimName;
  28696. dataDimNameMap.set(userDimName, i);
  28697. }
  28698. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28699. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28700. }
  28701. var encodeDef = opt.encodeDef;
  28702. if (!encodeDef && opt.encodeDefaulter) {
  28703. encodeDef = opt.encodeDefaulter(source, dimCount);
  28704. }
  28705. var encodeDefMap = createHashMap(encodeDef); // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  28706. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  28707. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28708. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28709. // this case.
  28710. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28711. encodeDefMap.set(coordDim, false);
  28712. return;
  28713. }
  28714. var validDataDims = encodeDefMap.set(coordDim, []);
  28715. each(dataDims, function (resultDimIdxOrName, idx) {
  28716. // The input resultDimIdx can be dim name or index.
  28717. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  28718. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28719. validDataDims[idx] = resultDimIdx;
  28720. applyDim(result[resultDimIdx], coordDim, idx);
  28721. }
  28722. });
  28723. }); // Apply templetes and default order from `sysDims`.
  28724. var availDimIdx = 0;
  28725. each(sysDims, function (sysDimItemRaw) {
  28726. var coordDim;
  28727. var sysDimItemDimsDef;
  28728. var sysDimItemOtherDims;
  28729. var sysDimItem;
  28730. if (isString(sysDimItemRaw)) {
  28731. coordDim = sysDimItemRaw;
  28732. sysDimItem = {};
  28733. } else {
  28734. sysDimItem = sysDimItemRaw;
  28735. coordDim = sysDimItem.name;
  28736. var ordinalMeta = sysDimItem.ordinalMeta;
  28737. sysDimItem.ordinalMeta = null;
  28738. sysDimItem = clone(sysDimItem);
  28739. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  28740. sysDimItemDimsDef = sysDimItem.dimsDef;
  28741. sysDimItemOtherDims = sysDimItem.otherDims;
  28742. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28743. }
  28744. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  28745. if (dataDims === false) {
  28746. return;
  28747. }
  28748. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  28749. if (!dataDims.length) {
  28750. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28751. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28752. availDimIdx++;
  28753. }
  28754. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28755. }
  28756. } // Apply templates.
  28757. each(dataDims, function (resultDimIdx, coordDimIndex) {
  28758. var resultItem = result[resultDimIdx];
  28759. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28760. if (resultItem.name == null && sysDimItemDimsDef) {
  28761. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28762. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  28763. name: sysDimItemDimsDefItem
  28764. });
  28765. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28766. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28767. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28768. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28769. });
  28770. });
  28771. function applyDim(resultItem, coordDim, coordDimIndex) {
  28772. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  28773. resultItem.otherDims[coordDim] = coordDimIndex;
  28774. } else {
  28775. resultItem.coordDim = coordDim;
  28776. resultItem.coordDimIndex = coordDimIndex;
  28777. coordDimNameMap.set(coordDim, true);
  28778. }
  28779. } // Make sure the first extra dim is 'value'.
  28780. var generateCoord = opt.generateCoord;
  28781. var generateCoordCount = opt.generateCoordCount;
  28782. var fromZero = generateCoordCount != null;
  28783. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  28784. var extra = generateCoord || 'value'; // Set dim `name` and other `coordDim` and other props.
  28785. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28786. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28787. var coordDim = resultItem.coordDim;
  28788. if (coordDim == null) {
  28789. resultItem.coordDim = genName(extra, coordDimNameMap, fromZero);
  28790. resultItem.coordDimIndex = 0;
  28791. if (!generateCoord || generateCoordCount <= 0) {
  28792. resultItem.isExtraCoord = true;
  28793. }
  28794. generateCoordCount--;
  28795. }
  28796. resultItem.name == null && (resultItem.name = genName(resultItem.coordDim, dataDimNameMap, false));
  28797. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  28798. // {
  28799. // dataset: {source: [
  28800. // ['2001', 123],
  28801. // ['2002', 456],
  28802. // ...
  28803. // ['The others', 987],
  28804. // ]},
  28805. // series: {type: 'pie'}
  28806. // }
  28807. // The first colum should better be treated as a "ordinal" although it
  28808. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28809. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  28810. resultItem.type = 'ordinal';
  28811. }
  28812. }
  28813. return result;
  28814. } // ??? TODO
  28815. // Originally detect dimCount by data[0]. Should we
  28816. // optimize it to only by sysDims and dimensions and encode.
  28817. // So only necessary dims will be initialized.
  28818. // But
  28819. // (1) custom series should be considered. where other dims
  28820. // may be visited.
  28821. // (2) sometimes user need to calcualte bubble size or use visualMap
  28822. // on other dimensions besides coordSys needed.
  28823. // So, dims that is not used by system, should be shared in storage?
  28824. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28825. // Note that the result dimCount should not small than columns count
  28826. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28827. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  28828. each(sysDims, function (sysDimItem) {
  28829. var sysDimItemDimsDef;
  28830. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  28831. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  28832. }
  28833. });
  28834. return dimCount;
  28835. }
  28836. function genName(name, map, fromZero) {
  28837. if (fromZero || map.get(name) != null) {
  28838. var i = 0;
  28839. while (map.get(name + i) != null) {
  28840. i++;
  28841. }
  28842. name += i;
  28843. }
  28844. map.set(name, true);
  28845. return name;
  28846. }
  28847. /**
  28848. * @param opt.coordDimensions
  28849. * @param opt.dimensionsDefine By default `source.dimensionsDefine` Overwrite source define.
  28850. * @param opt.encodeDefine By default `source.encodeDefine` Overwrite source define.
  28851. * @param opt.encodeDefaulter Make default encode if user not specified.
  28852. */
  28853. function createDimensions( // TODO: TYPE completeDimensions type
  28854. source, opt) {
  28855. opt = opt || {};
  28856. return completeDimensions(opt.coordDimensions || [], source, {
  28857. // FIXME:TS detect whether source then call `.dimensionsDefine` and `.encodeDefine`?
  28858. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28859. encodeDef: opt.encodeDefine || source.encodeDefine,
  28860. dimCount: opt.dimensionsCount,
  28861. encodeDefaulter: opt.encodeDefaulter,
  28862. generateCoord: opt.generateCoord,
  28863. generateCoordCount: opt.generateCoordCount
  28864. });
  28865. }
  28866. /**
  28867. * @class
  28868. * For example:
  28869. * {
  28870. * coordSysName: 'cartesian2d',
  28871. * coordSysDims: ['x', 'y', ...],
  28872. * axisMap: HashMap({
  28873. * x: xAxisModel,
  28874. * y: yAxisModel
  28875. * }),
  28876. * categoryAxisMap: HashMap({
  28877. * x: xAxisModel,
  28878. * y: undefined
  28879. * }),
  28880. * // The index of the first category axis in `coordSysDims`.
  28881. * // `null/undefined` means no category axis exists.
  28882. * firstCategoryDimIndex: 1,
  28883. * // To replace user specified encode.
  28884. * }
  28885. */
  28886. var CoordSysInfo =
  28887. /** @class */
  28888. function () {
  28889. function CoordSysInfo(coordSysName) {
  28890. this.coordSysDims = [];
  28891. this.axisMap = createHashMap();
  28892. this.categoryAxisMap = createHashMap();
  28893. this.coordSysName = coordSysName;
  28894. }
  28895. return CoordSysInfo;
  28896. }();
  28897. function getCoordSysInfoBySeries(seriesModel) {
  28898. var coordSysName = seriesModel.get('coordinateSystem');
  28899. var result = new CoordSysInfo(coordSysName);
  28900. var fetch = fetchers[coordSysName];
  28901. if (fetch) {
  28902. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28903. return result;
  28904. }
  28905. }
  28906. var fetchers = {
  28907. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28908. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  28909. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  28910. if ("development" !== 'production') {
  28911. if (!xAxisModel) {
  28912. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  28913. }
  28914. if (!yAxisModel) {
  28915. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  28916. }
  28917. }
  28918. result.coordSysDims = ['x', 'y'];
  28919. axisMap.set('x', xAxisModel);
  28920. axisMap.set('y', yAxisModel);
  28921. if (isCategory(xAxisModel)) {
  28922. categoryAxisMap.set('x', xAxisModel);
  28923. result.firstCategoryDimIndex = 0;
  28924. }
  28925. if (isCategory(yAxisModel)) {
  28926. categoryAxisMap.set('y', yAxisModel);
  28927. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28928. }
  28929. },
  28930. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28931. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  28932. if ("development" !== 'production') {
  28933. if (!singleAxisModel) {
  28934. throw new Error('singleAxis should be specified.');
  28935. }
  28936. }
  28937. result.coordSysDims = ['single'];
  28938. axisMap.set('single', singleAxisModel);
  28939. if (isCategory(singleAxisModel)) {
  28940. categoryAxisMap.set('single', singleAxisModel);
  28941. result.firstCategoryDimIndex = 0;
  28942. }
  28943. },
  28944. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28945. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  28946. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28947. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28948. if ("development" !== 'production') {
  28949. if (!angleAxisModel) {
  28950. throw new Error('angleAxis option not found');
  28951. }
  28952. if (!radiusAxisModel) {
  28953. throw new Error('radiusAxis option not found');
  28954. }
  28955. }
  28956. result.coordSysDims = ['radius', 'angle'];
  28957. axisMap.set('radius', radiusAxisModel);
  28958. axisMap.set('angle', angleAxisModel);
  28959. if (isCategory(radiusAxisModel)) {
  28960. categoryAxisMap.set('radius', radiusAxisModel);
  28961. result.firstCategoryDimIndex = 0;
  28962. }
  28963. if (isCategory(angleAxisModel)) {
  28964. categoryAxisMap.set('angle', angleAxisModel);
  28965. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28966. }
  28967. },
  28968. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28969. result.coordSysDims = ['lng', 'lat'];
  28970. },
  28971. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28972. var ecModel = seriesModel.ecModel;
  28973. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  28974. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28975. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28976. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28977. var axisDim = coordSysDims[index];
  28978. axisMap.set(axisDim, axisModel);
  28979. if (isCategory(axisModel)) {
  28980. categoryAxisMap.set(axisDim, axisModel);
  28981. if (result.firstCategoryDimIndex == null) {
  28982. result.firstCategoryDimIndex = index;
  28983. }
  28984. }
  28985. });
  28986. }
  28987. };
  28988. function isCategory(axisModel) {
  28989. return axisModel.get('type') === 'category';
  28990. }
  28991. /**
  28992. * Note that it is too complicated to support 3d stack by value
  28993. * (have to create two-dimension inverted index), so in 3d case
  28994. * we just support that stacked by index.
  28995. *
  28996. * @param seriesModel
  28997. * @param dimensionInfoList The same as the input of <module:echarts/data/List>.
  28998. * The input dimensionInfoList will be modified.
  28999. * @param opt
  29000. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29001. * @param opt.byIndex=false
  29002. * @return calculationInfo
  29003. * {
  29004. * stackedDimension: string
  29005. * stackedByDimension: string
  29006. * isStackedByIndex: boolean
  29007. * stackedOverDimension: string
  29008. * stackResultDimension: string
  29009. * }
  29010. */
  29011. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  29012. opt = opt || {};
  29013. var byIndex = opt.byIndex;
  29014. var stackedCoordDimension = opt.stackedCoordDimension; // Compatibal: when `stack` is set as '', do not stack.
  29015. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29016. var stackedByDimInfo;
  29017. var stackedDimInfo;
  29018. var stackResultDimension;
  29019. var stackedOverDimension;
  29020. each(dimensionInfoList, function (dimensionInfo, index) {
  29021. if (isString(dimensionInfo)) {
  29022. dimensionInfoList[index] = dimensionInfo = {
  29023. name: dimensionInfo
  29024. };
  29025. }
  29026. if (mayStack && !dimensionInfo.isExtraCoord) {
  29027. // Find the first ordinal dimension as the stackedByDimInfo.
  29028. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29029. stackedByDimInfo = dimensionInfo;
  29030. } // Find the first stackable dimension as the stackedDimInfo.
  29031. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29032. stackedDimInfo = dimensionInfo;
  29033. }
  29034. }
  29035. });
  29036. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29037. // Compatible with previous design, value axis (time axis) only stack by index.
  29038. // It may make sense if the user provides elaborately constructed data.
  29039. byIndex = true;
  29040. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29041. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29042. // might not be a good way.
  29043. if (stackedDimInfo) {
  29044. // Use a weird name that not duplicated with other names.
  29045. stackResultDimension = '__\0ecstackresult';
  29046. stackedOverDimension = '__\0ecstackedover'; // Create inverted index to fast query index by value.
  29047. if (stackedByDimInfo) {
  29048. stackedByDimInfo.createInvertedIndices = true;
  29049. }
  29050. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29051. var stackedDimType = stackedDimInfo.type;
  29052. var stackedDimCoordIndex_1 = 0;
  29053. each(dimensionInfoList, function (dimensionInfo) {
  29054. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29055. stackedDimCoordIndex_1++;
  29056. }
  29057. });
  29058. dimensionInfoList.push({
  29059. name: stackResultDimension,
  29060. coordDim: stackedDimCoordDim_1,
  29061. coordDimIndex: stackedDimCoordIndex_1,
  29062. type: stackedDimType,
  29063. isExtraCoord: true,
  29064. isCalculationCoord: true
  29065. });
  29066. stackedDimCoordIndex_1++;
  29067. dimensionInfoList.push({
  29068. name: stackedOverDimension,
  29069. // This dimension contains stack base (generally, 0), so do not set it as
  29070. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29071. coordDim: stackedOverDimension,
  29072. coordDimIndex: stackedDimCoordIndex_1,
  29073. type: stackedDimType,
  29074. isExtraCoord: true,
  29075. isCalculationCoord: true
  29076. });
  29077. }
  29078. return {
  29079. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29080. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29081. isStackedByIndex: byIndex,
  29082. stackedOverDimension: stackedOverDimension,
  29083. stackResultDimension: stackResultDimension
  29084. };
  29085. }
  29086. function isDimensionStacked(data, stackedDim
  29087. /*, stackedByDim*/
  29088. ) {
  29089. // Each single series only maps to one pair of axis. So we do not need to
  29090. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29091. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension'); // && (
  29092. // stackedByDim != null
  29093. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  29094. // : data.getCalculationInfo('isStackedByIndex')
  29095. // );
  29096. }
  29097. function getStackedDimension(data, targetDim) {
  29098. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29099. }
  29100. function createListFromArray(source, seriesModel, opt) {
  29101. opt = opt || {};
  29102. if (!isSourceInstance(source)) {
  29103. source = createSourceFromSeriesDataOption(source);
  29104. }
  29105. var coordSysName = seriesModel.get('coordinateSystem');
  29106. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29107. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29108. var coordSysDimDefs;
  29109. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29110. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29111. var dimInfo = {
  29112. name: dim
  29113. };
  29114. var axisModel = coordSysInfo.axisMap.get(dim);
  29115. if (axisModel) {
  29116. var axisType = axisModel.get('type');
  29117. dimInfo.type = getDimensionTypeByAxis(axisType); // dimInfo.stackable = isStackable(axisType);
  29118. }
  29119. return dimInfo;
  29120. });
  29121. }
  29122. if (!coordSysDimDefs) {
  29123. // Get dimensions from registered coordinate system
  29124. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29125. }
  29126. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29127. var dimInfoList = createDimensions(source, {
  29128. coordDimensions: coordSysDimDefs,
  29129. generateCoord: opt.generateCoord,
  29130. encodeDefaulter: isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null
  29131. });
  29132. var firstCategoryDimIndex;
  29133. var hasNameEncode;
  29134. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29135. var coordDim = dimInfo.coordDim;
  29136. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29137. if (categoryAxisModel) {
  29138. if (firstCategoryDimIndex == null) {
  29139. firstCategoryDimIndex = dimIndex;
  29140. }
  29141. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29142. if (opt.createInvertedIndices) {
  29143. dimInfo.createInvertedIndices = true;
  29144. }
  29145. }
  29146. if (dimInfo.otherDims.itemName != null) {
  29147. hasNameEncode = true;
  29148. }
  29149. });
  29150. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29151. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29152. }
  29153. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  29154. var list = new List(dimInfoList, seriesModel);
  29155. list.setCalculationInfo(stackCalculationInfo);
  29156. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29157. // Use dataIndex as ordinal value in categoryAxis
  29158. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29159. } : null;
  29160. list.hasItemOption = false;
  29161. list.initData(source, null, dimValueGetter);
  29162. return list;
  29163. }
  29164. function isNeedCompleteOrdinalData(source) {
  29165. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29166. var sampleItem = firstDataNotNull(source.data || []);
  29167. return sampleItem != null && !isArray(getDataItemValue(sampleItem));
  29168. }
  29169. }
  29170. function firstDataNotNull(data) {
  29171. var i = 0;
  29172. while (i < data.length && data[i] == null) {
  29173. i++;
  29174. }
  29175. return data[i];
  29176. }
  29177. var Scale =
  29178. /** @class */
  29179. function () {
  29180. function Scale(setting) {
  29181. this._setting = setting || {};
  29182. this._extent = [Infinity, -Infinity];
  29183. }
  29184. Scale.prototype.getSetting = function (name) {
  29185. return this._setting[name];
  29186. };
  29187. /**
  29188. * Set extent from data
  29189. */
  29190. Scale.prototype.unionExtent = function (other) {
  29191. var extent = this._extent;
  29192. other[0] < extent[0] && (extent[0] = other[0]);
  29193. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  29194. // this.setExtent(extent[0], extent[1]);
  29195. };
  29196. /**
  29197. * Set extent from data
  29198. */
  29199. Scale.prototype.unionExtentFromData = function (data, dim) {
  29200. this.unionExtent(data.getApproximateExtent(dim));
  29201. };
  29202. /**
  29203. * Get extent
  29204. *
  29205. * Extent is always in increase order.
  29206. */
  29207. Scale.prototype.getExtent = function () {
  29208. return this._extent.slice();
  29209. };
  29210. /**
  29211. * Set extent
  29212. */
  29213. Scale.prototype.setExtent = function (start, end) {
  29214. var thisExtent = this._extent;
  29215. if (!isNaN(start)) {
  29216. thisExtent[0] = start;
  29217. }
  29218. if (!isNaN(end)) {
  29219. thisExtent[1] = end;
  29220. }
  29221. };
  29222. /**
  29223. * If value is in extent range
  29224. */
  29225. Scale.prototype.isInExtentRange = function (value) {
  29226. return this._extent[0] <= value && this._extent[1] >= value;
  29227. };
  29228. /**
  29229. * When axis extent depends on data and no data exists,
  29230. * axis ticks should not be drawn, which is named 'blank'.
  29231. */
  29232. Scale.prototype.isBlank = function () {
  29233. return this._isBlank;
  29234. };
  29235. /**
  29236. * When axis extent depends on data and no data exists,
  29237. * axis ticks should not be drawn, which is named 'blank'.
  29238. */
  29239. Scale.prototype.setBlank = function (isBlank) {
  29240. this._isBlank = isBlank;
  29241. };
  29242. return Scale;
  29243. }();
  29244. enableClassManagement(Scale);
  29245. var OrdinalMeta =
  29246. /** @class */
  29247. function () {
  29248. function OrdinalMeta(opt) {
  29249. this.categories = opt.categories || [];
  29250. this._needCollect = opt.needCollect;
  29251. this._deduplication = opt.deduplication;
  29252. }
  29253. OrdinalMeta.createByAxisModel = function (axisModel) {
  29254. var option = axisModel.option;
  29255. var data = option.data;
  29256. var categories = data && map(data, getName);
  29257. return new OrdinalMeta({
  29258. categories: categories,
  29259. needCollect: !categories,
  29260. // deduplication is default in axis.
  29261. deduplication: option.dedplication !== false
  29262. });
  29263. };
  29264. OrdinalMeta.prototype.getOrdinal = function (category) {
  29265. // @ts-ignore
  29266. return this._getOrCreateMap().get(category);
  29267. };
  29268. /**
  29269. * @return The ordinal. If not found, return NaN.
  29270. */
  29271. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29272. var index;
  29273. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  29274. // This feature is only supported when !needCollect, because we should
  29275. // consider a common case: a value is 2017, which is a number but is
  29276. // expected to be tread as a category. This case usually happen in dataset,
  29277. // where it happent to be no need of the index feature.
  29278. if (typeof category !== 'string' && !needCollect) {
  29279. return category;
  29280. } // Optimize for the scenario:
  29281. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29282. // data has been ensured not duplicate and is large data.
  29283. // Notice, if a dataset dimension provide categroies, usually echarts
  29284. // should remove duplication except user tell echarts dont do that
  29285. // (set axis.deduplication = false), because echarts do not know whether
  29286. // the values in the category dimension has duplication (consider the
  29287. // parallel-aqi example)
  29288. if (needCollect && !this._deduplication) {
  29289. index = this.categories.length;
  29290. this.categories[index] = category;
  29291. return index;
  29292. }
  29293. var map = this._getOrCreateMap(); // @ts-ignore
  29294. index = map.get(category);
  29295. if (index == null) {
  29296. if (needCollect) {
  29297. index = this.categories.length;
  29298. this.categories[index] = category; // @ts-ignore
  29299. map.set(category, index);
  29300. } else {
  29301. index = NaN;
  29302. }
  29303. }
  29304. return index;
  29305. }; // Consider big data, do not create map until needed.
  29306. OrdinalMeta.prototype._getOrCreateMap = function () {
  29307. return this._map || (this._map = createHashMap(this.categories));
  29308. };
  29309. return OrdinalMeta;
  29310. }();
  29311. function getName(obj) {
  29312. if (isObject(obj) && obj.value != null) {
  29313. return obj.value;
  29314. } else {
  29315. return obj + '';
  29316. }
  29317. }
  29318. var roundNumber = round;
  29319. /**
  29320. * @param extent Both extent[0] and extent[1] should be valid number.
  29321. * Should be extent[0] < extent[1].
  29322. * @param splitNumber splitNumber should be >= 1.
  29323. */
  29324. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29325. var result = {};
  29326. var span = extent[1] - extent[0];
  29327. var interval = result.interval = nice(span / splitNumber, true);
  29328. if (minInterval != null && interval < minInterval) {
  29329. interval = result.interval = minInterval;
  29330. }
  29331. if (maxInterval != null && interval > maxInterval) {
  29332. interval = result.interval = maxInterval;
  29333. } // Tow more digital for tick.
  29334. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  29335. var niceTickExtent = result.niceTickExtent = [roundNumber(Math.ceil(extent[0] / interval) * interval, precision), roundNumber(Math.floor(extent[1] / interval) * interval, precision)];
  29336. fixExtent(niceTickExtent, extent);
  29337. return result;
  29338. }
  29339. /**
  29340. * @return interval precision
  29341. */
  29342. function getIntervalPrecision(interval) {
  29343. // Tow more digital for tick.
  29344. return getPrecisionSafe(interval) + 2;
  29345. }
  29346. function clamp(niceTickExtent, idx, extent) {
  29347. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29348. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29349. function fixExtent(niceTickExtent, extent) {
  29350. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29351. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29352. clamp(niceTickExtent, 0, extent);
  29353. clamp(niceTickExtent, 1, extent);
  29354. if (niceTickExtent[0] > niceTickExtent[1]) {
  29355. niceTickExtent[0] = niceTickExtent[1];
  29356. }
  29357. }
  29358. function contain$1(val, extent) {
  29359. return val >= extent[0] && val <= extent[1];
  29360. }
  29361. function normalize$1(val, extent) {
  29362. if (extent[1] === extent[0]) {
  29363. return 0.5;
  29364. }
  29365. return (val - extent[0]) / (extent[1] - extent[0]);
  29366. }
  29367. function scale$2(val, extent) {
  29368. return val * (extent[1] - extent[0]) + extent[0];
  29369. }
  29370. var OrdinalScale =
  29371. /** @class */
  29372. function (_super) {
  29373. __extends(OrdinalScale, _super);
  29374. function OrdinalScale(setting) {
  29375. var _this = _super.call(this, setting) || this;
  29376. _this.type = 'ordinal';
  29377. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  29378. // import approach to get OrdinalMeta class.
  29379. if (!ordinalMeta) {
  29380. ordinalMeta = new OrdinalMeta({});
  29381. }
  29382. if (isArray(ordinalMeta)) {
  29383. ordinalMeta = new OrdinalMeta({
  29384. categories: map(ordinalMeta, function (item) {
  29385. return isObject(item) ? item.value : item;
  29386. })
  29387. });
  29388. }
  29389. _this._ordinalMeta = ordinalMeta;
  29390. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  29391. return _this;
  29392. }
  29393. OrdinalScale.prototype.parse = function (val) {
  29394. return typeof val === 'string' ? this._ordinalMeta.getOrdinal(val) // val might be float.
  29395. : Math.round(val);
  29396. };
  29397. OrdinalScale.prototype.contain = function (rank) {
  29398. rank = this.parse(rank);
  29399. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  29400. };
  29401. /**
  29402. * Normalize given rank or name to linear [0, 1]
  29403. * @param val raw ordinal number.
  29404. * @return normalized value in [0, 1].
  29405. */
  29406. OrdinalScale.prototype.normalize = function (val) {
  29407. val = this._getTickNumber(this.parse(val));
  29408. return normalize$1(val, this._extent);
  29409. };
  29410. /**
  29411. * @param val normalized value in [0, 1].
  29412. * @return raw ordinal number.
  29413. */
  29414. OrdinalScale.prototype.scale = function (val) {
  29415. val = Math.round(scale$2(val, this._extent));
  29416. return this.getRawOrdinalNumber(val);
  29417. };
  29418. OrdinalScale.prototype.getTicks = function () {
  29419. var ticks = [];
  29420. var extent = this._extent;
  29421. var rank = extent[0];
  29422. while (rank <= extent[1]) {
  29423. ticks.push({
  29424. value: rank
  29425. });
  29426. rank++;
  29427. }
  29428. return ticks;
  29429. };
  29430. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  29431. // Not support.
  29432. return;
  29433. };
  29434. /**
  29435. * @see `Ordinal['_ordinalNumbersByTick']`
  29436. */
  29437. OrdinalScale.prototype.setSortInfo = function (info) {
  29438. if (info == null) {
  29439. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  29440. return;
  29441. }
  29442. var infoOrdinalNumbers = info.ordinalNumbers;
  29443. var ordinalsByTick = this._ordinalNumbersByTick = [];
  29444. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  29445. var tickNum = 0;
  29446. var allCategoryLen = this._ordinalMeta.categories.length;
  29447. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  29448. var ordinalNumber = infoOrdinalNumbers[tickNum];
  29449. ordinalsByTick[tickNum] = ordinalNumber;
  29450. ticksByOrdinal[ordinalNumber] = tickNum;
  29451. } // Handle that `series.data` only covers part of the `axis.category.data`.
  29452. var unusedOrdinal = 0;
  29453. for (; tickNum < allCategoryLen; ++tickNum) {
  29454. while (ticksByOrdinal[unusedOrdinal] != null) {
  29455. unusedOrdinal++;
  29456. }
  29457. ordinalsByTick.push(unusedOrdinal);
  29458. ticksByOrdinal[unusedOrdinal] = tickNum;
  29459. }
  29460. };
  29461. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  29462. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  29463. // where ordinal numbers are used as tick value directly.
  29464. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  29465. };
  29466. /**
  29467. * @usage
  29468. * ```js
  29469. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  29470. *
  29471. * // case0
  29472. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  29473. * // case1
  29474. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  29475. * // case2
  29476. * const coord = axis.dataToCoord(ordinalNumber);
  29477. * ```
  29478. *
  29479. * @param {OrdinalNumber} tickNumber index of display
  29480. */
  29481. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  29482. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  29483. // where ordinal numbers are used as tick value directly.
  29484. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  29485. };
  29486. /**
  29487. * Get item on tick
  29488. */
  29489. OrdinalScale.prototype.getLabel = function (tick) {
  29490. if (!this.isBlank()) {
  29491. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  29492. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  29493. // Return empty if it's not exist.
  29494. return cateogry == null ? '' : cateogry + '';
  29495. }
  29496. };
  29497. OrdinalScale.prototype.count = function () {
  29498. return this._extent[1] - this._extent[0] + 1;
  29499. };
  29500. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  29501. this.unionExtent(data.getApproximateExtent(dim));
  29502. };
  29503. /**
  29504. * @override
  29505. * If value is in extent range
  29506. */
  29507. OrdinalScale.prototype.isInExtentRange = function (value) {
  29508. value = this._getTickNumber(value);
  29509. return this._extent[0] <= value && this._extent[1] >= value;
  29510. };
  29511. OrdinalScale.prototype.getOrdinalMeta = function () {
  29512. return this._ordinalMeta;
  29513. };
  29514. OrdinalScale.prototype.niceTicks = function () {};
  29515. OrdinalScale.prototype.niceExtent = function () {};
  29516. OrdinalScale.type = 'ordinal';
  29517. return OrdinalScale;
  29518. }(Scale);
  29519. Scale.registerClass(OrdinalScale);
  29520. var roundNumber$1 = round;
  29521. var IntervalScale =
  29522. /** @class */
  29523. function (_super) {
  29524. __extends(IntervalScale, _super);
  29525. function IntervalScale() {
  29526. var _this = _super !== null && _super.apply(this, arguments) || this;
  29527. _this.type = 'interval'; // Step is calculated in adjustExtent.
  29528. _this._interval = 0;
  29529. _this._intervalPrecision = 2;
  29530. return _this;
  29531. }
  29532. IntervalScale.prototype.parse = function (val) {
  29533. return val;
  29534. };
  29535. IntervalScale.prototype.contain = function (val) {
  29536. return contain$1(val, this._extent);
  29537. };
  29538. IntervalScale.prototype.normalize = function (val) {
  29539. return normalize$1(val, this._extent);
  29540. };
  29541. IntervalScale.prototype.scale = function (val) {
  29542. return scale$2(val, this._extent);
  29543. };
  29544. IntervalScale.prototype.setExtent = function (start, end) {
  29545. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  29546. if (!isNaN(start)) {
  29547. thisExtent[0] = parseFloat(start);
  29548. }
  29549. if (!isNaN(end)) {
  29550. thisExtent[1] = parseFloat(end);
  29551. }
  29552. };
  29553. IntervalScale.prototype.unionExtent = function (other) {
  29554. var extent = this._extent;
  29555. other[0] < extent[0] && (extent[0] = other[0]);
  29556. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  29557. this.setExtent(extent[0], extent[1]);
  29558. };
  29559. IntervalScale.prototype.getInterval = function () {
  29560. return this._interval;
  29561. };
  29562. IntervalScale.prototype.setInterval = function (interval) {
  29563. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  29564. // We assume user wan't to set both interval, min, max to get a better result
  29565. this._niceExtent = this._extent.slice();
  29566. this._intervalPrecision = getIntervalPrecision(interval);
  29567. };
  29568. /**
  29569. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  29570. */
  29571. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  29572. var interval = this._interval;
  29573. var extent = this._extent;
  29574. var niceTickExtent = this._niceExtent;
  29575. var intervalPrecision = this._intervalPrecision;
  29576. var ticks = []; // If interval is 0, return [];
  29577. if (!interval) {
  29578. return ticks;
  29579. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  29580. var safeLimit = 10000;
  29581. if (extent[0] < niceTickExtent[0]) {
  29582. if (expandToNicedExtent) {
  29583. ticks.push({
  29584. value: roundNumber$1(niceTickExtent[0] - interval, intervalPrecision)
  29585. });
  29586. } else {
  29587. ticks.push({
  29588. value: extent[0]
  29589. });
  29590. }
  29591. }
  29592. var tick = niceTickExtent[0];
  29593. while (tick <= niceTickExtent[1]) {
  29594. ticks.push({
  29595. value: tick
  29596. }); // Avoid rounding error
  29597. tick = roundNumber$1(tick + interval, intervalPrecision);
  29598. if (tick === ticks[ticks.length - 1].value) {
  29599. // Consider out of safe float point, e.g.,
  29600. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29601. break;
  29602. }
  29603. if (ticks.length > safeLimit) {
  29604. return [];
  29605. }
  29606. } // Consider this case: the last item of ticks is smaller
  29607. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29608. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  29609. if (extent[1] > lastNiceTick) {
  29610. if (expandToNicedExtent) {
  29611. ticks.push({
  29612. value: roundNumber$1(lastNiceTick + interval, intervalPrecision)
  29613. });
  29614. } else {
  29615. ticks.push({
  29616. value: extent[1]
  29617. });
  29618. }
  29619. }
  29620. return ticks;
  29621. };
  29622. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  29623. var ticks = this.getTicks(true);
  29624. var minorTicks = [];
  29625. var extent = this.getExtent();
  29626. for (var i = 1; i < ticks.length; i++) {
  29627. var nextTick = ticks[i];
  29628. var prevTick = ticks[i - 1];
  29629. var count = 0;
  29630. var minorTicksGroup = [];
  29631. var interval = nextTick.value - prevTick.value;
  29632. var minorInterval = interval / splitNumber;
  29633. while (count < splitNumber - 1) {
  29634. var minorTick = roundNumber$1(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  29635. if (minorTick > extent[0] && minorTick < extent[1]) {
  29636. minorTicksGroup.push(minorTick);
  29637. }
  29638. count++;
  29639. }
  29640. minorTicks.push(minorTicksGroup);
  29641. }
  29642. return minorTicks;
  29643. };
  29644. /**
  29645. * @param opt.precision If 'auto', use nice presision.
  29646. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  29647. */
  29648. IntervalScale.prototype.getLabel = function (data, opt) {
  29649. if (data == null) {
  29650. return '';
  29651. }
  29652. var precision = opt && opt.precision;
  29653. if (precision == null) {
  29654. precision = getPrecisionSafe(data.value) || 0;
  29655. } else if (precision === 'auto') {
  29656. // Should be more precise then tick.
  29657. precision = this._intervalPrecision;
  29658. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29659. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29660. var dataNum = roundNumber$1(data.value, precision, true);
  29661. return addCommas(dataNum);
  29662. };
  29663. /**
  29664. * @param splitNumber By default `5`.
  29665. */
  29666. IntervalScale.prototype.niceTicks = function (splitNumber, minInterval, maxInterval) {
  29667. splitNumber = splitNumber || 5;
  29668. var extent = this._extent;
  29669. var span = extent[1] - extent[0];
  29670. if (!isFinite(span)) {
  29671. return;
  29672. } // User may set axis min 0 and data are all negative
  29673. // FIXME If it needs to reverse ?
  29674. if (span < 0) {
  29675. span = -span;
  29676. extent.reverse();
  29677. }
  29678. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  29679. this._intervalPrecision = result.intervalPrecision;
  29680. this._interval = result.interval;
  29681. this._niceExtent = result.niceTickExtent;
  29682. };
  29683. IntervalScale.prototype.niceExtent = function (opt) {
  29684. var extent = this._extent; // If extent start and end are same, expand them
  29685. if (extent[0] === extent[1]) {
  29686. if (extent[0] !== 0) {
  29687. // Expand extent
  29688. var expandSize = extent[0]; // In the fowllowing case
  29689. // Axis has been fixed max 100
  29690. // Plus data are all 100 and axis extent are [100, 100].
  29691. // Extend to the both side will cause expanded max is larger than fixed max.
  29692. // So only expand to the smaller side.
  29693. if (!opt.fixMax) {
  29694. extent[1] += expandSize / 2;
  29695. extent[0] -= expandSize / 2;
  29696. } else {
  29697. extent[0] -= expandSize / 2;
  29698. }
  29699. } else {
  29700. extent[1] = 1;
  29701. }
  29702. }
  29703. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  29704. if (!isFinite(span)) {
  29705. extent[0] = 0;
  29706. extent[1] = 1;
  29707. }
  29708. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  29709. var interval = this._interval;
  29710. if (!opt.fixMin) {
  29711. extent[0] = roundNumber$1(Math.floor(extent[0] / interval) * interval);
  29712. }
  29713. if (!opt.fixMax) {
  29714. extent[1] = roundNumber$1(Math.ceil(extent[1] / interval) * interval);
  29715. }
  29716. };
  29717. IntervalScale.type = 'interval';
  29718. return IntervalScale;
  29719. }(Scale);
  29720. Scale.registerClass(IntervalScale);
  29721. var STACK_PREFIX = '__ec_stack_';
  29722. var LARGE_BAR_MIN_WIDTH = 0.5;
  29723. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29724. function getSeriesStackId(seriesModel) {
  29725. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29726. }
  29727. function getAxisKey(axis) {
  29728. return axis.dim + axis.index;
  29729. }
  29730. function prepareLayoutBarSeries(seriesType, ecModel) {
  29731. var seriesModels = [];
  29732. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29733. // Check series coordinate, do layout for cartesian2d only
  29734. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29735. seriesModels.push(seriesModel);
  29736. }
  29737. });
  29738. return seriesModels;
  29739. }
  29740. /**
  29741. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29742. * values.
  29743. * This works for time axes, value axes, and log axes.
  29744. * For a single time axis, return value is in the form like
  29745. * {'x_0': [1000000]}.
  29746. * The value of 1000000 is in milliseconds.
  29747. */
  29748. function getValueAxesMinGaps(barSeries) {
  29749. /**
  29750. * Map from axis.index to values.
  29751. * For a single time axis, axisValues is in the form like
  29752. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29753. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29754. * series.
  29755. */
  29756. var axisValues = {};
  29757. each(barSeries, function (seriesModel) {
  29758. var cartesian = seriesModel.coordinateSystem;
  29759. var baseAxis = cartesian.getBaseAxis();
  29760. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29761. return;
  29762. }
  29763. var data = seriesModel.getData();
  29764. var key = baseAxis.dim + '_' + baseAxis.index;
  29765. var dim = data.mapDimension(baseAxis.dim);
  29766. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29767. var value = data.get(dim, i);
  29768. if (!axisValues[key]) {
  29769. // No previous data for the axis
  29770. axisValues[key] = [value];
  29771. } else {
  29772. // No value in previous series
  29773. axisValues[key].push(value);
  29774. } // Ignore duplicated time values in the same axis
  29775. }
  29776. });
  29777. var axisMinGaps = {};
  29778. for (var key in axisValues) {
  29779. if (axisValues.hasOwnProperty(key)) {
  29780. var valuesInAxis = axisValues[key];
  29781. if (valuesInAxis) {
  29782. // Sort axis values into ascending order to calculate gaps
  29783. valuesInAxis.sort(function (a, b) {
  29784. return a - b;
  29785. });
  29786. var min = null;
  29787. for (var j = 1; j < valuesInAxis.length; ++j) {
  29788. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29789. if (delta > 0) {
  29790. // Ignore 0 delta because they are of the same axis value
  29791. min = min === null ? delta : Math.min(min, delta);
  29792. }
  29793. } // Set to null if only have one data
  29794. axisMinGaps[key] = min;
  29795. }
  29796. }
  29797. }
  29798. return axisMinGaps;
  29799. }
  29800. function makeColumnLayout(barSeries) {
  29801. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29802. var seriesInfoList = [];
  29803. each(barSeries, function (seriesModel) {
  29804. var cartesian = seriesModel.coordinateSystem;
  29805. var baseAxis = cartesian.getBaseAxis();
  29806. var axisExtent = baseAxis.getExtent();
  29807. var bandWidth;
  29808. if (baseAxis.type === 'category') {
  29809. bandWidth = baseAxis.getBandWidth();
  29810. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29811. var key = baseAxis.dim + '_' + baseAxis.index;
  29812. var minGap = axisMinGaps[key];
  29813. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29814. var scale = baseAxis.scale.getExtent();
  29815. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29816. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  29817. } else {
  29818. var data = seriesModel.getData();
  29819. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29820. }
  29821. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  29822. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  29823. var barMinWidth = parsePercent$1( // barMinWidth by default is 1 in cartesian. Because in value axis,
  29824. // the auto-calculated bar width might be less than 1.
  29825. seriesModel.get('barMinWidth') || 1, bandWidth);
  29826. var barGap = seriesModel.get('barGap');
  29827. var barCategoryGap = seriesModel.get('barCategoryGap');
  29828. seriesInfoList.push({
  29829. bandWidth: bandWidth,
  29830. barWidth: barWidth,
  29831. barMaxWidth: barMaxWidth,
  29832. barMinWidth: barMinWidth,
  29833. barGap: barGap,
  29834. barCategoryGap: barCategoryGap,
  29835. axisKey: getAxisKey(baseAxis),
  29836. stackId: getSeriesStackId(seriesModel)
  29837. });
  29838. });
  29839. return doCalBarWidthAndOffset(seriesInfoList);
  29840. }
  29841. function doCalBarWidthAndOffset(seriesInfoList) {
  29842. // Columns info on each category axis. Key is cartesian name
  29843. var columnsMap = {};
  29844. each(seriesInfoList, function (seriesInfo, idx) {
  29845. var axisKey = seriesInfo.axisKey;
  29846. var bandWidth = seriesInfo.bandWidth;
  29847. var columnsOnAxis = columnsMap[axisKey] || {
  29848. bandWidth: bandWidth,
  29849. remainedWidth: bandWidth,
  29850. autoWidthCount: 0,
  29851. categoryGap: null,
  29852. gap: '20%',
  29853. stacks: {}
  29854. };
  29855. var stacks = columnsOnAxis.stacks;
  29856. columnsMap[axisKey] = columnsOnAxis;
  29857. var stackId = seriesInfo.stackId;
  29858. if (!stacks[stackId]) {
  29859. columnsOnAxis.autoWidthCount++;
  29860. }
  29861. stacks[stackId] = stacks[stackId] || {
  29862. width: 0,
  29863. maxWidth: 0
  29864. }; // Caution: In a single coordinate system, these barGrid attributes
  29865. // will be shared by series. Consider that they have default values,
  29866. // only the attributes set on the last series will work.
  29867. // Do not change this fact unless there will be a break change.
  29868. var barWidth = seriesInfo.barWidth;
  29869. if (barWidth && !stacks[stackId].width) {
  29870. // See #6312, do not restrict width.
  29871. stacks[stackId].width = barWidth;
  29872. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29873. columnsOnAxis.remainedWidth -= barWidth;
  29874. }
  29875. var barMaxWidth = seriesInfo.barMaxWidth;
  29876. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  29877. var barMinWidth = seriesInfo.barMinWidth;
  29878. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  29879. var barGap = seriesInfo.barGap;
  29880. barGap != null && (columnsOnAxis.gap = barGap);
  29881. var barCategoryGap = seriesInfo.barCategoryGap;
  29882. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  29883. });
  29884. var result = {};
  29885. each(columnsMap, function (columnsOnAxis, coordSysName) {
  29886. result[coordSysName] = {};
  29887. var stacks = columnsOnAxis.stacks;
  29888. var bandWidth = columnsOnAxis.bandWidth;
  29889. var categoryGapPercent = columnsOnAxis.categoryGap;
  29890. if (categoryGapPercent == null) {
  29891. var columnCount = keys(stacks).length; // More columns in one group
  29892. // the spaces between group is smaller. Or the column will be too thin.
  29893. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  29894. }
  29895. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  29896. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  29897. var remainedWidth = columnsOnAxis.remainedWidth;
  29898. var autoWidthCount = columnsOnAxis.autoWidthCount;
  29899. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29900. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  29901. each(stacks, function (column) {
  29902. var maxWidth = column.maxWidth;
  29903. var minWidth = column.minWidth;
  29904. if (!column.width) {
  29905. var finalWidth = autoWidth;
  29906. if (maxWidth && maxWidth < finalWidth) {
  29907. finalWidth = Math.min(maxWidth, remainedWidth);
  29908. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  29909. // bar is able to be visible. So `minWidth` should not be restricted
  29910. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  29911. // the extreme cases for `value` axis, bars are allowed to overlap
  29912. // with each other if `minWidth` specified.
  29913. if (minWidth && minWidth > finalWidth) {
  29914. finalWidth = minWidth;
  29915. }
  29916. if (finalWidth !== autoWidth) {
  29917. column.width = finalWidth;
  29918. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29919. autoWidthCount--;
  29920. }
  29921. } else {
  29922. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  29923. // CSS does. Becuase barWidth can be a percent value, where
  29924. // `barMaxWidth` can be used to restrict the final width.
  29925. var finalWidth = column.width;
  29926. if (maxWidth) {
  29927. finalWidth = Math.min(finalWidth, maxWidth);
  29928. } // `minWidth` has higher priority, as described above
  29929. if (minWidth) {
  29930. finalWidth = Math.max(finalWidth, minWidth);
  29931. }
  29932. column.width = finalWidth;
  29933. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29934. autoWidthCount--;
  29935. }
  29936. }); // Recalculate width again
  29937. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29938. autoWidth = Math.max(autoWidth, 0);
  29939. var widthSum = 0;
  29940. var lastColumn;
  29941. each(stacks, function (column, idx) {
  29942. if (!column.width) {
  29943. column.width = autoWidth;
  29944. }
  29945. lastColumn = column;
  29946. widthSum += column.width * (1 + barGapPercent);
  29947. });
  29948. if (lastColumn) {
  29949. widthSum -= lastColumn.width * barGapPercent;
  29950. }
  29951. var offset = -widthSum / 2;
  29952. each(stacks, function (column, stackId) {
  29953. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  29954. bandWidth: bandWidth,
  29955. offset: offset,
  29956. width: column.width
  29957. };
  29958. offset += column.width * (1 + barGapPercent);
  29959. });
  29960. });
  29961. return result;
  29962. }
  29963. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  29964. if (barWidthAndOffset && axis) {
  29965. var result = barWidthAndOffset[getAxisKey(axis)];
  29966. if (result != null && seriesModel != null) {
  29967. return result[getSeriesStackId(seriesModel)];
  29968. }
  29969. return result;
  29970. }
  29971. }
  29972. function layout(seriesType, ecModel) {
  29973. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  29974. var barWidthAndOffset = makeColumnLayout(seriesModels);
  29975. var lastStackCoords = {};
  29976. each(seriesModels, function (seriesModel) {
  29977. var data = seriesModel.getData();
  29978. var cartesian = seriesModel.coordinateSystem;
  29979. var baseAxis = cartesian.getBaseAxis();
  29980. var stackId = getSeriesStackId(seriesModel);
  29981. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  29982. var columnOffset = columnLayoutInfo.offset;
  29983. var columnWidth = columnLayoutInfo.width;
  29984. var valueAxis = cartesian.getOtherAxis(baseAxis);
  29985. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  29986. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  29987. data.setLayout({
  29988. bandWidth: columnLayoutInfo.bandWidth,
  29989. offset: columnOffset,
  29990. size: columnWidth
  29991. });
  29992. var valueDim = data.mapDimension(valueAxis.dim);
  29993. var baseDim = data.mapDimension(baseAxis.dim);
  29994. var stacked = isDimensionStacked(data, valueDim
  29995. /*, baseDim*/
  29996. );
  29997. var isValueAxisH = valueAxis.isHorizontal();
  29998. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  29999. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30000. var value = data.get(valueDim, idx);
  30001. var baseValue = data.get(baseDim, idx);
  30002. var sign = value >= 0 ? 'p' : 'n';
  30003. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  30004. // stackResultDimension directly.
  30005. if (stacked) {
  30006. // Only ordinal axis can be stacked.
  30007. if (!lastStackCoords[stackId][baseValue]) {
  30008. lastStackCoords[stackId][baseValue] = {
  30009. p: valueAxisStart,
  30010. n: valueAxisStart // Negative stack
  30011. };
  30012. } // Should also consider #4243
  30013. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30014. }
  30015. var x = void 0;
  30016. var y = void 0;
  30017. var width = void 0;
  30018. var height = void 0;
  30019. if (isValueAxisH) {
  30020. var coord = cartesian.dataToPoint([value, baseValue]);
  30021. x = baseCoord;
  30022. y = coord[1] + columnOffset;
  30023. width = coord[0] - valueAxisStart;
  30024. height = columnWidth;
  30025. if (Math.abs(width) < barMinHeight) {
  30026. width = (width < 0 ? -1 : 1) * barMinHeight;
  30027. } // Ignore stack from NaN value
  30028. if (!isNaN(width)) {
  30029. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30030. }
  30031. } else {
  30032. var coord = cartesian.dataToPoint([baseValue, value]);
  30033. x = coord[0] + columnOffset;
  30034. y = baseCoord;
  30035. width = columnWidth;
  30036. height = coord[1] - valueAxisStart;
  30037. if (Math.abs(height) < barMinHeight) {
  30038. // Include zero to has a positive bar
  30039. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30040. } // Ignore stack from NaN value
  30041. if (!isNaN(height)) {
  30042. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30043. }
  30044. }
  30045. data.setItemLayout(idx, {
  30046. x: x,
  30047. y: y,
  30048. width: width,
  30049. height: height
  30050. });
  30051. }
  30052. });
  30053. } // TODO: Do not support stack in large mode yet.
  30054. var largeLayout = {
  30055. seriesType: 'bar',
  30056. plan: createRenderPlanner(),
  30057. reset: function (seriesModel) {
  30058. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30059. return;
  30060. }
  30061. var data = seriesModel.getData();
  30062. var cartesian = seriesModel.coordinateSystem;
  30063. var coordLayout = cartesian.master.getRect();
  30064. var baseAxis = cartesian.getBaseAxis();
  30065. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30066. var valueDim = data.mapDimension(valueAxis.dim);
  30067. var baseDim = data.mapDimension(baseAxis.dim);
  30068. var valueAxisHorizontal = valueAxis.isHorizontal();
  30069. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30070. var barWidth = retrieveColumnLayout(makeColumnLayout([seriesModel]), baseAxis, seriesModel).width;
  30071. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) {
  30072. // jshint ignore:line
  30073. barWidth = LARGE_BAR_MIN_WIDTH;
  30074. }
  30075. return {
  30076. progress: function (params, data) {
  30077. var count = params.count;
  30078. var largePoints = new LargeArr(count * 2);
  30079. var largeBackgroundPoints = new LargeArr(count * 2);
  30080. var largeDataIndices = new LargeArr(count);
  30081. var dataIndex;
  30082. var coord = [];
  30083. var valuePair = [];
  30084. var pointsOffset = 0;
  30085. var idxOffset = 0;
  30086. while ((dataIndex = params.next()) != null) {
  30087. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30088. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30089. coord = cartesian.dataToPoint(valuePair, null, coord); // Data index might not be in order, depends on `progressiveChunkMode`.
  30090. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];
  30091. largePoints[pointsOffset++] = coord[0];
  30092. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height;
  30093. largePoints[pointsOffset++] = coord[1];
  30094. largeDataIndices[idxOffset++] = dataIndex;
  30095. }
  30096. data.setLayout({
  30097. largePoints: largePoints,
  30098. largeDataIndices: largeDataIndices,
  30099. largeBackgroundPoints: largeBackgroundPoints,
  30100. barWidth: barWidth,
  30101. valueAxisStart: getValueAxisStart(baseAxis, valueAxis),
  30102. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  30103. valueAxisHorizontal: valueAxisHorizontal
  30104. });
  30105. }
  30106. };
  30107. }
  30108. };
  30109. function isOnCartesian(seriesModel) {
  30110. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30111. }
  30112. function isInLargeMode(seriesModel) {
  30113. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30114. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30115. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30116. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30117. }
  30118. var bisect = function (a, x, lo, hi) {
  30119. while (lo < hi) {
  30120. var mid = lo + hi >>> 1;
  30121. if (a[mid][1] < x) {
  30122. lo = mid + 1;
  30123. } else {
  30124. hi = mid;
  30125. }
  30126. }
  30127. return lo;
  30128. };
  30129. var TimeScale =
  30130. /** @class */
  30131. function (_super) {
  30132. __extends(TimeScale, _super);
  30133. function TimeScale(settings) {
  30134. var _this = _super.call(this, settings) || this;
  30135. _this.type = 'time';
  30136. return _this;
  30137. }
  30138. /**
  30139. * Get label is mainly for other components like dataZoom, tooltip.
  30140. */
  30141. TimeScale.prototype.getLabel = function (tick) {
  30142. var useUTC = this.getSetting('useUTC');
  30143. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30144. };
  30145. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30146. var isUTC = this.getSetting('useUTC');
  30147. var lang = this.getSetting('locale');
  30148. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30149. };
  30150. /**
  30151. * @override
  30152. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  30153. */
  30154. TimeScale.prototype.getTicks = function (expandToNicedExtent) {
  30155. var interval = this._interval;
  30156. var extent = this._extent;
  30157. var ticks = []; // If interval is 0, return [];
  30158. if (!interval) {
  30159. return ticks;
  30160. }
  30161. ticks.push({
  30162. value: extent[0],
  30163. level: 0
  30164. });
  30165. var useUTC = this.getSetting('useUTC');
  30166. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30167. ticks = ticks.concat(innerTicks);
  30168. ticks.push({
  30169. value: extent[1],
  30170. level: 0
  30171. });
  30172. return ticks;
  30173. };
  30174. TimeScale.prototype.niceExtent = function (opt) {
  30175. var extent = this._extent; // If extent start and end are same, expand them
  30176. if (extent[0] === extent[1]) {
  30177. // Expand extent
  30178. extent[0] -= ONE_DAY;
  30179. extent[1] += ONE_DAY;
  30180. } // If there are no data and extent are [Infinity, -Infinity]
  30181. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30182. var d = new Date();
  30183. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30184. extent[0] = extent[1] - ONE_DAY;
  30185. }
  30186. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30187. };
  30188. TimeScale.prototype.niceTicks = function (approxTickNum, minInterval, maxInterval) {
  30189. approxTickNum = approxTickNum || 10;
  30190. var extent = this._extent;
  30191. var span = extent[1] - extent[0];
  30192. this._approxInterval = span / approxTickNum;
  30193. if (minInterval != null && this._approxInterval < minInterval) {
  30194. this._approxInterval = minInterval;
  30195. }
  30196. if (maxInterval != null && this._approxInterval > maxInterval) {
  30197. this._approxInterval = maxInterval;
  30198. }
  30199. var scaleIntervalsLen = scaleIntervals.length;
  30200. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  30201. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  30202. // We check one more level to avoid the ticks are to sparse in some case.
  30203. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30204. };
  30205. TimeScale.prototype.parse = function (val) {
  30206. // val might be float.
  30207. return typeof val === 'number' ? val : +parseDate(val);
  30208. };
  30209. TimeScale.prototype.contain = function (val) {
  30210. return contain$1(this.parse(val), this._extent);
  30211. };
  30212. TimeScale.prototype.normalize = function (val) {
  30213. return normalize$1(this.parse(val), this._extent);
  30214. };
  30215. TimeScale.prototype.scale = function (val) {
  30216. return scale$2(val, this._extent);
  30217. };
  30218. TimeScale.type = 'time';
  30219. return TimeScale;
  30220. }(IntervalScale);
  30221. /**
  30222. * This implementation was originally copied from "d3.js"
  30223. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30224. * with some modifications made for this program.
  30225. * See the license statement at the head of this file.
  30226. */
  30227. var scaleIntervals = [// Format interval
  30228. ['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
  30229. ];
  30230. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30231. var dateA = parseDate(valueA);
  30232. var dateB = parseDate(valueB);
  30233. var isSame = function (unit) {
  30234. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30235. };
  30236. var isSameYear = function () {
  30237. return isSame('year');
  30238. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30239. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30240. var isSameMonth = function () {
  30241. return isSameYear() && isSame('month');
  30242. };
  30243. var isSameDay = function () {
  30244. return isSameMonth() && isSame('day');
  30245. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30246. var isSameHour = function () {
  30247. return isSameDay() && isSame('hour');
  30248. };
  30249. var isSameMinute = function () {
  30250. return isSameHour() && isSame('minute');
  30251. };
  30252. var isSameSecond = function () {
  30253. return isSameMinute() && isSame('second');
  30254. };
  30255. var isSameMilliSecond = function () {
  30256. return isSameSecond() && isSame('millisecond');
  30257. };
  30258. switch (unit) {
  30259. case 'year':
  30260. return isSameYear();
  30261. case 'month':
  30262. return isSameMonth();
  30263. case 'day':
  30264. return isSameDay();
  30265. case 'hour':
  30266. return isSameHour();
  30267. case 'minute':
  30268. return isSameMinute();
  30269. case 'second':
  30270. return isSameSecond();
  30271. case 'millisecond':
  30272. return isSameMilliSecond();
  30273. }
  30274. } // const primaryUnitGetters = {
  30275. // year: fullYearGetterName(),
  30276. // month: monthGetterName(),
  30277. // day: dateGetterName(),
  30278. // hour: hoursGetterName(),
  30279. // minute: minutesGetterName(),
  30280. // second: secondsGetterName(),
  30281. // millisecond: millisecondsGetterName()
  30282. // };
  30283. // const primaryUnitUTCGetters = {
  30284. // year: fullYearGetterName(true),
  30285. // month: monthGetterName(true),
  30286. // day: dateGetterName(true),
  30287. // hour: hoursGetterName(true),
  30288. // minute: minutesGetterName(true),
  30289. // second: secondsGetterName(true),
  30290. // millisecond: millisecondsGetterName(true)
  30291. // };
  30292. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30293. // step = step || 1;
  30294. // switch (getPrimaryTimeUnit(unitName)) {
  30295. // case 'year':
  30296. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30297. // break;
  30298. // case 'month':
  30299. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30300. // break;
  30301. // case 'day':
  30302. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  30303. // break;
  30304. // case 'hour':
  30305. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  30306. // break;
  30307. // case 'minute':
  30308. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  30309. // break;
  30310. // case 'second':
  30311. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  30312. // break;
  30313. // case 'millisecond':
  30314. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  30315. // break;
  30316. // }
  30317. // return date.getTime();
  30318. // }
  30319. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  30320. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  30321. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  30322. function getDateInterval(approxInterval, daysInMonth) {
  30323. approxInterval /= ONE_DAY;
  30324. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick betwen two month.
  30325. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  30326. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  30327. }
  30328. function getMonthInterval(approxInterval) {
  30329. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  30330. approxInterval /= APPROX_ONE_MONTH;
  30331. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  30332. }
  30333. function getHourInterval(approxInterval) {
  30334. approxInterval /= ONE_HOUR;
  30335. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  30336. }
  30337. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  30338. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  30339. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  30340. }
  30341. function getMillisecondsInterval(approxInterval) {
  30342. return nice(approxInterval, true);
  30343. }
  30344. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  30345. var outDate = new Date(date);
  30346. switch (getPrimaryTimeUnit(unitName)) {
  30347. case 'year':
  30348. case 'month':
  30349. outDate[monthSetterName(isUTC)](0);
  30350. case 'day':
  30351. outDate[dateSetterName(isUTC)](1);
  30352. case 'hour':
  30353. outDate[hoursSetterName(isUTC)](0);
  30354. case 'minute':
  30355. outDate[minutesSetterName(isUTC)](0);
  30356. case 'second':
  30357. outDate[secondsSetterName(isUTC)](0);
  30358. outDate[millisecondsSetterName(isUTC)](0);
  30359. }
  30360. return outDate.getTime();
  30361. }
  30362. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  30363. var safeLimit = 10000;
  30364. var unitNames = timeUnits;
  30365. var iter = 0;
  30366. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  30367. var date = new Date(minTimestamp);
  30368. var dateTime = minTimestamp;
  30369. var d = date[getMethodName](); // if (isDate) {
  30370. // d -= 1; // Starts with 0; PENDING
  30371. // }
  30372. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  30373. out.push({
  30374. value: dateTime
  30375. });
  30376. d += interval;
  30377. date[setMethodName](d);
  30378. dateTime = date.getTime();
  30379. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  30380. out.push({
  30381. value: dateTime,
  30382. notAdd: true
  30383. });
  30384. }
  30385. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  30386. var newAddedTicks = [];
  30387. var isFirstLevel = !lastLevelTicks.length;
  30388. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  30389. return;
  30390. }
  30391. if (isFirstLevel) {
  30392. lastLevelTicks = [{
  30393. // TODO Optimize. Not include so may ticks.
  30394. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  30395. }, {
  30396. value: extent[1]
  30397. }];
  30398. }
  30399. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  30400. var startTick = lastLevelTicks[i].value;
  30401. var endTick = lastLevelTicks[i + 1].value;
  30402. if (startTick === endTick) {
  30403. continue;
  30404. }
  30405. var interval = void 0;
  30406. var getterName = void 0;
  30407. var setterName = void 0;
  30408. var isDate = false;
  30409. switch (unitName) {
  30410. case 'year':
  30411. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  30412. getterName = fullYearGetterName(isUTC);
  30413. setterName = fullYearSetterName(isUTC);
  30414. break;
  30415. case 'half-year':
  30416. case 'quarter':
  30417. case 'month':
  30418. interval = getMonthInterval(approxInterval);
  30419. getterName = monthGetterName(isUTC);
  30420. setterName = monthSetterName(isUTC);
  30421. break;
  30422. case 'week': // PENDING If week is added. Ignore day.
  30423. case 'half-week':
  30424. case 'day':
  30425. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  30426. getterName = dateGetterName(isUTC);
  30427. setterName = dateSetterName(isUTC);
  30428. isDate = true;
  30429. break;
  30430. case 'half-day':
  30431. case 'quarter-day':
  30432. case 'hour':
  30433. interval = getHourInterval(approxInterval);
  30434. getterName = hoursGetterName(isUTC);
  30435. setterName = hoursSetterName(isUTC);
  30436. break;
  30437. case 'minute':
  30438. interval = getMinutesAndSecondsInterval(approxInterval, true);
  30439. getterName = minutesGetterName(isUTC);
  30440. setterName = minutesSetterName(isUTC);
  30441. break;
  30442. case 'second':
  30443. interval = getMinutesAndSecondsInterval(approxInterval, false);
  30444. getterName = secondsGetterName(isUTC);
  30445. setterName = secondsSetterName(isUTC);
  30446. break;
  30447. case 'millisecond':
  30448. interval = getMillisecondsInterval(approxInterval);
  30449. getterName = millisecondsGetterName(isUTC);
  30450. setterName = millisecondsSetterName(isUTC);
  30451. break;
  30452. }
  30453. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  30454. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  30455. // Add nearest years to the left extent.
  30456. levelTicks.unshift({
  30457. value: levelTicks[0].value - interval
  30458. });
  30459. }
  30460. }
  30461. for (var i = 0; i < newAddedTicks.length; i++) {
  30462. levelTicks.push(newAddedTicks[i]);
  30463. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  30464. return newAddedTicks;
  30465. }
  30466. var levelsTicks = [];
  30467. var currentLevelTicks = [];
  30468. var tickCount = 0;
  30469. var lastLevelTickCount = 0;
  30470. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  30471. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  30472. if (!isPrimaryTimeUnit(unitNames[i])) {
  30473. // TODO
  30474. continue;
  30475. }
  30476. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  30477. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  30478. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  30479. if (currentLevelTicks.length) {
  30480. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  30481. currentLevelTicks.sort(function (a, b) {
  30482. return a.value - b.value;
  30483. });
  30484. var levelTicksRemoveDuplicated = [];
  30485. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  30486. var tickValue = currentLevelTicks[i_1].value;
  30487. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  30488. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  30489. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  30490. tickCount++;
  30491. }
  30492. }
  30493. }
  30494. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  30495. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  30496. break;
  30497. } // Only treat primary time unit as one level.
  30498. levelsTicks.push(levelTicksRemoveDuplicated);
  30499. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  30500. break;
  30501. }
  30502. } // Reset if next unitName is primary
  30503. currentLevelTicks = [];
  30504. }
  30505. }
  30506. if ("development" !== 'production') {
  30507. if (iter >= safeLimit) {
  30508. warn('Exceed safe limit.');
  30509. }
  30510. }
  30511. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  30512. return filter(levelTicks, function (tick) {
  30513. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  30514. });
  30515. }), function (levelTicks) {
  30516. return levelTicks.length > 0;
  30517. });
  30518. var ticks = [];
  30519. var maxLevel = levelsTicksInExtent.length - 1;
  30520. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  30521. var levelTicks = levelsTicksInExtent[i];
  30522. for (var k = 0; k < levelTicks.length; ++k) {
  30523. ticks.push({
  30524. value: levelTicks[k].value,
  30525. level: maxLevel - i
  30526. });
  30527. }
  30528. }
  30529. ticks.sort(function (a, b) {
  30530. return a.value - b.value;
  30531. }); // Remove duplicates
  30532. var result = [];
  30533. for (var i = 0; i < ticks.length; ++i) {
  30534. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  30535. result.push(ticks[i]);
  30536. }
  30537. }
  30538. return result;
  30539. }
  30540. Scale.registerClass(TimeScale);
  30541. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  30542. var intervalScaleProto = IntervalScale.prototype;
  30543. var getPrecisionSafe$1 = getPrecisionSafe;
  30544. var roundingErrorFix = round;
  30545. var mathFloor$1 = Math.floor;
  30546. var mathCeil = Math.ceil;
  30547. var mathPow$1 = Math.pow;
  30548. var mathLog = Math.log;
  30549. var LogScale =
  30550. /** @class */
  30551. function (_super) {
  30552. __extends(LogScale, _super);
  30553. function LogScale() {
  30554. var _this = _super !== null && _super.apply(this, arguments) || this;
  30555. _this.type = 'log';
  30556. _this.base = 10;
  30557. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  30558. _this._interval = 0;
  30559. return _this;
  30560. }
  30561. /**
  30562. * @param Whether expand the ticks to niced extent.
  30563. */
  30564. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  30565. var originalScale = this._originalScale;
  30566. var extent = this._extent;
  30567. var originalExtent = originalScale.getExtent();
  30568. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  30569. return map(ticks, function (tick) {
  30570. var val = tick.value;
  30571. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  30572. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  30573. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  30574. return {
  30575. value: powVal
  30576. };
  30577. }, this);
  30578. };
  30579. LogScale.prototype.setExtent = function (start, end) {
  30580. var base = this.base;
  30581. start = mathLog(start) / mathLog(base);
  30582. end = mathLog(end) / mathLog(base);
  30583. intervalScaleProto.setExtent.call(this, start, end);
  30584. };
  30585. /**
  30586. * @return {number} end
  30587. */
  30588. LogScale.prototype.getExtent = function () {
  30589. var base = this.base;
  30590. var extent = scaleProto.getExtent.call(this);
  30591. extent[0] = mathPow$1(base, extent[0]);
  30592. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  30593. var originalScale = this._originalScale;
  30594. var originalExtent = originalScale.getExtent();
  30595. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30596. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30597. return extent;
  30598. };
  30599. LogScale.prototype.unionExtent = function (extent) {
  30600. this._originalScale.unionExtent(extent);
  30601. var base = this.base;
  30602. extent[0] = mathLog(extent[0]) / mathLog(base);
  30603. extent[1] = mathLog(extent[1]) / mathLog(base);
  30604. scaleProto.unionExtent.call(this, extent);
  30605. };
  30606. LogScale.prototype.unionExtentFromData = function (data, dim) {
  30607. // TODO
  30608. // filter value that <= 0
  30609. this.unionExtent(data.getApproximateExtent(dim));
  30610. };
  30611. /**
  30612. * Update interval and extent of intervals for nice ticks
  30613. * @param approxTickNum default 10 Given approx tick number
  30614. */
  30615. LogScale.prototype.niceTicks = function (approxTickNum) {
  30616. approxTickNum = approxTickNum || 10;
  30617. var extent = this._extent;
  30618. var span = extent[1] - extent[0];
  30619. if (span === Infinity || span <= 0) {
  30620. return;
  30621. }
  30622. var interval = quantity(span);
  30623. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  30624. if (err <= 0.5) {
  30625. interval *= 10;
  30626. } // Interval should be integer
  30627. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30628. interval *= 10;
  30629. }
  30630. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor$1(extent[1] / interval) * interval)];
  30631. this._interval = interval;
  30632. this._niceExtent = niceExtent;
  30633. };
  30634. LogScale.prototype.niceExtent = function (opt) {
  30635. intervalScaleProto.niceExtent.call(this, opt);
  30636. this._fixMin = opt.fixMin;
  30637. this._fixMax = opt.fixMax;
  30638. };
  30639. LogScale.prototype.parse = function (val) {
  30640. return val;
  30641. };
  30642. LogScale.prototype.contain = function (val) {
  30643. val = mathLog(val) / mathLog(this.base);
  30644. return contain$1(val, this._extent);
  30645. };
  30646. LogScale.prototype.normalize = function (val) {
  30647. val = mathLog(val) / mathLog(this.base);
  30648. return normalize$1(val, this._extent);
  30649. };
  30650. LogScale.prototype.scale = function (val) {
  30651. val = scale$2(val, this._extent);
  30652. return mathPow$1(this.base, val);
  30653. };
  30654. LogScale.type = 'log';
  30655. return LogScale;
  30656. }(Scale);
  30657. var proto = LogScale.prototype;
  30658. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  30659. proto.getLabel = intervalScaleProto.getLabel;
  30660. function fixRoundingError(val, originalVal) {
  30661. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30662. }
  30663. Scale.registerClass(LogScale);
  30664. var ScaleRawExtentInfo =
  30665. /** @class */
  30666. function () {
  30667. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  30668. originalExtent) {
  30669. this._prepareParams(scale, model, originalExtent);
  30670. }
  30671. /**
  30672. * Parameters depending on ouside (like model, user callback)
  30673. * are prepared and fixed here.
  30674. */
  30675. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  30676. dataExtent) {
  30677. if (dataExtent[1] < dataExtent[0]) {
  30678. dataExtent = [NaN, NaN];
  30679. }
  30680. this._dataMin = dataExtent[0];
  30681. this._dataMax = dataExtent[1];
  30682. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  30683. this._needCrossZero = model.getNeedCrossZero && model.getNeedCrossZero();
  30684. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  30685. if (isFunction(modelMinRaw)) {
  30686. // This callback alway provide users the full data extent (before data filtered).
  30687. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  30688. min: dataExtent[0],
  30689. max: dataExtent[1]
  30690. }));
  30691. } else if (modelMinRaw !== 'dataMin') {
  30692. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  30693. }
  30694. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  30695. if (isFunction(modelMaxRaw)) {
  30696. // This callback alway provide users the full data extent (before data filtered).
  30697. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  30698. min: dataExtent[0],
  30699. max: dataExtent[1]
  30700. }));
  30701. } else if (modelMaxRaw !== 'dataMax') {
  30702. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  30703. }
  30704. if (isOrdinal) {
  30705. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  30706. // and progressive rendering is using, here the category result might just only contain
  30707. // the processed chunk rather than the entire result.
  30708. this._axisDataLen = model.getCategories().length;
  30709. } else {
  30710. var boundaryGap = model.get('boundaryGap');
  30711. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  30712. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  30713. if ("development" !== 'production') {
  30714. 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.');
  30715. }
  30716. this._boundaryGapInner = [0, 0];
  30717. } else {
  30718. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  30719. }
  30720. }
  30721. };
  30722. /**
  30723. * Calculate extent by prepared parameters.
  30724. * This method has no external dependency and can be called duplicatedly,
  30725. * getting the same result.
  30726. * If parameters changed, should call this method to recalcuate.
  30727. */
  30728. ScaleRawExtentInfo.prototype.calculate = function () {
  30729. // Notice: When min/max is not set (that is, when there are null/undefined,
  30730. // which is the most common case), these cases should be ensured:
  30731. // (1) For 'ordinal', show all axis.data.
  30732. // (2) For others:
  30733. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30734. // disabled).
  30735. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30736. // be the result that originalExtent enlarged by boundaryGap.
  30737. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30738. var isOrdinal = this._isOrdinal;
  30739. var dataMin = this._dataMin;
  30740. var dataMax = this._dataMax;
  30741. var axisDataLen = this._axisDataLen;
  30742. var boundaryGapInner = this._boundaryGapInner;
  30743. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  30744. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  30745. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  30746. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  30747. var minFixed = min != null;
  30748. var maxFixed = max != null;
  30749. if (min == null) {
  30750. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  30751. }
  30752. if (max == null) {
  30753. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  30754. }
  30755. (min == null || !isFinite(min)) && (min = NaN);
  30756. (max == null || !isFinite(max)) && (max = NaN);
  30757. if (min > max) {
  30758. min = NaN;
  30759. max = NaN;
  30760. }
  30761. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  30762. if (this._needCrossZero) {
  30763. // Axis is over zero and min is not set
  30764. if (min > 0 && max > 0 && !minFixed) {
  30765. min = 0; // minFixed = true;
  30766. } // Axis is under zero and max is not set
  30767. if (min < 0 && max < 0 && !maxFixed) {
  30768. max = 0; // maxFixed = true;
  30769. } // PENDING:
  30770. // When `needCrossZero` and all data is positive/negative, should it be ensured
  30771. // that the results processed by boundaryGap are positive/negative?
  30772. // If so, here `minFixed`/`maxFixed` need to be set.
  30773. }
  30774. var determinedMin = this._determinedMin;
  30775. var determinedMax = this._determinedMax;
  30776. if (determinedMin != null) {
  30777. min = determinedMin;
  30778. minFixed = true;
  30779. }
  30780. if (determinedMax != null) {
  30781. max = determinedMax;
  30782. maxFixed = true;
  30783. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  30784. // `NaN` means min/max axis is blank.
  30785. return {
  30786. min: min,
  30787. max: max,
  30788. minFixed: minFixed,
  30789. maxFixed: maxFixed,
  30790. isBlank: isBlank
  30791. };
  30792. };
  30793. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  30794. if ("development" !== 'production') {
  30795. assert(!this.frozen);
  30796. }
  30797. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  30798. };
  30799. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  30800. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  30801. if ("development" !== 'production') {
  30802. assert(!this.frozen // Earse them usually means logic flaw.
  30803. && this[attr] == null);
  30804. }
  30805. this[attr] = val;
  30806. };
  30807. ScaleRawExtentInfo.prototype.freeze = function () {
  30808. // @ts-ignore
  30809. this.frozen = true;
  30810. };
  30811. return ScaleRawExtentInfo;
  30812. }();
  30813. var DETERMINED_MIN_MAX_ATTR = {
  30814. min: '_determinedMin',
  30815. max: '_determinedMax'
  30816. };
  30817. var DATA_MIN_MAX_ATTR = {
  30818. min: '_dataMin',
  30819. max: '_dataMax'
  30820. };
  30821. /**
  30822. * Get scale min max and related info only depends on model settings.
  30823. * This method can be called after coordinate system created.
  30824. * For example, in data processing stage.
  30825. *
  30826. * Scale extent info probably be required multiple times during a workflow.
  30827. * For example:
  30828. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  30829. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  30830. * (3) `coordSys.update` use it to finally decide the scale extent.
  30831. * But the callback of `min`/`max` should not be called multiple times.
  30832. * The code below should not be implemented repeatedly either.
  30833. * So we cache the result in the scale instance, which will be recreated at the begining
  30834. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  30835. */
  30836. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  30837. originalExtent) {
  30838. // Do not permit to recreate.
  30839. var rawExtentInfo = scale.rawExtentInfo;
  30840. if (rawExtentInfo) {
  30841. return rawExtentInfo;
  30842. }
  30843. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  30844. scale.rawExtentInfo = rawExtentInfo;
  30845. return rawExtentInfo;
  30846. }
  30847. function parseAxisModelMinMax(scale, minMax) {
  30848. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  30849. }
  30850. /**
  30851. * Get axis scale extent before niced.
  30852. * Item of returned array can only be number (including Infinity and NaN).
  30853. *
  30854. * Caution:
  30855. * Precondition of calling this method:
  30856. * The scale extent has been initialized using series data extent via
  30857. * `scale.setExtent` or `scale.unionExtentFromData`;
  30858. */
  30859. function getScaleExtent(scale, model) {
  30860. var scaleType = scale.type;
  30861. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  30862. scale.setBlank(rawExtentResult.isBlank);
  30863. var min = rawExtentResult.min;
  30864. 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
  30865. // is base axis
  30866. // FIXME
  30867. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30868. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30869. // Should not depend on series type `bar`?
  30870. // (3) Fix that might overlap when using dataZoom.
  30871. // (4) Consider other chart types using `barGrid`?
  30872. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30873. var ecModel = model.ecModel;
  30874. if (ecModel && scaleType === 'time'
  30875. /*|| scaleType === 'interval' */
  30876. ) {
  30877. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30878. var isBaseAxisAndHasBarSeries_1 = false;
  30879. each(barSeriesModels, function (seriesModel) {
  30880. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  30881. });
  30882. if (isBaseAxisAndHasBarSeries_1) {
  30883. // Calculate placement of bars on axis. TODO should be decoupled
  30884. // with barLayout
  30885. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  30886. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30887. min = adjustedScale.min;
  30888. max = adjustedScale.max;
  30889. }
  30890. }
  30891. return {
  30892. extent: [min, max],
  30893. // "fix" means "fixed", the value should not be
  30894. // changed in the subsequent steps.
  30895. fixMin: rawExtentResult.minFixed,
  30896. fixMax: rawExtentResult.maxFixed
  30897. };
  30898. }
  30899. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  30900. barWidthAndOffset) {
  30901. // Get Axis Length
  30902. var axisExtent = model.axis.getExtent();
  30903. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  30904. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30905. if (barsOnCurrentAxis === undefined) {
  30906. return {
  30907. min: min,
  30908. max: max
  30909. };
  30910. }
  30911. var minOverflow = Infinity;
  30912. each(barsOnCurrentAxis, function (item) {
  30913. minOverflow = Math.min(item.offset, minOverflow);
  30914. });
  30915. var maxOverflow = -Infinity;
  30916. each(barsOnCurrentAxis, function (item) {
  30917. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30918. });
  30919. minOverflow = Math.abs(minOverflow);
  30920. maxOverflow = Math.abs(maxOverflow);
  30921. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  30922. var oldRange = max - min;
  30923. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  30924. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  30925. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30926. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30927. return {
  30928. min: min,
  30929. max: max
  30930. };
  30931. } // Precondition of calling this method:
  30932. // The scale extent has been initailized using series data extent via
  30933. // `scale.setExtent` or `scale.unionExtentFromData`;
  30934. function niceScaleExtent(scale, model) {
  30935. var extentInfo = getScaleExtent(scale, model);
  30936. var extent = extentInfo.extent;
  30937. var splitNumber = model.get('splitNumber');
  30938. if (scale instanceof LogScale) {
  30939. scale.base = model.get('logBase');
  30940. }
  30941. var scaleType = scale.type;
  30942. scale.setExtent(extent[0], extent[1]);
  30943. scale.niceExtent({
  30944. splitNumber: splitNumber,
  30945. fixMin: extentInfo.fixMin,
  30946. fixMax: extentInfo.fixMax,
  30947. minInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('minInterval') : null,
  30948. maxInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('maxInterval') : null
  30949. }); // If some one specified the min, max. And the default calculated interval
  30950. // is not good enough. He can specify the interval. It is often appeared
  30951. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30952. // to be 60.
  30953. // FIXME
  30954. var interval = model.get('interval');
  30955. if (interval != null) {
  30956. scale.setInterval && scale.setInterval(interval);
  30957. }
  30958. }
  30959. /**
  30960. * @param axisType Default retrieve from model.type
  30961. */
  30962. function createScaleByModel(model, axisType) {
  30963. axisType = axisType || model.get('type');
  30964. if (axisType) {
  30965. switch (axisType) {
  30966. // Buildin scale
  30967. case 'category':
  30968. return new OrdinalScale({
  30969. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  30970. extent: [Infinity, -Infinity]
  30971. });
  30972. case 'time':
  30973. return new TimeScale({
  30974. locale: model.ecModel.getLocaleModel(),
  30975. useUTC: model.ecModel.get('useUTC')
  30976. });
  30977. default:
  30978. // case 'value'/'interval', 'log', or others.
  30979. return new (Scale.getClass(axisType) || IntervalScale)();
  30980. }
  30981. }
  30982. }
  30983. /**
  30984. * Check if the axis cross 0
  30985. */
  30986. function ifAxisCrossZero(axis) {
  30987. var dataExtent = axis.scale.getExtent();
  30988. var min = dataExtent[0];
  30989. var max = dataExtent[1];
  30990. return !(min > 0 && max > 0 || min < 0 && max < 0);
  30991. }
  30992. /**
  30993. * @param axis
  30994. * @return Label formatter function.
  30995. * param: {number} tickValue,
  30996. * param: {number} idx, the index in all ticks.
  30997. * If category axis, this param is not required.
  30998. * return: {string} label string.
  30999. */
  31000. function makeLabelFormatter(axis) {
  31001. var labelFormatter = axis.getLabelModel().get('formatter');
  31002. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31003. if (axis.scale.type === 'time') {
  31004. return function (tpl) {
  31005. return function (tick, idx) {
  31006. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31007. };
  31008. }(labelFormatter);
  31009. } else if (typeof labelFormatter === 'string') {
  31010. return function (tpl) {
  31011. return function (tick) {
  31012. // For category axis, get raw value; for numeric axis,
  31013. // get formatted label like '1,333,444'.
  31014. var label = axis.scale.getLabel(tick);
  31015. var text = tpl.replace('{value}', label != null ? label : '');
  31016. return text;
  31017. };
  31018. }(labelFormatter);
  31019. } else if (typeof labelFormatter === 'function') {
  31020. return function (cb) {
  31021. return function (tick, idx) {
  31022. // The original intention of `idx` is "the index of the tick in all ticks".
  31023. // But the previous implementation of category axis do not consider the
  31024. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31025. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31026. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31027. // the definition here for back compatibility.
  31028. if (categoryTickStart != null) {
  31029. idx = tick.value - categoryTickStart;
  31030. }
  31031. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31032. level: tick.level
  31033. } : null);
  31034. };
  31035. }(labelFormatter);
  31036. } else {
  31037. return function (tick) {
  31038. return axis.scale.getLabel(tick);
  31039. };
  31040. }
  31041. }
  31042. function getAxisRawValue(axis, tick) {
  31043. // In category axis with data zoom, tick is not the original
  31044. // index of axis.data. So tick should not be exposed to user
  31045. // in category axis.
  31046. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31047. }
  31048. /**
  31049. * @param axis
  31050. * @return Be null/undefined if no labels.
  31051. */
  31052. function estimateLabelUnionRect(axis) {
  31053. var axisModel = axis.model;
  31054. var scale = axis.scale;
  31055. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31056. return;
  31057. }
  31058. var realNumberScaleTicks;
  31059. var tickCount;
  31060. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  31061. if (scale instanceof OrdinalScale) {
  31062. tickCount = scale.count();
  31063. } else {
  31064. realNumberScaleTicks = scale.getTicks();
  31065. tickCount = realNumberScaleTicks.length;
  31066. }
  31067. var axisLabelModel = axis.getLabelModel();
  31068. var labelFormatter = makeLabelFormatter(axis);
  31069. var rect;
  31070. var step = 1; // Simple optimization for large amount of labels
  31071. if (tickCount > 40) {
  31072. step = Math.ceil(tickCount / 40);
  31073. }
  31074. for (var i = 0; i < tickCount; i += step) {
  31075. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31076. value: categoryScaleExtent[0] + i
  31077. };
  31078. var label = labelFormatter(tick, i);
  31079. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31080. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31081. rect ? rect.union(singleRect) : rect = singleRect;
  31082. }
  31083. return rect;
  31084. }
  31085. function rotateTextRect(textRect, rotate) {
  31086. var rotateRadians = rotate * Math.PI / 180;
  31087. var beforeWidth = textRect.width;
  31088. var beforeHeight = textRect.height;
  31089. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31090. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31091. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31092. return rotatedRect;
  31093. }
  31094. /**
  31095. * @param model axisLabelModel or axisTickModel
  31096. * @return {number|String} Can be null|'auto'|number|function
  31097. */
  31098. function getOptionCategoryInterval(model) {
  31099. var interval = model.get('interval');
  31100. return interval == null ? 'auto' : interval;
  31101. }
  31102. /**
  31103. * Set `categoryInterval` as 0 implicitly indicates that
  31104. * show all labels reguardless of overlap.
  31105. * @param {Object} axis axisModel.axis
  31106. */
  31107. function shouldShowAllLabels(axis) {
  31108. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31109. }
  31110. function getDataDimensionsOnAxis(data, axisDim) {
  31111. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31112. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31113. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31114. // there has been stacked result dim?
  31115. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31116. // For example, the extent of the original dimension
  31117. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31118. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31119. // because there is no graphic corresponding to [0.1, 0.5].
  31120. // See the case in `test/area-stack.html` `main1`, where area line
  31121. // stack needs `yAxis` not start from 0.
  31122. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31123. });
  31124. return keys(dataDimMap);
  31125. }
  31126. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  31127. if (data) {
  31128. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  31129. var seriesExtent = data.getApproximateExtent(dim);
  31130. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  31131. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  31132. });
  31133. }
  31134. }
  31135. /*
  31136. * Licensed to the Apache Software Foundation (ASF) under one
  31137. * or more contributor license agreements. See the NOTICE file
  31138. * distributed with this work for additional information
  31139. * regarding copyright ownership. The ASF licenses this file
  31140. * to you under the Apache License, Version 2.0 (the
  31141. * "License"); you may not use this file except in compliance
  31142. * with the License. You may obtain a copy of the License at
  31143. *
  31144. * http://www.apache.org/licenses/LICENSE-2.0
  31145. *
  31146. * Unless required by applicable law or agreed to in writing,
  31147. * software distributed under the License is distributed on an
  31148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31149. * KIND, either express or implied. See the License for the
  31150. * specific language governing permissions and limitations
  31151. * under the License.
  31152. */
  31153. /**
  31154. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31155. */
  31156. /*
  31157. * Licensed to the Apache Software Foundation (ASF) under one
  31158. * or more contributor license agreements. See the NOTICE file
  31159. * distributed with this work for additional information
  31160. * regarding copyright ownership. The ASF licenses this file
  31161. * to you under the Apache License, Version 2.0 (the
  31162. * "License"); you may not use this file except in compliance
  31163. * with the License. You may obtain a copy of the License at
  31164. *
  31165. * http://www.apache.org/licenses/LICENSE-2.0
  31166. *
  31167. * Unless required by applicable law or agreed to in writing,
  31168. * software distributed under the License is distributed on an
  31169. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31170. * KIND, either express or implied. See the License for the
  31171. * specific language governing permissions and limitations
  31172. * under the License.
  31173. */
  31174. var AxisModelCommonMixin =
  31175. /** @class */
  31176. function () {
  31177. function AxisModelCommonMixin() {}
  31178. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31179. var option = this.option;
  31180. return !option.scale;
  31181. };
  31182. /**
  31183. * Should be implemented by each axis model if necessary.
  31184. * @return coordinate system model
  31185. */
  31186. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31187. return;
  31188. };
  31189. return AxisModelCommonMixin;
  31190. }();
  31191. /**
  31192. * Create a muti dimension List structure from seriesModel.
  31193. */
  31194. function createList(seriesModel) {
  31195. return createListFromArray(seriesModel.getSource(), seriesModel);
  31196. } // export function createGraph(seriesModel) {
  31197. var dataStack$1 = {
  31198. isDimensionStacked: isDimensionStacked,
  31199. enableDataStack: enableDataStack,
  31200. getStackedDimension: getStackedDimension
  31201. };
  31202. /**
  31203. * Create scale
  31204. * @param {Array.<number>} dataExtent
  31205. * @param {Object|module:echarts/Model} option If `optoin.type`
  31206. * is secified, it can only be `'value'` currently.
  31207. */
  31208. function createScale(dataExtent, option) {
  31209. var axisModel = option;
  31210. if (!(option instanceof Model)) {
  31211. axisModel = new Model(option); // FIXME
  31212. // Currently AxisModelCommonMixin has nothing to do with the
  31213. // the requirements of `axisHelper.createScaleByModel`. For
  31214. // example the method `getCategories` and `getOrdinalMeta`
  31215. // are required for `'category'` axis, and ecModel are required
  31216. // for `'time'` axis. But occationally echarts-gl happened
  31217. // to only use `'value'` axis.
  31218. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31219. }
  31220. var scale = createScaleByModel(axisModel);
  31221. scale.setExtent(dataExtent[0], dataExtent[1]);
  31222. niceScaleExtent(scale, axisModel);
  31223. return scale;
  31224. }
  31225. /**
  31226. * Mixin common methods to axis model,
  31227. *
  31228. * Inlcude methods
  31229. * `getFormattedLabels() => Array.<string>`
  31230. * `getCategories() => Array.<string>`
  31231. * `getMin(origin: boolean) => number`
  31232. * `getMax(origin: boolean) => number`
  31233. * `getNeedCrossZero() => boolean`
  31234. */
  31235. function mixinAxisModelCommonMethods(Model) {
  31236. mixin(Model, AxisModelCommonMixin);
  31237. }
  31238. function createTextStyle$1(textStyleModel, opts) {
  31239. opts = opts || {};
  31240. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31241. }
  31242. var helper = /*#__PURE__*/Object.freeze({
  31243. __proto__: null,
  31244. createList: createList,
  31245. getLayoutRect: getLayoutRect,
  31246. dataStack: dataStack$1,
  31247. createScale: createScale,
  31248. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31249. getECData: getECData,
  31250. createTextStyle: createTextStyle$1,
  31251. createDimensions: createDimensions,
  31252. createSymbol: createSymbol,
  31253. enableHoverEmphasis: enableHoverEmphasis
  31254. });
  31255. var EPSILON$3 = 1e-8;
  31256. function isAroundEqual$1(a, b) {
  31257. return Math.abs(a - b) < EPSILON$3;
  31258. }
  31259. function contain$2(points, x, y) {
  31260. var w = 0;
  31261. var p = points[0];
  31262. if (!p) {
  31263. return false;
  31264. }
  31265. for (var i = 1; i < points.length; i++) {
  31266. var p2 = points[i];
  31267. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31268. p = p2;
  31269. }
  31270. var p0 = points[0];
  31271. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31272. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31273. }
  31274. return w !== 0;
  31275. }
  31276. var Region =
  31277. /** @class */
  31278. function () {
  31279. function Region(name, geometries, cp) {
  31280. this.name = name;
  31281. this.geometries = geometries;
  31282. if (!cp) {
  31283. var rect = this.getBoundingRect();
  31284. cp = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31285. } else {
  31286. cp = [cp[0], cp[1]];
  31287. }
  31288. this.center = cp;
  31289. }
  31290. Region.prototype.getBoundingRect = function () {
  31291. var rect = this._rect;
  31292. if (rect) {
  31293. return rect;
  31294. }
  31295. var MAX_NUMBER = Number.MAX_VALUE;
  31296. var min$1 = [MAX_NUMBER, MAX_NUMBER];
  31297. var max$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31298. var min2 = [];
  31299. var max2 = [];
  31300. var geometries = this.geometries;
  31301. var i = 0;
  31302. for (; i < geometries.length; i++) {
  31303. // Only support polygon
  31304. if (geometries[i].type !== 'polygon') {
  31305. continue;
  31306. } // Doesn't consider hole
  31307. var exterior = geometries[i].exterior;
  31308. fromPoints(exterior, min2, max2);
  31309. min(min$1, min$1, min2);
  31310. max(max$1, max$1, max2);
  31311. } // No data
  31312. if (i === 0) {
  31313. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  31314. }
  31315. return this._rect = new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  31316. };
  31317. Region.prototype.contain = function (coord) {
  31318. var rect = this.getBoundingRect();
  31319. var geometries = this.geometries;
  31320. if (!rect.contain(coord[0], coord[1])) {
  31321. return false;
  31322. }
  31323. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  31324. // Only support polygon.
  31325. if (geometries[i].type !== 'polygon') {
  31326. continue;
  31327. }
  31328. var exterior = geometries[i].exterior;
  31329. var interiors = geometries[i].interiors;
  31330. if (contain$2(exterior, coord[0], coord[1])) {
  31331. // Not in the region if point is in the hole.
  31332. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31333. if (contain$2(interiors[k], coord[0], coord[1])) {
  31334. continue loopGeo;
  31335. }
  31336. }
  31337. return true;
  31338. }
  31339. }
  31340. return false;
  31341. };
  31342. Region.prototype.transformTo = function (x, y, width, height) {
  31343. var rect = this.getBoundingRect();
  31344. var aspect = rect.width / rect.height;
  31345. if (!width) {
  31346. width = aspect * height;
  31347. } else if (!height) {
  31348. height = width / aspect;
  31349. }
  31350. var target = new BoundingRect(x, y, width, height);
  31351. var transform = rect.calculateTransform(target);
  31352. var geometries = this.geometries;
  31353. for (var i = 0; i < geometries.length; i++) {
  31354. // Only support polygon.
  31355. if (geometries[i].type !== 'polygon') {
  31356. continue;
  31357. }
  31358. var exterior = geometries[i].exterior;
  31359. var interiors = geometries[i].interiors;
  31360. for (var p = 0; p < exterior.length; p++) {
  31361. applyTransform(exterior[p], exterior[p], transform);
  31362. }
  31363. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31364. for (var p = 0; p < interiors[h].length; p++) {
  31365. applyTransform(interiors[h][p], interiors[h][p], transform);
  31366. }
  31367. }
  31368. }
  31369. rect = this._rect;
  31370. rect.copy(target); // Update center
  31371. this.center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31372. };
  31373. Region.prototype.cloneShallow = function (name) {
  31374. name == null && (name = this.name);
  31375. var newRegion = new Region(name, this.geometries, this.center);
  31376. newRegion._rect = this._rect;
  31377. newRegion.transformTo = null; // Simply avoid to be called.
  31378. return newRegion;
  31379. };
  31380. return Region;
  31381. }();
  31382. function decode(json) {
  31383. if (!json.UTF8Encoding) {
  31384. return json;
  31385. }
  31386. var jsonCompressed = json;
  31387. var encodeScale = jsonCompressed.UTF8Scale;
  31388. if (encodeScale == null) {
  31389. encodeScale = 1024;
  31390. }
  31391. var features = jsonCompressed.features;
  31392. for (var f = 0; f < features.length; f++) {
  31393. var feature = features[f];
  31394. var geometry = feature.geometry;
  31395. if (geometry.type === 'Polygon') {
  31396. var coordinates = geometry.coordinates;
  31397. for (var c = 0; c < coordinates.length; c++) {
  31398. coordinates[c] = decodePolygon(coordinates[c], geometry.encodeOffsets[c], encodeScale);
  31399. }
  31400. } else if (geometry.type === 'MultiPolygon') {
  31401. var coordinates = geometry.coordinates;
  31402. for (var c = 0; c < coordinates.length; c++) {
  31403. var coordinate = coordinates[c];
  31404. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31405. coordinate[c2] = decodePolygon(coordinate[c2], geometry.encodeOffsets[c][c2], encodeScale);
  31406. }
  31407. }
  31408. }
  31409. } // Has been decoded
  31410. jsonCompressed.UTF8Encoding = false;
  31411. return jsonCompressed;
  31412. }
  31413. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31414. var result = [];
  31415. var prevX = encodeOffsets[0];
  31416. var prevY = encodeOffsets[1];
  31417. for (var i = 0; i < coordinate.length; i += 2) {
  31418. var x = coordinate.charCodeAt(i) - 64;
  31419. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  31420. x = x >> 1 ^ -(x & 1);
  31421. y = y >> 1 ^ -(y & 1); // Delta deocding
  31422. x += prevX;
  31423. y += prevY;
  31424. prevX = x;
  31425. prevY = y; // Dequantize
  31426. result.push([x / encodeScale, y / encodeScale]);
  31427. }
  31428. return result;
  31429. }
  31430. function parseGeoJSON(geoJson, nameProperty) {
  31431. geoJson = decode(geoJson);
  31432. return map(filter(geoJson.features, function (featureObj) {
  31433. // Output of mapshaper may have geometry null
  31434. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  31435. }), function (featureObj) {
  31436. var properties = featureObj.properties;
  31437. var geo = featureObj.geometry;
  31438. var geometries = [];
  31439. if (geo.type === 'Polygon') {
  31440. var coordinates = geo.coordinates;
  31441. geometries.push({
  31442. type: 'polygon',
  31443. // According to the GeoJSON specification.
  31444. // First must be exterior, and the rest are all interior(holes).
  31445. exterior: coordinates[0],
  31446. interiors: coordinates.slice(1)
  31447. });
  31448. }
  31449. if (geo.type === 'MultiPolygon') {
  31450. var coordinates = geo.coordinates;
  31451. each(coordinates, function (item) {
  31452. if (item[0]) {
  31453. geometries.push({
  31454. type: 'polygon',
  31455. exterior: item[0],
  31456. interiors: item.slice(1)
  31457. });
  31458. }
  31459. });
  31460. }
  31461. var region = new Region(properties[nameProperty || 'name'], geometries, properties.cp);
  31462. region.properties = properties;
  31463. return region;
  31464. });
  31465. }
  31466. var number = /*#__PURE__*/Object.freeze({
  31467. __proto__: null,
  31468. linearMap: linearMap,
  31469. round: round,
  31470. asc: asc,
  31471. getPrecision: getPrecision,
  31472. getPrecisionSafe: getPrecisionSafe,
  31473. getPixelPrecision: getPixelPrecision,
  31474. getPercentWithPrecision: getPercentWithPrecision,
  31475. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  31476. remRadian: remRadian,
  31477. isRadianAroundZero: isRadianAroundZero,
  31478. parseDate: parseDate,
  31479. quantity: quantity,
  31480. quantityExponent: quantityExponent,
  31481. nice: nice,
  31482. quantile: quantile,
  31483. reformIntervals: reformIntervals,
  31484. isNumeric: isNumeric,
  31485. numericToNumber: numericToNumber
  31486. });
  31487. var time = /*#__PURE__*/Object.freeze({
  31488. __proto__: null,
  31489. parse: parseDate,
  31490. format: format
  31491. });
  31492. var graphic$1 = /*#__PURE__*/Object.freeze({
  31493. __proto__: null,
  31494. extendShape: extendShape,
  31495. extendPath: extendPath,
  31496. makePath: makePath,
  31497. makeImage: makeImage,
  31498. mergePath: mergePath$1,
  31499. resizePath: resizePath,
  31500. createIcon: createIcon,
  31501. updateProps: updateProps,
  31502. initProps: initProps,
  31503. getTransform: getTransform,
  31504. clipPointsByRect: clipPointsByRect,
  31505. clipRectByRect: clipRectByRect,
  31506. registerShape: registerShape,
  31507. getShapeClass: getShapeClass,
  31508. Group: Group,
  31509. Image: ZRImage,
  31510. Text: ZRText,
  31511. Circle: Circle,
  31512. Ellipse: Ellipse,
  31513. Sector: Sector,
  31514. Ring: Ring,
  31515. Polygon: Polygon,
  31516. Polyline: Polyline,
  31517. Rect: Rect,
  31518. Line: Line,
  31519. BezierCurve: BezierCurve,
  31520. Arc: Arc,
  31521. IncrementalDisplayable: IncrementalDisplayable,
  31522. CompoundPath: CompoundPath,
  31523. LinearGradient: LinearGradient,
  31524. RadialGradient: RadialGradient,
  31525. BoundingRect: BoundingRect
  31526. });
  31527. var format$1 = /*#__PURE__*/Object.freeze({
  31528. __proto__: null,
  31529. addCommas: addCommas,
  31530. toCamelCase: toCamelCase,
  31531. normalizeCssArray: normalizeCssArray$1,
  31532. encodeHTML: encodeHTML,
  31533. formatTpl: formatTpl,
  31534. getTooltipMarker: getTooltipMarker,
  31535. formatTime: formatTime,
  31536. capitalFirst: capitalFirst,
  31537. truncateText: truncateText,
  31538. getTextRect: getTextRect
  31539. });
  31540. var util$1 = /*#__PURE__*/Object.freeze({
  31541. __proto__: null,
  31542. map: map,
  31543. each: each,
  31544. indexOf: indexOf,
  31545. inherits: inherits,
  31546. reduce: reduce,
  31547. filter: filter,
  31548. bind: bind,
  31549. curry: curry,
  31550. isArray: isArray,
  31551. isString: isString,
  31552. isObject: isObject,
  31553. isFunction: isFunction,
  31554. extend: extend,
  31555. defaults: defaults,
  31556. clone: clone,
  31557. merge: merge
  31558. });
  31559. var inner$4 = makeInner();
  31560. function createAxisLabels(axis) {
  31561. // Only ordinal scale support tick interval
  31562. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  31563. }
  31564. /**
  31565. * @param {module:echats/coord/Axis} axis
  31566. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31567. * @return {Object} {
  31568. * ticks: Array.<number>
  31569. * tickCategoryInterval: number
  31570. * }
  31571. */
  31572. function createAxisTicks(axis, tickModel) {
  31573. // Only ordinal scale support tick interval
  31574. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  31575. ticks: map(axis.scale.getTicks(), function (tick) {
  31576. return tick.value;
  31577. })
  31578. };
  31579. }
  31580. function makeCategoryLabels(axis) {
  31581. var labelModel = axis.getLabelModel();
  31582. var result = makeCategoryLabelsActually(axis, labelModel);
  31583. return !labelModel.get('show') || axis.scale.isBlank() ? {
  31584. labels: [],
  31585. labelCategoryInterval: result.labelCategoryInterval
  31586. } : result;
  31587. }
  31588. function makeCategoryLabelsActually(axis, labelModel) {
  31589. var labelsCache = getListCache(axis, 'labels');
  31590. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31591. var result = listCacheGet(labelsCache, optionLabelInterval);
  31592. if (result) {
  31593. return result;
  31594. }
  31595. var labels;
  31596. var numericLabelInterval;
  31597. if (isFunction(optionLabelInterval)) {
  31598. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31599. } else {
  31600. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31601. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31602. } // Cache to avoid calling interval function repeatly.
  31603. return listCacheSet(labelsCache, optionLabelInterval, {
  31604. labels: labels,
  31605. labelCategoryInterval: numericLabelInterval
  31606. });
  31607. }
  31608. function makeCategoryTicks(axis, tickModel) {
  31609. var ticksCache = getListCache(axis, 'ticks');
  31610. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31611. var result = listCacheGet(ticksCache, optionTickInterval);
  31612. if (result) {
  31613. return result;
  31614. }
  31615. var ticks;
  31616. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  31617. // we should not return all ticks.
  31618. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31619. ticks = [];
  31620. }
  31621. if (isFunction(optionTickInterval)) {
  31622. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31623. } // Always use label interval by default despite label show. Consider this
  31624. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31625. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31626. else if (optionTickInterval === 'auto') {
  31627. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31628. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31629. ticks = map(labelsResult.labels, function (labelItem) {
  31630. return labelItem.tickValue;
  31631. });
  31632. } else {
  31633. tickCategoryInterval = optionTickInterval;
  31634. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31635. } // Cache to avoid calling interval function repeatly.
  31636. return listCacheSet(ticksCache, optionTickInterval, {
  31637. ticks: ticks,
  31638. tickCategoryInterval: tickCategoryInterval
  31639. });
  31640. }
  31641. function makeRealNumberLabels(axis) {
  31642. var ticks = axis.scale.getTicks();
  31643. var labelFormatter = makeLabelFormatter(axis);
  31644. return {
  31645. labels: map(ticks, function (tick, idx) {
  31646. return {
  31647. formattedLabel: labelFormatter(tick, idx),
  31648. rawLabel: axis.scale.getLabel(tick),
  31649. tickValue: tick.value
  31650. };
  31651. })
  31652. };
  31653. }
  31654. function getListCache(axis, prop) {
  31655. // Because key can be funciton, and cache size always be small, we use array cache.
  31656. return inner$4(axis)[prop] || (inner$4(axis)[prop] = []);
  31657. }
  31658. function listCacheGet(cache, key) {
  31659. for (var i = 0; i < cache.length; i++) {
  31660. if (cache[i].key === key) {
  31661. return cache[i].value;
  31662. }
  31663. }
  31664. }
  31665. function listCacheSet(cache, key, value) {
  31666. cache.push({
  31667. key: key,
  31668. value: value
  31669. });
  31670. return value;
  31671. }
  31672. function makeAutoCategoryInterval(axis) {
  31673. var result = inner$4(axis).autoInterval;
  31674. return result != null ? result : inner$4(axis).autoInterval = axis.calculateCategoryInterval();
  31675. }
  31676. /**
  31677. * Calculate interval for category axis ticks and labels.
  31678. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31679. * should be implemented in axis.
  31680. */
  31681. function calculateCategoryInterval(axis) {
  31682. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31683. var labelFormatter = makeLabelFormatter(axis);
  31684. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31685. var ordinalScale = axis.scale;
  31686. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  31687. // avoid generating a long array by `getTicks`
  31688. // in large category data case.
  31689. var tickCount = ordinalScale.count();
  31690. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31691. return 0;
  31692. }
  31693. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  31694. if (tickCount > 40) {
  31695. step = Math.max(1, Math.floor(tickCount / 40));
  31696. }
  31697. var tickValue = ordinalExtent[0];
  31698. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31699. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31700. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31701. var maxW = 0;
  31702. var maxH = 0; // Caution: Performance sensitive for large category data.
  31703. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31704. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31705. var width = 0;
  31706. var height = 0; // Not precise, do not consider align and vertical align
  31707. // and each distance from axis line yet.
  31708. var rect = getBoundingRect(labelFormatter({
  31709. value: tickValue
  31710. }), params.font, 'center', 'top'); // Magic number
  31711. width = rect.width * 1.3;
  31712. height = rect.height * 1.3; // Min size, void long loop.
  31713. maxW = Math.max(maxW, width, 7);
  31714. maxH = Math.max(maxH, height, 7);
  31715. }
  31716. var dw = maxW / unitW;
  31717. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  31718. isNaN(dw) && (dw = Infinity);
  31719. isNaN(dh) && (dh = Infinity);
  31720. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31721. var cache = inner$4(axis.model);
  31722. var axisExtent = axis.getExtent();
  31723. var lastAutoInterval = cache.lastAutoInterval;
  31724. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  31725. // otherwise the calculated interval might jitter when the zoom
  31726. // window size is close to the interval-changing size.
  31727. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  31728. // The jitter will cause that sometimes the displayed labels are
  31729. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  31730. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  31731. // point is not the same when zooming in or zooming out.
  31732. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  31733. // be used. Otherwise some hiden labels might not be shown again.
  31734. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  31735. interval = lastAutoInterval;
  31736. } // Only update cache if cache not used, otherwise the
  31737. // changing of interval is too insensitive.
  31738. else {
  31739. cache.lastTickCount = tickCount;
  31740. cache.lastAutoInterval = interval;
  31741. cache.axisExtent0 = axisExtent[0];
  31742. cache.axisExtent1 = axisExtent[1];
  31743. }
  31744. return interval;
  31745. }
  31746. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31747. var labelModel = axis.getLabelModel();
  31748. return {
  31749. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  31750. labelRotate: labelModel.get('rotate') || 0,
  31751. font: labelModel.getFont()
  31752. };
  31753. }
  31754. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31755. var labelFormatter = makeLabelFormatter(axis);
  31756. var ordinalScale = axis.scale;
  31757. var ordinalExtent = ordinalScale.getExtent();
  31758. var labelModel = axis.getLabelModel();
  31759. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  31760. var step = Math.max((categoryInterval || 0) + 1, 1);
  31761. var startTick = ordinalExtent[0];
  31762. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  31763. // while zooming and moving while interval > 0. Otherwise the selection
  31764. // of displayable ticks and symbols probably keep changing.
  31765. // 3 is empirical value.
  31766. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  31767. startTick = Math.round(Math.ceil(startTick / step) * step);
  31768. } // (1) Only add min max label here but leave overlap checking
  31769. // to render stage, which also ensure the returned list
  31770. // suitable for splitLine and splitArea rendering.
  31771. // (2) Scales except category always contain min max label so
  31772. // do not need to perform this process.
  31773. var showAllLabel = shouldShowAllLabels(axis);
  31774. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  31775. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31776. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31777. addItem(ordinalExtent[0]);
  31778. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  31779. var tickValue = startTick;
  31780. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31781. addItem(tickValue);
  31782. }
  31783. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  31784. addItem(ordinalExtent[1]);
  31785. }
  31786. function addItem(tickValue) {
  31787. var tickObj = {
  31788. value: tickValue
  31789. };
  31790. result.push(onlyTick ? tickValue : {
  31791. formattedLabel: labelFormatter(tickObj),
  31792. rawLabel: ordinalScale.getLabel(tickObj),
  31793. tickValue: tickValue
  31794. });
  31795. }
  31796. return result;
  31797. }
  31798. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  31799. var ordinalScale = axis.scale;
  31800. var labelFormatter = makeLabelFormatter(axis);
  31801. var result = [];
  31802. each(ordinalScale.getTicks(), function (tick) {
  31803. var rawLabel = ordinalScale.getLabel(tick);
  31804. var tickValue = tick.value;
  31805. if (categoryInterval(tick.value, rawLabel)) {
  31806. result.push(onlyTick ? tickValue : {
  31807. formattedLabel: labelFormatter(tick),
  31808. rawLabel: rawLabel,
  31809. tickValue: tickValue
  31810. });
  31811. }
  31812. });
  31813. return result;
  31814. }
  31815. var NORMALIZED_EXTENT = [0, 1];
  31816. /**
  31817. * Base class of Axis.
  31818. */
  31819. var Axis =
  31820. /** @class */
  31821. function () {
  31822. function Axis(dim, scale, extent) {
  31823. this.onBand = false;
  31824. this.inverse = false;
  31825. this.dim = dim;
  31826. this.scale = scale;
  31827. this._extent = extent || [0, 0];
  31828. }
  31829. /**
  31830. * If axis extent contain given coord
  31831. */
  31832. Axis.prototype.contain = function (coord) {
  31833. var extent = this._extent;
  31834. var min = Math.min(extent[0], extent[1]);
  31835. var max = Math.max(extent[0], extent[1]);
  31836. return coord >= min && coord <= max;
  31837. };
  31838. /**
  31839. * If axis extent contain given data
  31840. */
  31841. Axis.prototype.containData = function (data) {
  31842. return this.scale.contain(data);
  31843. };
  31844. /**
  31845. * Get coord extent.
  31846. */
  31847. Axis.prototype.getExtent = function () {
  31848. return this._extent.slice();
  31849. };
  31850. /**
  31851. * Get precision used for formatting
  31852. */
  31853. Axis.prototype.getPixelPrecision = function (dataExtent) {
  31854. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  31855. };
  31856. /**
  31857. * Set coord extent
  31858. */
  31859. Axis.prototype.setExtent = function (start, end) {
  31860. var extent = this._extent;
  31861. extent[0] = start;
  31862. extent[1] = end;
  31863. };
  31864. /**
  31865. * Convert data to coord. Data is the rank if it has an ordinal scale
  31866. */
  31867. Axis.prototype.dataToCoord = function (data, clamp) {
  31868. var extent = this._extent;
  31869. var scale = this.scale;
  31870. data = scale.normalize(data);
  31871. if (this.onBand && scale.type === 'ordinal') {
  31872. extent = extent.slice();
  31873. fixExtentWithBands(extent, scale.count());
  31874. }
  31875. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  31876. };
  31877. /**
  31878. * Convert coord to data. Data is the rank if it has an ordinal scale
  31879. */
  31880. Axis.prototype.coordToData = function (coord, clamp) {
  31881. var extent = this._extent;
  31882. var scale = this.scale;
  31883. if (this.onBand && scale.type === 'ordinal') {
  31884. extent = extent.slice();
  31885. fixExtentWithBands(extent, scale.count());
  31886. }
  31887. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  31888. return this.scale.scale(t);
  31889. };
  31890. /**
  31891. * Convert pixel point to data in axis
  31892. */
  31893. Axis.prototype.pointToData = function (point, clamp) {
  31894. // Should be implemented in derived class if necessary.
  31895. return;
  31896. };
  31897. /**
  31898. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  31899. * `axis.getTicksCoords` considers `onBand`, which is used by
  31900. * `boundaryGap:true` of category axis and splitLine and splitArea.
  31901. * @param opt.tickModel default: axis.model.getModel('axisTick')
  31902. * @param opt.clamp If `true`, the first and the last
  31903. * tick must be at the axis end points. Otherwise, clip ticks
  31904. * that outside the axis extent.
  31905. */
  31906. Axis.prototype.getTicksCoords = function (opt) {
  31907. opt = opt || {};
  31908. var tickModel = opt.tickModel || this.getTickModel();
  31909. var result = createAxisTicks(this, tickModel);
  31910. var ticks = result.ticks;
  31911. var ticksCoords = map(ticks, function (tickVal) {
  31912. return {
  31913. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  31914. tickValue: tickVal
  31915. };
  31916. }, this);
  31917. var alignWithLabel = tickModel.get('alignWithLabel');
  31918. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  31919. return ticksCoords;
  31920. };
  31921. Axis.prototype.getMinorTicksCoords = function () {
  31922. if (this.scale.type === 'ordinal') {
  31923. // Category axis doesn't support minor ticks
  31924. return [];
  31925. }
  31926. var minorTickModel = this.model.getModel('minorTick');
  31927. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  31928. if (!(splitNumber > 0 && splitNumber < 100)) {
  31929. splitNumber = 5;
  31930. }
  31931. var minorTicks = this.scale.getMinorTicks(splitNumber);
  31932. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  31933. return map(minorTicksGroup, function (minorTick) {
  31934. return {
  31935. coord: this.dataToCoord(minorTick),
  31936. tickValue: minorTick
  31937. };
  31938. }, this);
  31939. }, this);
  31940. return minorTicksCoords;
  31941. };
  31942. Axis.prototype.getViewLabels = function () {
  31943. return createAxisLabels(this).labels;
  31944. };
  31945. Axis.prototype.getLabelModel = function () {
  31946. return this.model.getModel('axisLabel');
  31947. };
  31948. /**
  31949. * Notice here we only get the default tick model. For splitLine
  31950. * or splitArea, we should pass the splitLineModel or splitAreaModel
  31951. * manually when calling `getTicksCoords`.
  31952. * In GL, this method may be overrided to:
  31953. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  31954. */
  31955. Axis.prototype.getTickModel = function () {
  31956. return this.model.getModel('axisTick');
  31957. };
  31958. /**
  31959. * Get width of band
  31960. */
  31961. Axis.prototype.getBandWidth = function () {
  31962. var axisExtent = this._extent;
  31963. var dataExtent = this.scale.getExtent();
  31964. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  31965. len === 0 && (len = 1);
  31966. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  31967. return Math.abs(size) / len;
  31968. };
  31969. /**
  31970. * Only be called in category axis.
  31971. * Can be overrided, consider other axes like in 3D.
  31972. * @return Auto interval for cateogry axis tick and label
  31973. */
  31974. Axis.prototype.calculateCategoryInterval = function () {
  31975. return calculateCategoryInterval(this);
  31976. };
  31977. return Axis;
  31978. }();
  31979. function fixExtentWithBands(extent, nTick) {
  31980. var size = extent[1] - extent[0];
  31981. var len = nTick;
  31982. var margin = size / len / 2;
  31983. extent[0] += margin;
  31984. extent[1] -= margin;
  31985. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  31986. // |---1---|---2---|---3---|---4---|.
  31987. // So the displayed ticks and splitLine/splitArea should between
  31988. // each data item, otherwise cause misleading (e.g., split tow bars
  31989. // of a single data item when there are two bar series).
  31990. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  31991. // splitLine/spliteArea should layout appropriately corresponding
  31992. // to displayed labels. (So we should not use `getBandWidth` in this
  31993. // case).
  31994. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  31995. var ticksLen = ticksCoords.length;
  31996. if (!axis.onBand || alignWithLabel || !ticksLen) {
  31997. return;
  31998. }
  31999. var axisExtent = axis.getExtent();
  32000. var last;
  32001. var diffSize;
  32002. if (ticksLen === 1) {
  32003. ticksCoords[0].coord = axisExtent[0];
  32004. last = ticksCoords[1] = {
  32005. coord: axisExtent[0]
  32006. };
  32007. } else {
  32008. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32009. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32010. each(ticksCoords, function (ticksItem) {
  32011. ticksItem.coord -= shift_1 / 2;
  32012. });
  32013. var dataExtent = axis.scale.getExtent();
  32014. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32015. last = {
  32016. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32017. };
  32018. ticksCoords.push(last);
  32019. }
  32020. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  32021. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32022. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32023. }
  32024. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32025. ticksCoords.unshift({
  32026. coord: axisExtent[0]
  32027. });
  32028. }
  32029. if (littleThan(axisExtent[1], last.coord)) {
  32030. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32031. }
  32032. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32033. ticksCoords.push({
  32034. coord: axisExtent[1]
  32035. });
  32036. }
  32037. function littleThan(a, b) {
  32038. // Avoid rounding error cause calculated tick coord different with extent.
  32039. // It may cause an extra unecessary tick added.
  32040. a = round(a);
  32041. b = round(b);
  32042. return inverse ? a > b : a < b;
  32043. }
  32044. }
  32045. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32046. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32047. // class Bar3DModel extends ComponentModel {}
  32048. // export function install(registers) { regsiters.registerComponentModel(Bar3DModel); }
  32049. // echarts.use(install);
  32050. function extendComponentModel(proto) {
  32051. var Model = ComponentModel.extend(proto);
  32052. ComponentModel.registerClass(Model);
  32053. return Model;
  32054. }
  32055. function extendComponentView(proto) {
  32056. var View = ComponentView.extend(proto);
  32057. ComponentView.registerClass(View);
  32058. return View;
  32059. }
  32060. function extendSeriesModel(proto) {
  32061. var Model = SeriesModel.extend(proto);
  32062. SeriesModel.registerClass(Model);
  32063. return Model;
  32064. }
  32065. function extendChartView(proto) {
  32066. var View = ChartView.extend(proto);
  32067. ChartView.registerClass(View);
  32068. return View;
  32069. }
  32070. function createElement(name) {
  32071. return document.createElementNS('http://www.w3.org/2000/svg', name);
  32072. }
  32073. function diff(oldArr, newArr, equals) {
  32074. if (!equals) {
  32075. equals = function (a, b) {
  32076. return a === b;
  32077. };
  32078. }
  32079. oldArr = oldArr.slice();
  32080. newArr = newArr.slice();
  32081. var newLen = newArr.length;
  32082. var oldLen = oldArr.length;
  32083. var editLength = 1;
  32084. var maxEditLength = newLen + oldLen;
  32085. var bestPath = [{ newPos: -1, components: [] }];
  32086. var oldPos = extractCommon(bestPath[0], newArr, oldArr, 0, equals);
  32087. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  32088. var indices = [];
  32089. for (var i = 0; i < newArr.length; i++) {
  32090. indices.push(i);
  32091. }
  32092. return [{
  32093. indices: indices,
  32094. count: newArr.length,
  32095. added: false,
  32096. removed: false
  32097. }];
  32098. }
  32099. function execEditLength() {
  32100. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  32101. var basePath;
  32102. var addPath = bestPath[diagonalPath - 1];
  32103. var removePath = bestPath[diagonalPath + 1];
  32104. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  32105. if (addPath) {
  32106. bestPath[diagonalPath - 1] = undefined;
  32107. }
  32108. var canAdd = addPath && addPath.newPos + 1 < newLen;
  32109. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  32110. if (!canAdd && !canRemove) {
  32111. bestPath[diagonalPath] = undefined;
  32112. continue;
  32113. }
  32114. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  32115. basePath = clonePath(removePath);
  32116. pushComponent(basePath.components, false, true);
  32117. }
  32118. else {
  32119. basePath = addPath;
  32120. basePath.newPos++;
  32121. pushComponent(basePath.components, true, false);
  32122. }
  32123. oldPos = extractCommon(basePath, newArr, oldArr, diagonalPath, equals);
  32124. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  32125. return buildValues(basePath.components);
  32126. }
  32127. else {
  32128. bestPath[diagonalPath] = basePath;
  32129. }
  32130. }
  32131. editLength++;
  32132. }
  32133. while (editLength <= maxEditLength) {
  32134. var ret = execEditLength();
  32135. if (ret) {
  32136. return ret;
  32137. }
  32138. }
  32139. }
  32140. function extractCommon(basePath, newArr, oldArr, diagonalPath, equals) {
  32141. var newLen = newArr.length;
  32142. var oldLen = oldArr.length;
  32143. var newPos = basePath.newPos;
  32144. var oldPos = newPos - diagonalPath;
  32145. var commonCount = 0;
  32146. while (newPos + 1 < newLen && oldPos + 1 < oldLen && equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  32147. newPos++;
  32148. oldPos++;
  32149. commonCount++;
  32150. }
  32151. if (commonCount) {
  32152. basePath.components.push({
  32153. count: commonCount,
  32154. added: false,
  32155. removed: false,
  32156. indices: []
  32157. });
  32158. }
  32159. basePath.newPos = newPos;
  32160. return oldPos;
  32161. }
  32162. function pushComponent(components, added, removed) {
  32163. var last = components[components.length - 1];
  32164. if (last && last.added === added && last.removed === removed) {
  32165. components[components.length - 1] = {
  32166. count: last.count + 1,
  32167. added: added,
  32168. removed: removed,
  32169. indices: []
  32170. };
  32171. }
  32172. else {
  32173. components.push({
  32174. count: 1,
  32175. added: added,
  32176. removed: removed,
  32177. indices: []
  32178. });
  32179. }
  32180. }
  32181. function buildValues(components) {
  32182. var componentPos = 0;
  32183. var componentLen = components.length;
  32184. var newPos = 0;
  32185. var oldPos = 0;
  32186. for (; componentPos < componentLen; componentPos++) {
  32187. var component = components[componentPos];
  32188. if (!component.removed) {
  32189. var indices = [];
  32190. for (var i = newPos; i < newPos + component.count; i++) {
  32191. indices.push(i);
  32192. }
  32193. component.indices = indices;
  32194. newPos += component.count;
  32195. if (!component.added) {
  32196. oldPos += component.count;
  32197. }
  32198. }
  32199. else {
  32200. for (var i = oldPos; i < oldPos + component.count; i++) {
  32201. component.indices.push(i);
  32202. }
  32203. oldPos += component.count;
  32204. }
  32205. }
  32206. return components;
  32207. }
  32208. function clonePath(path) {
  32209. return { newPos: path.newPos, components: path.components.slice(0) };
  32210. }
  32211. function arrayDiff(oldArr, newArr, equal) {
  32212. return diff(oldArr, newArr, equal);
  32213. }
  32214. var NONE = 'none';
  32215. var mathRound = Math.round;
  32216. var mathSin$4 = Math.sin;
  32217. var mathCos$4 = Math.cos;
  32218. var PI$4 = Math.PI;
  32219. var PI2$7 = Math.PI * 2;
  32220. var degree = 180 / PI$4;
  32221. var EPSILON$4 = 1e-4;
  32222. function round3(val) {
  32223. return mathRound(val * 1e3) / 1e3;
  32224. }
  32225. function round4(val) {
  32226. return mathRound(val * 1e4) / 1e4;
  32227. }
  32228. function isAroundZero$1(val) {
  32229. return val < EPSILON$4 && val > -EPSILON$4;
  32230. }
  32231. function pathHasFill(style) {
  32232. var fill = style.fill;
  32233. return fill != null && fill !== NONE;
  32234. }
  32235. function pathHasStroke(style) {
  32236. var stroke = style.stroke;
  32237. return stroke != null && stroke !== NONE;
  32238. }
  32239. function setTransform(svgEl, m) {
  32240. if (m) {
  32241. attr(svgEl, 'transform', 'matrix('
  32242. + round3(m[0]) + ','
  32243. + round3(m[1]) + ','
  32244. + round3(m[2]) + ','
  32245. + round3(m[3]) + ','
  32246. + round4(m[4]) + ','
  32247. + round4(m[5])
  32248. + ')');
  32249. }
  32250. }
  32251. function attr(el, key, val) {
  32252. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  32253. el.setAttribute(key, val);
  32254. }
  32255. }
  32256. function attrXLink(el, key, val) {
  32257. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  32258. }
  32259. function attrXML(el, key, val) {
  32260. el.setAttributeNS('http://www.w3.org/XML/1998/namespace', key, val);
  32261. }
  32262. function bindStyle(svgEl, style, el) {
  32263. var opacity = style.opacity == null ? 1 : style.opacity;
  32264. if (el instanceof ZRImage) {
  32265. svgEl.style.opacity = opacity + '';
  32266. return;
  32267. }
  32268. if (pathHasFill(style)) {
  32269. var fill = style.fill;
  32270. fill = fill === 'transparent' ? NONE : fill;
  32271. attr(svgEl, 'fill', fill);
  32272. attr(svgEl, 'fill-opacity', (style.fillOpacity != null ? style.fillOpacity * opacity : opacity) + '');
  32273. }
  32274. else {
  32275. attr(svgEl, 'fill', NONE);
  32276. }
  32277. if (pathHasStroke(style)) {
  32278. var stroke = style.stroke;
  32279. stroke = stroke === 'transparent' ? NONE : stroke;
  32280. attr(svgEl, 'stroke', stroke);
  32281. var strokeWidth = style.lineWidth;
  32282. var strokeScale_1 = style.strokeNoScale
  32283. ? el.getLineScale()
  32284. : 1;
  32285. attr(svgEl, 'stroke-width', (strokeScale_1 ? strokeWidth / strokeScale_1 : 0) + '');
  32286. attr(svgEl, 'paint-order', style.strokeFirst ? 'stroke' : 'fill');
  32287. attr(svgEl, 'stroke-opacity', (style.strokeOpacity != null ? style.strokeOpacity * opacity : opacity) + '');
  32288. var lineDash = style.lineDash && strokeWidth > 0 && normalizeLineDash(style.lineDash, strokeWidth);
  32289. if (lineDash) {
  32290. var lineDashOffset = style.lineDashOffset;
  32291. if (strokeScale_1 && strokeScale_1 !== 1) {
  32292. lineDash = map(lineDash, function (rawVal) {
  32293. return rawVal / strokeScale_1;
  32294. });
  32295. if (lineDashOffset) {
  32296. lineDashOffset /= strokeScale_1;
  32297. lineDashOffset = mathRound(lineDashOffset);
  32298. }
  32299. }
  32300. attr(svgEl, 'stroke-dasharray', lineDash.join(','));
  32301. attr(svgEl, 'stroke-dashoffset', (lineDashOffset || 0) + '');
  32302. }
  32303. else {
  32304. attr(svgEl, 'stroke-dasharray', '');
  32305. }
  32306. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  32307. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  32308. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit + '');
  32309. }
  32310. else {
  32311. attr(svgEl, 'stroke', NONE);
  32312. }
  32313. }
  32314. var SVGPathRebuilder = (function () {
  32315. function SVGPathRebuilder() {
  32316. }
  32317. SVGPathRebuilder.prototype.reset = function () {
  32318. this._d = [];
  32319. this._str = '';
  32320. };
  32321. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  32322. this._add('M', x, y);
  32323. };
  32324. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  32325. this._add('L', x, y);
  32326. };
  32327. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  32328. this._add('C', x, y, x2, y2, x3, y3);
  32329. };
  32330. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  32331. this._add('Q', x, y, x2, y2);
  32332. };
  32333. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  32334. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  32335. };
  32336. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  32337. var firstCmd = this._d.length === 0;
  32338. var dTheta = endAngle - startAngle;
  32339. var clockwise = !anticlockwise;
  32340. var dThetaPositive = Math.abs(dTheta);
  32341. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  32342. || (clockwise ? dTheta >= PI2$7 : -dTheta >= PI2$7);
  32343. var unifiedTheta = dTheta > 0 ? dTheta % PI2$7 : (dTheta % PI2$7 + PI2$7);
  32344. var large = false;
  32345. if (isCircle) {
  32346. large = true;
  32347. }
  32348. else if (isAroundZero$1(dThetaPositive)) {
  32349. large = false;
  32350. }
  32351. else {
  32352. large = (unifiedTheta >= PI$4) === !!clockwise;
  32353. }
  32354. var x0 = round4(cx + rx * mathCos$4(startAngle));
  32355. var y0 = round4(cy + ry * mathSin$4(startAngle));
  32356. if (isCircle) {
  32357. if (clockwise) {
  32358. dTheta = PI2$7 - 1e-4;
  32359. }
  32360. else {
  32361. dTheta = -PI2$7 + 1e-4;
  32362. }
  32363. large = true;
  32364. if (firstCmd) {
  32365. this._d.push('M', x0, y0);
  32366. }
  32367. }
  32368. var x = round4(cx + rx * mathCos$4(startAngle + dTheta));
  32369. var y = round4(cy + ry * mathSin$4(startAngle + dTheta));
  32370. if (isNaN(x0) || isNaN(y0) || isNaN(rx) || isNaN(ry) || isNaN(psi) || isNaN(degree) || isNaN(x) || isNaN(y)) {
  32371. return '';
  32372. }
  32373. this._d.push('A', round4(rx), round4(ry), mathRound(psi * degree), +large, +clockwise, x, y);
  32374. };
  32375. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  32376. this._add('M', x, y);
  32377. this._add('L', x + w, y);
  32378. this._add('L', x + w, y + h);
  32379. this._add('L', x, y + h);
  32380. this._add('L', x, y);
  32381. };
  32382. SVGPathRebuilder.prototype.closePath = function () {
  32383. if (this._d.length > 0) {
  32384. this._add('Z');
  32385. }
  32386. };
  32387. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  32388. this._d.push(cmd);
  32389. for (var i = 1; i < arguments.length; i++) {
  32390. var val = arguments[i];
  32391. if (isNaN(val)) {
  32392. this._invalid = true;
  32393. return;
  32394. }
  32395. this._d.push(round4(val));
  32396. }
  32397. };
  32398. SVGPathRebuilder.prototype.generateStr = function () {
  32399. this._str = this._invalid ? '' : this._d.join(' ');
  32400. this._d = [];
  32401. };
  32402. SVGPathRebuilder.prototype.getStr = function () {
  32403. return this._str;
  32404. };
  32405. return SVGPathRebuilder;
  32406. }());
  32407. var svgPath = {
  32408. brush: function (el) {
  32409. var style = el.style;
  32410. var svgEl = el.__svgEl;
  32411. if (!svgEl) {
  32412. svgEl = createElement('path');
  32413. el.__svgEl = svgEl;
  32414. }
  32415. if (!el.path) {
  32416. el.createPathProxy();
  32417. }
  32418. var path = el.path;
  32419. if (el.shapeChanged()) {
  32420. path.beginPath();
  32421. el.buildPath(path, el.shape);
  32422. el.pathUpdated();
  32423. }
  32424. var pathVersion = path.getVersion();
  32425. var elExt = el;
  32426. var svgPathBuilder = elExt.__svgPathBuilder;
  32427. if (elExt.__svgPathVersion !== pathVersion || !svgPathBuilder || el.style.strokePercent < 1) {
  32428. if (!svgPathBuilder) {
  32429. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  32430. }
  32431. svgPathBuilder.reset();
  32432. path.rebuildPath(svgPathBuilder, el.style.strokePercent);
  32433. svgPathBuilder.generateStr();
  32434. elExt.__svgPathVersion = pathVersion;
  32435. }
  32436. attr(svgEl, 'd', svgPathBuilder.getStr());
  32437. bindStyle(svgEl, style, el);
  32438. setTransform(svgEl, el.transform);
  32439. }
  32440. };
  32441. var svgImage = {
  32442. brush: function (el) {
  32443. var style = el.style;
  32444. var image = style.image;
  32445. if (image instanceof HTMLImageElement) {
  32446. image = image.src;
  32447. }
  32448. else if (image instanceof HTMLCanvasElement) {
  32449. image = image.toDataURL();
  32450. }
  32451. if (!image) {
  32452. return;
  32453. }
  32454. var x = style.x || 0;
  32455. var y = style.y || 0;
  32456. var dw = style.width;
  32457. var dh = style.height;
  32458. var svgEl = el.__svgEl;
  32459. if (!svgEl) {
  32460. svgEl = createElement('image');
  32461. el.__svgEl = svgEl;
  32462. }
  32463. if (image !== el.__imageSrc) {
  32464. attrXLink(svgEl, 'href', image);
  32465. el.__imageSrc = image;
  32466. }
  32467. attr(svgEl, 'width', dw + '');
  32468. attr(svgEl, 'height', dh + '');
  32469. attr(svgEl, 'x', x + '');
  32470. attr(svgEl, 'y', y + '');
  32471. bindStyle(svgEl, style, el);
  32472. setTransform(svgEl, el.transform);
  32473. }
  32474. };
  32475. var TEXT_ALIGN_TO_ANCHOR = {
  32476. left: 'start',
  32477. right: 'end',
  32478. center: 'middle',
  32479. middle: 'middle'
  32480. };
  32481. function adjustTextY$1(y, lineHeight, textBaseline) {
  32482. if (textBaseline === 'top') {
  32483. y += lineHeight / 2;
  32484. }
  32485. else if (textBaseline === 'bottom') {
  32486. y -= lineHeight / 2;
  32487. }
  32488. return y;
  32489. }
  32490. var svgText = {
  32491. brush: function (el) {
  32492. var style = el.style;
  32493. var text = style.text;
  32494. text != null && (text += '');
  32495. if (!text || isNaN(style.x) || isNaN(style.y)) {
  32496. return;
  32497. }
  32498. var textSvgEl = el.__svgEl;
  32499. if (!textSvgEl) {
  32500. textSvgEl = createElement('text');
  32501. attrXML(textSvgEl, 'xml:space', 'preserve');
  32502. el.__svgEl = textSvgEl;
  32503. }
  32504. var font = style.font || DEFAULT_FONT;
  32505. var textSvgElStyle = textSvgEl.style;
  32506. textSvgElStyle.font = font;
  32507. textSvgEl.textContent = text;
  32508. bindStyle(textSvgEl, style, el);
  32509. setTransform(textSvgEl, el.transform);
  32510. var x = style.x || 0;
  32511. var y = adjustTextY$1(style.y || 0, getLineHeight(font), style.textBaseline);
  32512. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  32513. || style.textAlign;
  32514. attr(textSvgEl, 'dominant-baseline', 'central');
  32515. attr(textSvgEl, 'text-anchor', textAlign);
  32516. attr(textSvgEl, 'x', x + '');
  32517. attr(textSvgEl, 'y', y + '');
  32518. }
  32519. };
  32520. var MARK_UNUSED = '0';
  32521. var MARK_USED = '1';
  32522. var Definable = (function () {
  32523. function Definable(zrId, svgRoot, tagNames, markLabel, domName) {
  32524. this.nextId = 0;
  32525. this._domName = '_dom';
  32526. this.createElement = createElement;
  32527. this._zrId = zrId;
  32528. this._svgRoot = svgRoot;
  32529. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  32530. this._markLabel = markLabel;
  32531. if (domName) {
  32532. this._domName = domName;
  32533. }
  32534. }
  32535. Definable.prototype.getDefs = function (isForceCreating) {
  32536. var svgRoot = this._svgRoot;
  32537. var defs = this._svgRoot.getElementsByTagName('defs');
  32538. if (defs.length === 0) {
  32539. if (isForceCreating) {
  32540. var defs_1 = svgRoot.insertBefore(this.createElement('defs'), svgRoot.firstChild);
  32541. if (!defs_1.contains) {
  32542. defs_1.contains = function (el) {
  32543. var children = defs_1.children;
  32544. if (!children) {
  32545. return false;
  32546. }
  32547. for (var i = children.length - 1; i >= 0; --i) {
  32548. if (children[i] === el) {
  32549. return true;
  32550. }
  32551. }
  32552. return false;
  32553. };
  32554. }
  32555. return defs_1;
  32556. }
  32557. else {
  32558. return null;
  32559. }
  32560. }
  32561. else {
  32562. return defs[0];
  32563. }
  32564. };
  32565. Definable.prototype.doUpdate = function (target, onUpdate) {
  32566. if (!target) {
  32567. return;
  32568. }
  32569. var defs = this.getDefs(false);
  32570. if (target[this._domName] && defs.contains(target[this._domName])) {
  32571. if (typeof onUpdate === 'function') {
  32572. onUpdate(target);
  32573. }
  32574. }
  32575. else {
  32576. var dom = this.add(target);
  32577. if (dom) {
  32578. target[this._domName] = dom;
  32579. }
  32580. }
  32581. };
  32582. Definable.prototype.add = function (target) {
  32583. return null;
  32584. };
  32585. Definable.prototype.addDom = function (dom) {
  32586. var defs = this.getDefs(true);
  32587. if (dom.parentNode !== defs) {
  32588. defs.appendChild(dom);
  32589. }
  32590. };
  32591. Definable.prototype.removeDom = function (target) {
  32592. var defs = this.getDefs(false);
  32593. if (defs && target[this._domName]) {
  32594. defs.removeChild(target[this._domName]);
  32595. target[this._domName] = null;
  32596. }
  32597. };
  32598. Definable.prototype.getDoms = function () {
  32599. var defs = this.getDefs(false);
  32600. if (!defs) {
  32601. return [];
  32602. }
  32603. var doms = [];
  32604. each(this._tagNames, function (tagName) {
  32605. var tags = defs.getElementsByTagName(tagName);
  32606. for (var i = 0; i < tags.length; i++) {
  32607. doms.push(tags[i]);
  32608. }
  32609. });
  32610. return doms;
  32611. };
  32612. Definable.prototype.markAllUnused = function () {
  32613. var doms = this.getDoms();
  32614. var that = this;
  32615. each(doms, function (dom) {
  32616. dom[that._markLabel] = MARK_UNUSED;
  32617. });
  32618. };
  32619. Definable.prototype.markDomUsed = function (dom) {
  32620. dom && (dom[this._markLabel] = MARK_USED);
  32621. };
  32622. Definable.prototype.markDomUnused = function (dom) {
  32623. dom && (dom[this._markLabel] = MARK_UNUSED);
  32624. };
  32625. Definable.prototype.isDomUnused = function (dom) {
  32626. return dom && dom[this._markLabel] !== MARK_USED;
  32627. };
  32628. Definable.prototype.removeUnused = function () {
  32629. var _this = this;
  32630. var defs = this.getDefs(false);
  32631. if (!defs) {
  32632. return;
  32633. }
  32634. var doms = this.getDoms();
  32635. each(doms, function (dom) {
  32636. if (_this.isDomUnused(dom)) {
  32637. defs.removeChild(dom);
  32638. }
  32639. });
  32640. };
  32641. Definable.prototype.getSvgProxy = function (displayable) {
  32642. if (displayable instanceof Path) {
  32643. return svgPath;
  32644. }
  32645. else if (displayable instanceof ZRImage) {
  32646. return svgImage;
  32647. }
  32648. else if (displayable instanceof TSpan) {
  32649. return svgText;
  32650. }
  32651. else {
  32652. return svgPath;
  32653. }
  32654. };
  32655. Definable.prototype.getSvgElement = function (displayable) {
  32656. return displayable.__svgEl;
  32657. };
  32658. return Definable;
  32659. }());
  32660. function isLinearGradient(value) {
  32661. return value.type === 'linear';
  32662. }
  32663. function isRadialGradient(value) {
  32664. return value.type === 'radial';
  32665. }
  32666. function isGradient(value) {
  32667. return value && (value.type === 'linear'
  32668. || value.type === 'radial');
  32669. }
  32670. var GradientManager = (function (_super) {
  32671. __extends(GradientManager, _super);
  32672. function GradientManager(zrId, svgRoot) {
  32673. return _super.call(this, zrId, svgRoot, ['linearGradient', 'radialGradient'], '__gradient_in_use__') || this;
  32674. }
  32675. GradientManager.prototype.addWithoutUpdate = function (svgElement, displayable) {
  32676. if (displayable && displayable.style) {
  32677. var that_1 = this;
  32678. each(['fill', 'stroke'], function (fillOrStroke) {
  32679. var value = displayable.style[fillOrStroke];
  32680. if (isGradient(value)) {
  32681. var gradient = value;
  32682. var defs = that_1.getDefs(true);
  32683. var dom = void 0;
  32684. if (gradient.__dom) {
  32685. dom = gradient.__dom;
  32686. if (!defs.contains(gradient.__dom)) {
  32687. that_1.addDom(dom);
  32688. }
  32689. }
  32690. else {
  32691. dom = that_1.add(gradient);
  32692. }
  32693. that_1.markUsed(displayable);
  32694. var id = dom.getAttribute('id');
  32695. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  32696. }
  32697. });
  32698. }
  32699. };
  32700. GradientManager.prototype.add = function (gradient) {
  32701. var dom;
  32702. if (isLinearGradient(gradient)) {
  32703. dom = this.createElement('linearGradient');
  32704. }
  32705. else if (isRadialGradient(gradient)) {
  32706. dom = this.createElement('radialGradient');
  32707. }
  32708. else {
  32709. logError('Illegal gradient type.');
  32710. return null;
  32711. }
  32712. gradient.id = gradient.id || this.nextId++;
  32713. dom.setAttribute('id', 'zr' + this._zrId
  32714. + '-gradient-' + gradient.id);
  32715. this.updateDom(gradient, dom);
  32716. this.addDom(dom);
  32717. return dom;
  32718. };
  32719. GradientManager.prototype.update = function (gradient) {
  32720. if (!isGradient(gradient)) {
  32721. return;
  32722. }
  32723. var that = this;
  32724. this.doUpdate(gradient, function () {
  32725. var dom = gradient.__dom;
  32726. if (!dom) {
  32727. return;
  32728. }
  32729. var tagName = dom.tagName;
  32730. var type = gradient.type;
  32731. if (type === 'linear' && tagName === 'linearGradient'
  32732. || type === 'radial' && tagName === 'radialGradient') {
  32733. that.updateDom(gradient, gradient.__dom);
  32734. }
  32735. else {
  32736. that.removeDom(gradient);
  32737. that.add(gradient);
  32738. }
  32739. });
  32740. };
  32741. GradientManager.prototype.updateDom = function (gradient, dom) {
  32742. if (isLinearGradient(gradient)) {
  32743. dom.setAttribute('x1', gradient.x + '');
  32744. dom.setAttribute('y1', gradient.y + '');
  32745. dom.setAttribute('x2', gradient.x2 + '');
  32746. dom.setAttribute('y2', gradient.y2 + '');
  32747. }
  32748. else if (isRadialGradient(gradient)) {
  32749. dom.setAttribute('cx', gradient.x + '');
  32750. dom.setAttribute('cy', gradient.y + '');
  32751. dom.setAttribute('r', gradient.r + '');
  32752. }
  32753. else {
  32754. logError('Illegal gradient type.');
  32755. return;
  32756. }
  32757. if (gradient.global) {
  32758. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  32759. }
  32760. else {
  32761. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  32762. }
  32763. dom.innerHTML = '';
  32764. var colors = gradient.colorStops;
  32765. for (var i = 0, len = colors.length; i < len; ++i) {
  32766. var stop_1 = this.createElement('stop');
  32767. stop_1.setAttribute('offset', colors[i].offset * 100 + '%');
  32768. var color$1 = colors[i].color;
  32769. if (color$1.indexOf('rgba') > -1) {
  32770. var opacity = parse(color$1)[3];
  32771. var hex = toHex(color$1);
  32772. stop_1.setAttribute('stop-color', '#' + hex);
  32773. stop_1.setAttribute('stop-opacity', opacity + '');
  32774. }
  32775. else {
  32776. stop_1.setAttribute('stop-color', colors[i].color);
  32777. }
  32778. dom.appendChild(stop_1);
  32779. }
  32780. gradient.__dom = dom;
  32781. };
  32782. GradientManager.prototype.markUsed = function (displayable) {
  32783. if (displayable.style) {
  32784. var gradient = displayable.style.fill;
  32785. if (gradient && gradient.__dom) {
  32786. _super.prototype.markDomUsed.call(this, gradient.__dom);
  32787. }
  32788. gradient = displayable.style.stroke;
  32789. if (gradient && gradient.__dom) {
  32790. _super.prototype.markDomUsed.call(this, gradient.__dom);
  32791. }
  32792. }
  32793. };
  32794. return GradientManager;
  32795. }(Definable));
  32796. function isPattern(value) {
  32797. return value && (!!value.image || !!value.svgElement);
  32798. }
  32799. var patternDomMap = new WeakMap();
  32800. var PatternManager = (function (_super) {
  32801. __extends(PatternManager, _super);
  32802. function PatternManager(zrId, svgRoot) {
  32803. return _super.call(this, zrId, svgRoot, ['pattern'], '__pattern_in_use__') || this;
  32804. }
  32805. PatternManager.prototype.addWithoutUpdate = function (svgElement, displayable) {
  32806. if (displayable && displayable.style) {
  32807. var that_1 = this;
  32808. each(['fill', 'stroke'], function (fillOrStroke) {
  32809. var pattern = displayable.style[fillOrStroke];
  32810. if (isPattern(pattern)) {
  32811. var defs = that_1.getDefs(true);
  32812. var dom = patternDomMap.get(pattern);
  32813. if (dom) {
  32814. if (!defs.contains(dom)) {
  32815. that_1.addDom(dom);
  32816. }
  32817. }
  32818. else {
  32819. dom = that_1.add(pattern);
  32820. }
  32821. that_1.markUsed(displayable);
  32822. var id = dom.getAttribute('id');
  32823. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  32824. }
  32825. });
  32826. }
  32827. };
  32828. PatternManager.prototype.add = function (pattern) {
  32829. if (!isPattern(pattern)) {
  32830. return;
  32831. }
  32832. var dom = this.createElement('pattern');
  32833. pattern.id = pattern.id == null ? this.nextId++ : pattern.id;
  32834. dom.setAttribute('id', 'zr' + this._zrId
  32835. + '-pattern-' + pattern.id);
  32836. dom.setAttribute('x', '0');
  32837. dom.setAttribute('y', '0');
  32838. dom.setAttribute('patternUnits', 'userSpaceOnUse');
  32839. this.updateDom(pattern, dom);
  32840. this.addDom(dom);
  32841. return dom;
  32842. };
  32843. PatternManager.prototype.update = function (pattern) {
  32844. if (!isPattern(pattern)) {
  32845. return;
  32846. }
  32847. var that = this;
  32848. this.doUpdate(pattern, function () {
  32849. var dom = patternDomMap.get(pattern);
  32850. that.updateDom(pattern, dom);
  32851. });
  32852. };
  32853. PatternManager.prototype.updateDom = function (pattern, patternDom) {
  32854. var svgElement = pattern.svgElement;
  32855. if (svgElement instanceof SVGElement) {
  32856. if (svgElement.parentNode !== patternDom) {
  32857. patternDom.innerHTML = '';
  32858. patternDom.appendChild(svgElement);
  32859. patternDom.setAttribute('width', pattern.svgWidth + '');
  32860. patternDom.setAttribute('height', pattern.svgHeight + '');
  32861. }
  32862. }
  32863. else {
  32864. var img = void 0;
  32865. var prevImage = patternDom.getElementsByTagName('image');
  32866. if (prevImage.length) {
  32867. if (pattern.image) {
  32868. img = prevImage[0];
  32869. }
  32870. else {
  32871. patternDom.removeChild(prevImage[0]);
  32872. return;
  32873. }
  32874. }
  32875. else if (pattern.image) {
  32876. img = this.createElement('image');
  32877. }
  32878. if (img) {
  32879. var imageSrc = void 0;
  32880. if (typeof pattern.image === 'string') {
  32881. imageSrc = pattern.image;
  32882. }
  32883. else if (pattern.image instanceof HTMLImageElement) {
  32884. imageSrc = pattern.image.src;
  32885. }
  32886. else if (pattern.image instanceof HTMLCanvasElement) {
  32887. imageSrc = pattern.image.toDataURL();
  32888. }
  32889. if (imageSrc) {
  32890. img.setAttribute('href', imageSrc);
  32891. img.setAttribute('x', '0');
  32892. img.setAttribute('y', '0');
  32893. var hostEl = {
  32894. dirty: function () { }
  32895. };
  32896. var createdImage = createOrUpdateImage(imageSrc, img, hostEl, function (img) {
  32897. patternDom.setAttribute('width', img.width + '');
  32898. patternDom.setAttribute('height', img.height + '');
  32899. });
  32900. if (createdImage && createdImage.width && createdImage.height) {
  32901. patternDom.setAttribute('width', createdImage.width + '');
  32902. patternDom.setAttribute('height', createdImage.height + '');
  32903. }
  32904. patternDom.appendChild(img);
  32905. }
  32906. }
  32907. }
  32908. var x = pattern.x || 0;
  32909. var y = pattern.y || 0;
  32910. var rotation = (pattern.rotation || 0) / Math.PI * 180;
  32911. var scaleX = pattern.scaleX || 1;
  32912. var scaleY = pattern.scaleY || 1;
  32913. var transform = "translate(" + x + ", " + y + ") rotate(" + rotation + ") scale(" + scaleX + ", " + scaleY + ")";
  32914. patternDom.setAttribute('patternTransform', transform);
  32915. patternDomMap.set(pattern, patternDom);
  32916. };
  32917. PatternManager.prototype.markUsed = function (displayable) {
  32918. if (displayable.style) {
  32919. if (isPattern(displayable.style.fill)) {
  32920. _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.fill));
  32921. }
  32922. if (isPattern(displayable.style.stroke)) {
  32923. _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.stroke));
  32924. }
  32925. }
  32926. };
  32927. return PatternManager;
  32928. }(Definable));
  32929. function generateClipPathsKey(clipPaths) {
  32930. var key = [];
  32931. if (clipPaths) {
  32932. for (var i = 0; i < clipPaths.length; i++) {
  32933. var clipPath = clipPaths[i];
  32934. key.push(clipPath.id);
  32935. }
  32936. }
  32937. return key.join(',');
  32938. }
  32939. function hasClipPath(displayable) {
  32940. var clipPaths = displayable.__clipPaths;
  32941. return clipPaths && clipPaths.length > 0;
  32942. }
  32943. var ClippathManager = (function (_super) {
  32944. __extends(ClippathManager, _super);
  32945. function ClippathManager(zrId, svgRoot) {
  32946. var _this = _super.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__') || this;
  32947. _this._refGroups = {};
  32948. _this._keyDuplicateCount = {};
  32949. return _this;
  32950. }
  32951. ClippathManager.prototype.markAllUnused = function () {
  32952. _super.prototype.markAllUnused.call(this);
  32953. for (var key in this._refGroups) {
  32954. this.markDomUnused(this._refGroups[key]);
  32955. }
  32956. this._keyDuplicateCount = {};
  32957. };
  32958. ClippathManager.prototype._getClipPathGroup = function (displayable, prevDisplayable) {
  32959. if (!hasClipPath(displayable)) {
  32960. return;
  32961. }
  32962. var clipPaths = displayable.__clipPaths;
  32963. var keyDuplicateCount = this._keyDuplicateCount;
  32964. var clipPathKey = generateClipPathsKey(clipPaths);
  32965. if (isClipPathChanged(clipPaths, prevDisplayable && prevDisplayable.__clipPaths)) {
  32966. keyDuplicateCount[clipPathKey] = keyDuplicateCount[clipPathKey] || 0;
  32967. keyDuplicateCount[clipPathKey] && (clipPathKey += '-' + keyDuplicateCount[clipPathKey]);
  32968. keyDuplicateCount[clipPathKey]++;
  32969. }
  32970. return this._refGroups[clipPathKey]
  32971. || (this._refGroups[clipPathKey] = this.createElement('g'));
  32972. };
  32973. ClippathManager.prototype.update = function (displayable, prevDisplayable) {
  32974. var clipGroup = this._getClipPathGroup(displayable, prevDisplayable);
  32975. if (clipGroup) {
  32976. this.markDomUsed(clipGroup);
  32977. this.updateDom(clipGroup, displayable.__clipPaths);
  32978. }
  32979. return clipGroup;
  32980. };
  32981. ClippathManager.prototype.updateDom = function (parentEl, clipPaths) {
  32982. if (clipPaths && clipPaths.length > 0) {
  32983. var defs = this.getDefs(true);
  32984. var clipPath = clipPaths[0];
  32985. var clipPathEl = void 0;
  32986. var id = void 0;
  32987. if (clipPath._dom) {
  32988. id = clipPath._dom.getAttribute('id');
  32989. clipPathEl = clipPath._dom;
  32990. if (!defs.contains(clipPathEl)) {
  32991. defs.appendChild(clipPathEl);
  32992. }
  32993. }
  32994. else {
  32995. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  32996. ++this.nextId;
  32997. clipPathEl = this.createElement('clipPath');
  32998. clipPathEl.setAttribute('id', id);
  32999. defs.appendChild(clipPathEl);
  33000. clipPath._dom = clipPathEl;
  33001. }
  33002. var svgProxy = this.getSvgProxy(clipPath);
  33003. svgProxy.brush(clipPath);
  33004. var pathEl = this.getSvgElement(clipPath);
  33005. clipPathEl.innerHTML = '';
  33006. clipPathEl.appendChild(pathEl);
  33007. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  33008. if (clipPaths.length > 1) {
  33009. this.updateDom(clipPathEl, clipPaths.slice(1));
  33010. }
  33011. }
  33012. else {
  33013. if (parentEl) {
  33014. parentEl.setAttribute('clip-path', 'none');
  33015. }
  33016. }
  33017. };
  33018. ClippathManager.prototype.markUsed = function (displayable) {
  33019. var _this = this;
  33020. if (displayable.__clipPaths) {
  33021. each(displayable.__clipPaths, function (clipPath) {
  33022. if (clipPath._dom) {
  33023. _super.prototype.markDomUsed.call(_this, clipPath._dom);
  33024. }
  33025. });
  33026. }
  33027. };
  33028. ClippathManager.prototype.removeUnused = function () {
  33029. _super.prototype.removeUnused.call(this);
  33030. var newRefGroupsMap = {};
  33031. for (var key in this._refGroups) {
  33032. var group = this._refGroups[key];
  33033. if (!this.isDomUnused(group)) {
  33034. newRefGroupsMap[key] = group;
  33035. }
  33036. else if (group.parentNode) {
  33037. group.parentNode.removeChild(group);
  33038. }
  33039. }
  33040. this._refGroups = newRefGroupsMap;
  33041. };
  33042. return ClippathManager;
  33043. }(Definable));
  33044. var ShadowManager = (function (_super) {
  33045. __extends(ShadowManager, _super);
  33046. function ShadowManager(zrId, svgRoot) {
  33047. var _this = _super.call(this, zrId, svgRoot, ['filter'], '__filter_in_use__', '_shadowDom') || this;
  33048. _this._shadowDomMap = {};
  33049. _this._shadowDomPool = [];
  33050. return _this;
  33051. }
  33052. ShadowManager.prototype._getFromPool = function () {
  33053. var shadowDom = this._shadowDomPool.pop();
  33054. if (!shadowDom) {
  33055. shadowDom = this.createElement('filter');
  33056. shadowDom.setAttribute('id', 'zr' + this._zrId + '-shadow-' + this.nextId++);
  33057. var domChild = this.createElement('feDropShadow');
  33058. shadowDom.appendChild(domChild);
  33059. this.addDom(shadowDom);
  33060. }
  33061. return shadowDom;
  33062. };
  33063. ShadowManager.prototype.update = function (svgElement, displayable) {
  33064. var style = displayable.style;
  33065. if (hasShadow(style)) {
  33066. var shadowKey = getShadowKey(displayable);
  33067. var shadowDom = displayable._shadowDom = this._shadowDomMap[shadowKey];
  33068. if (!shadowDom) {
  33069. shadowDom = this._getFromPool();
  33070. this._shadowDomMap[shadowKey] = shadowDom;
  33071. }
  33072. this.updateDom(svgElement, displayable, shadowDom);
  33073. }
  33074. else {
  33075. this.remove(svgElement, displayable);
  33076. }
  33077. };
  33078. ShadowManager.prototype.remove = function (svgElement, displayable) {
  33079. if (displayable._shadowDom != null) {
  33080. displayable._shadowDom = null;
  33081. svgElement.style.filter = '';
  33082. }
  33083. };
  33084. ShadowManager.prototype.updateDom = function (svgElement, displayable, shadowDom) {
  33085. var domChild = shadowDom.children[0];
  33086. var style = displayable.style;
  33087. var globalScale = displayable.getGlobalScale();
  33088. var scaleX = globalScale[0];
  33089. var scaleY = globalScale[1];
  33090. if (!scaleX || !scaleY) {
  33091. return;
  33092. }
  33093. var offsetX = style.shadowOffsetX || 0;
  33094. var offsetY = style.shadowOffsetY || 0;
  33095. var blur = style.shadowBlur;
  33096. var color = style.shadowColor;
  33097. domChild.setAttribute('dx', offsetX / scaleX + '');
  33098. domChild.setAttribute('dy', offsetY / scaleY + '');
  33099. domChild.setAttribute('flood-color', color);
  33100. var stdDx = blur / 2 / scaleX;
  33101. var stdDy = blur / 2 / scaleY;
  33102. var stdDeviation = stdDx + ' ' + stdDy;
  33103. domChild.setAttribute('stdDeviation', stdDeviation);
  33104. shadowDom.setAttribute('x', '-100%');
  33105. shadowDom.setAttribute('y', '-100%');
  33106. shadowDom.setAttribute('width', '300%');
  33107. shadowDom.setAttribute('height', '300%');
  33108. displayable._shadowDom = shadowDom;
  33109. var id = shadowDom.getAttribute('id');
  33110. svgElement.style.filter = 'url(#' + id + ')';
  33111. };
  33112. ShadowManager.prototype.removeUnused = function () {
  33113. var defs = this.getDefs(false);
  33114. if (!defs) {
  33115. return;
  33116. }
  33117. var shadowDomsPool = this._shadowDomPool;
  33118. for (var key in this._shadowDomMap) {
  33119. var dom = this._shadowDomMap[key];
  33120. shadowDomsPool.push(dom);
  33121. }
  33122. this._shadowDomMap = {};
  33123. };
  33124. return ShadowManager;
  33125. }(Definable));
  33126. function hasShadow(style) {
  33127. return style
  33128. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  33129. }
  33130. function getShadowKey(displayable) {
  33131. var style = displayable.style;
  33132. var globalScale = displayable.getGlobalScale();
  33133. return [
  33134. style.shadowColor,
  33135. (style.shadowBlur || 0).toFixed(2),
  33136. (style.shadowOffsetX || 0).toFixed(2),
  33137. (style.shadowOffsetY || 0).toFixed(2),
  33138. globalScale[0],
  33139. globalScale[1]
  33140. ].join(',');
  33141. }
  33142. function parseInt10(val) {
  33143. return parseInt(val, 10);
  33144. }
  33145. function getSvgProxy(el) {
  33146. if (el instanceof Path) {
  33147. return svgPath;
  33148. }
  33149. else if (el instanceof ZRImage) {
  33150. return svgImage;
  33151. }
  33152. else if (el instanceof TSpan) {
  33153. return svgText;
  33154. }
  33155. else {
  33156. return svgPath;
  33157. }
  33158. }
  33159. function checkParentAvailable(parent, child) {
  33160. return child && parent && child.parentNode !== parent;
  33161. }
  33162. function insertAfter(parent, child, prevSibling) {
  33163. if (checkParentAvailable(parent, child) && prevSibling) {
  33164. var nextSibling = prevSibling.nextSibling;
  33165. nextSibling ? parent.insertBefore(child, nextSibling)
  33166. : parent.appendChild(child);
  33167. }
  33168. }
  33169. function prepend(parent, child) {
  33170. if (checkParentAvailable(parent, child)) {
  33171. var firstChild = parent.firstChild;
  33172. firstChild ? parent.insertBefore(child, firstChild)
  33173. : parent.appendChild(child);
  33174. }
  33175. }
  33176. function remove(parent, child) {
  33177. if (child && parent && child.parentNode === parent) {
  33178. parent.removeChild(child);
  33179. }
  33180. }
  33181. function removeFromMyParent(child) {
  33182. if (child && child.parentNode) {
  33183. child.parentNode.removeChild(child);
  33184. }
  33185. }
  33186. function getSvgElement(displayable) {
  33187. return displayable.__svgEl;
  33188. }
  33189. var SVGPainter = (function () {
  33190. function SVGPainter(root, storage, opts, zrId) {
  33191. this.type = 'svg';
  33192. this.refreshHover = createMethodNotSupport('refreshHover');
  33193. this.pathToImage = createMethodNotSupport('pathToImage');
  33194. this.configLayer = createMethodNotSupport('configLayer');
  33195. this.root = root;
  33196. this.storage = storage;
  33197. this._opts = opts = extend({}, opts || {});
  33198. var svgDom = createElement('svg');
  33199. svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.w3.org/2000/svg');
  33200. svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
  33201. svgDom.setAttribute('version', '1.1');
  33202. svgDom.setAttribute('baseProfile', 'full');
  33203. svgDom.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  33204. var bgRoot = createElement('g');
  33205. svgDom.appendChild(bgRoot);
  33206. var svgRoot = createElement('g');
  33207. svgDom.appendChild(svgRoot);
  33208. this._gradientManager = new GradientManager(zrId, svgRoot);
  33209. this._patternManager = new PatternManager(zrId, svgRoot);
  33210. this._clipPathManager = new ClippathManager(zrId, svgRoot);
  33211. this._shadowManager = new ShadowManager(zrId, svgRoot);
  33212. var viewport = document.createElement('div');
  33213. viewport.style.cssText = 'overflow:hidden;position:relative';
  33214. this._svgDom = svgDom;
  33215. this._svgRoot = svgRoot;
  33216. this._backgroundRoot = bgRoot;
  33217. this._viewport = viewport;
  33218. root.appendChild(viewport);
  33219. viewport.appendChild(svgDom);
  33220. this.resize(opts.width, opts.height);
  33221. this._visibleList = [];
  33222. }
  33223. SVGPainter.prototype.getType = function () {
  33224. return 'svg';
  33225. };
  33226. SVGPainter.prototype.getViewportRoot = function () {
  33227. return this._viewport;
  33228. };
  33229. SVGPainter.prototype.getSvgDom = function () {
  33230. return this._svgDom;
  33231. };
  33232. SVGPainter.prototype.getSvgRoot = function () {
  33233. return this._svgRoot;
  33234. };
  33235. SVGPainter.prototype.getViewportRootOffset = function () {
  33236. var viewportRoot = this.getViewportRoot();
  33237. if (viewportRoot) {
  33238. return {
  33239. offsetLeft: viewportRoot.offsetLeft || 0,
  33240. offsetTop: viewportRoot.offsetTop || 0
  33241. };
  33242. }
  33243. };
  33244. SVGPainter.prototype.refresh = function () {
  33245. var list = this.storage.getDisplayList(true);
  33246. this._paintList(list);
  33247. };
  33248. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  33249. if (this._backgroundRoot && this._backgroundNode) {
  33250. this._backgroundRoot.removeChild(this._backgroundNode);
  33251. }
  33252. var bgNode = createElement('rect');
  33253. bgNode.setAttribute('width', this.getWidth());
  33254. bgNode.setAttribute('height', this.getHeight());
  33255. bgNode.setAttribute('x', 0);
  33256. bgNode.setAttribute('y', 0);
  33257. bgNode.setAttribute('id', 0);
  33258. bgNode.style.fill = backgroundColor;
  33259. this._backgroundRoot.appendChild(bgNode);
  33260. this._backgroundNode = bgNode;
  33261. };
  33262. SVGPainter.prototype.createSVGElement = function (tag) {
  33263. return createElement(tag);
  33264. };
  33265. SVGPainter.prototype.paintOne = function (el) {
  33266. var svgProxy = getSvgProxy(el);
  33267. svgProxy && svgProxy.brush(el);
  33268. return getSvgElement(el);
  33269. };
  33270. SVGPainter.prototype._paintList = function (list) {
  33271. var gradientManager = this._gradientManager;
  33272. var patternManager = this._patternManager;
  33273. var clipPathManager = this._clipPathManager;
  33274. var shadowManager = this._shadowManager;
  33275. gradientManager.markAllUnused();
  33276. patternManager.markAllUnused();
  33277. clipPathManager.markAllUnused();
  33278. shadowManager.markAllUnused();
  33279. var svgRoot = this._svgRoot;
  33280. var visibleList = this._visibleList;
  33281. var listLen = list.length;
  33282. var newVisibleList = [];
  33283. for (var i = 0; i < listLen; i++) {
  33284. var displayable = list[i];
  33285. var svgProxy = getSvgProxy(displayable);
  33286. var svgElement = getSvgElement(displayable);
  33287. if (!displayable.invisible) {
  33288. if (displayable.__dirty || !svgElement) {
  33289. svgProxy && svgProxy.brush(displayable);
  33290. svgElement = getSvgElement(displayable);
  33291. if (svgElement && displayable.style) {
  33292. gradientManager.update(displayable.style.fill);
  33293. gradientManager.update(displayable.style.stroke);
  33294. patternManager.update(displayable.style.fill);
  33295. patternManager.update(displayable.style.stroke);
  33296. shadowManager.update(svgElement, displayable);
  33297. }
  33298. displayable.__dirty = 0;
  33299. }
  33300. if (svgElement) {
  33301. newVisibleList.push(displayable);
  33302. }
  33303. }
  33304. }
  33305. var diff = arrayDiff(visibleList, newVisibleList);
  33306. var prevSvgElement;
  33307. var topPrevSvgElement;
  33308. for (var i = 0; i < diff.length; i++) {
  33309. var item = diff[i];
  33310. if (item.removed) {
  33311. for (var k = 0; k < item.count; k++) {
  33312. var displayable = visibleList[item.indices[k]];
  33313. var svgElement = getSvgElement(displayable);
  33314. hasClipPath(displayable) ? removeFromMyParent(svgElement)
  33315. : remove(svgRoot, svgElement);
  33316. }
  33317. }
  33318. }
  33319. var prevDisplayable;
  33320. var currentClipGroup;
  33321. for (var i = 0; i < diff.length; i++) {
  33322. var item = diff[i];
  33323. if (item.removed) {
  33324. continue;
  33325. }
  33326. for (var k = 0; k < item.count; k++) {
  33327. var displayable = newVisibleList[item.indices[k]];
  33328. var clipGroup = clipPathManager.update(displayable, prevDisplayable);
  33329. if (clipGroup !== currentClipGroup) {
  33330. prevSvgElement = topPrevSvgElement;
  33331. if (clipGroup) {
  33332. prevSvgElement ? insertAfter(svgRoot, clipGroup, prevSvgElement)
  33333. : prepend(svgRoot, clipGroup);
  33334. topPrevSvgElement = clipGroup;
  33335. prevSvgElement = null;
  33336. }
  33337. currentClipGroup = clipGroup;
  33338. }
  33339. var svgElement = getSvgElement(displayable);
  33340. prevSvgElement
  33341. ? insertAfter(currentClipGroup || svgRoot, svgElement, prevSvgElement)
  33342. : prepend(currentClipGroup || svgRoot, svgElement);
  33343. prevSvgElement = svgElement || prevSvgElement;
  33344. if (!currentClipGroup) {
  33345. topPrevSvgElement = prevSvgElement;
  33346. }
  33347. gradientManager.markUsed(displayable);
  33348. gradientManager.addWithoutUpdate(svgElement, displayable);
  33349. patternManager.markUsed(displayable);
  33350. patternManager.addWithoutUpdate(svgElement, displayable);
  33351. clipPathManager.markUsed(displayable);
  33352. prevDisplayable = displayable;
  33353. }
  33354. }
  33355. gradientManager.removeUnused();
  33356. patternManager.removeUnused();
  33357. clipPathManager.removeUnused();
  33358. shadowManager.removeUnused();
  33359. this._visibleList = newVisibleList;
  33360. };
  33361. SVGPainter.prototype._getDefs = function (isForceCreating) {
  33362. var svgRoot = this._svgDom;
  33363. var defs = svgRoot.getElementsByTagName('defs');
  33364. if (defs.length === 0) {
  33365. if (isForceCreating) {
  33366. var defs_1 = svgRoot.insertBefore(createElement('defs'), svgRoot.firstChild);
  33367. if (!defs_1.contains) {
  33368. defs_1.contains = function (el) {
  33369. var children = defs_1.children;
  33370. if (!children) {
  33371. return false;
  33372. }
  33373. for (var i = children.length - 1; i >= 0; --i) {
  33374. if (children[i] === el) {
  33375. return true;
  33376. }
  33377. }
  33378. return false;
  33379. };
  33380. }
  33381. return defs_1;
  33382. }
  33383. else {
  33384. return null;
  33385. }
  33386. }
  33387. else {
  33388. return defs[0];
  33389. }
  33390. };
  33391. SVGPainter.prototype.resize = function (width, height) {
  33392. var viewport = this._viewport;
  33393. viewport.style.display = 'none';
  33394. var opts = this._opts;
  33395. width != null && (opts.width = width);
  33396. height != null && (opts.height = height);
  33397. width = this._getSize(0);
  33398. height = this._getSize(1);
  33399. viewport.style.display = '';
  33400. if (this._width !== width || this._height !== height) {
  33401. this._width = width;
  33402. this._height = height;
  33403. var viewportStyle = viewport.style;
  33404. viewportStyle.width = width + 'px';
  33405. viewportStyle.height = height + 'px';
  33406. var svgRoot = this._svgDom;
  33407. svgRoot.setAttribute('width', width + '');
  33408. svgRoot.setAttribute('height', height + '');
  33409. }
  33410. if (this._backgroundNode) {
  33411. this._backgroundNode.setAttribute('width', width);
  33412. this._backgroundNode.setAttribute('height', height);
  33413. }
  33414. };
  33415. SVGPainter.prototype.getWidth = function () {
  33416. return this._width;
  33417. };
  33418. SVGPainter.prototype.getHeight = function () {
  33419. return this._height;
  33420. };
  33421. SVGPainter.prototype._getSize = function (whIdx) {
  33422. var opts = this._opts;
  33423. var wh = ['width', 'height'][whIdx];
  33424. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  33425. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  33426. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  33427. if (opts[wh] != null && opts[wh] !== 'auto') {
  33428. return parseFloat(opts[wh]);
  33429. }
  33430. var root = this.root;
  33431. var stl = document.defaultView.getComputedStyle(root);
  33432. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  33433. - (parseInt10(stl[plt]) || 0)
  33434. - (parseInt10(stl[prb]) || 0)) | 0;
  33435. };
  33436. SVGPainter.prototype.dispose = function () {
  33437. this.root.innerHTML = '';
  33438. this._svgRoot
  33439. = this._backgroundRoot
  33440. = this._svgDom
  33441. = this._backgroundNode
  33442. = this._viewport
  33443. = this.storage
  33444. = null;
  33445. };
  33446. SVGPainter.prototype.clear = function () {
  33447. var viewportNode = this._viewport;
  33448. if (viewportNode && viewportNode.parentNode) {
  33449. viewportNode.parentNode.removeChild(viewportNode);
  33450. }
  33451. };
  33452. SVGPainter.prototype.toDataURL = function () {
  33453. this.refresh();
  33454. var svgDom = this._svgDom;
  33455. var outerHTML = svgDom.outerHTML
  33456. || (svgDom.parentNode && svgDom.parentNode).innerHTML;
  33457. var html = encodeURIComponent(outerHTML.replace(/></g, '>\n\r<'));
  33458. return 'data:image/svg+xml;charset=UTF-8,' + html;
  33459. };
  33460. return SVGPainter;
  33461. }());
  33462. function createMethodNotSupport(method) {
  33463. return function () {
  33464. logError('In SVG mode painter not support method "' + method + '"');
  33465. };
  33466. }
  33467. function install(registers) {
  33468. registers.registerPainter('svg', SVGPainter);
  33469. }
  33470. function returnFalse() {
  33471. return false;
  33472. }
  33473. function createDom(id, painter, dpr) {
  33474. var newDom = createCanvas();
  33475. var width = painter.getWidth();
  33476. var height = painter.getHeight();
  33477. var newDomStyle = newDom.style;
  33478. if (newDomStyle) {
  33479. newDomStyle.position = 'absolute';
  33480. newDomStyle.left = '0';
  33481. newDomStyle.top = '0';
  33482. newDomStyle.width = width + 'px';
  33483. newDomStyle.height = height + 'px';
  33484. newDom.setAttribute('data-zr-dom-id', id);
  33485. }
  33486. newDom.width = width * dpr;
  33487. newDom.height = height * dpr;
  33488. return newDom;
  33489. }
  33490. var Layer = (function (_super) {
  33491. __extends(Layer, _super);
  33492. function Layer(id, painter, dpr) {
  33493. var _this = _super.call(this) || this;
  33494. _this.motionBlur = false;
  33495. _this.lastFrameAlpha = 0.7;
  33496. _this.dpr = 1;
  33497. _this.virtual = false;
  33498. _this.config = {};
  33499. _this.incremental = false;
  33500. _this.zlevel = 0;
  33501. _this.maxRepaintRectCount = 5;
  33502. _this.__dirty = true;
  33503. _this.__firstTimePaint = true;
  33504. _this.__used = false;
  33505. _this.__drawIndex = 0;
  33506. _this.__startIndex = 0;
  33507. _this.__endIndex = 0;
  33508. _this.__prevStartIndex = null;
  33509. _this.__prevEndIndex = null;
  33510. var dom;
  33511. dpr = dpr || devicePixelRatio;
  33512. if (typeof id === 'string') {
  33513. dom = createDom(id, painter, dpr);
  33514. }
  33515. else if (isObject(id)) {
  33516. dom = id;
  33517. id = dom.id;
  33518. }
  33519. _this.id = id;
  33520. _this.dom = dom;
  33521. var domStyle = dom.style;
  33522. if (domStyle) {
  33523. dom.onselectstart = returnFalse;
  33524. domStyle.webkitUserSelect = 'none';
  33525. domStyle.userSelect = 'none';
  33526. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  33527. domStyle['-webkit-touch-callout'] = 'none';
  33528. domStyle.padding = '0';
  33529. domStyle.margin = '0';
  33530. domStyle.borderWidth = '0';
  33531. }
  33532. _this.domBack = null;
  33533. _this.ctxBack = null;
  33534. _this.painter = painter;
  33535. _this.config = null;
  33536. _this.dpr = dpr;
  33537. return _this;
  33538. }
  33539. Layer.prototype.getElementCount = function () {
  33540. return this.__endIndex - this.__startIndex;
  33541. };
  33542. Layer.prototype.afterBrush = function () {
  33543. this.__prevStartIndex = this.__startIndex;
  33544. this.__prevEndIndex = this.__endIndex;
  33545. };
  33546. Layer.prototype.initContext = function () {
  33547. this.ctx = this.dom.getContext('2d');
  33548. this.ctx.dpr = this.dpr;
  33549. };
  33550. Layer.prototype.setUnpainted = function () {
  33551. this.__firstTimePaint = true;
  33552. };
  33553. Layer.prototype.createBackBuffer = function () {
  33554. var dpr = this.dpr;
  33555. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  33556. this.ctxBack = this.domBack.getContext('2d');
  33557. if (dpr !== 1) {
  33558. this.ctxBack.scale(dpr, dpr);
  33559. }
  33560. };
  33561. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  33562. if (this.__firstTimePaint) {
  33563. this.__firstTimePaint = false;
  33564. return null;
  33565. }
  33566. var mergedRepaintRects = [];
  33567. var maxRepaintRectCount = this.maxRepaintRectCount;
  33568. var full = false;
  33569. var pendingRect = new BoundingRect(0, 0, 0, 0);
  33570. function addRectToMergePool(rect) {
  33571. if (!rect.isFinite() || rect.isZero()) {
  33572. return;
  33573. }
  33574. if (mergedRepaintRects.length === 0) {
  33575. var boundingRect = new BoundingRect(0, 0, 0, 0);
  33576. boundingRect.copy(rect);
  33577. mergedRepaintRects.push(boundingRect);
  33578. }
  33579. else {
  33580. var isMerged = false;
  33581. var minDeltaArea = Infinity;
  33582. var bestRectToMergeIdx = 0;
  33583. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  33584. var mergedRect = mergedRepaintRects[i];
  33585. if (mergedRect.intersect(rect)) {
  33586. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  33587. pendingRect_1.copy(mergedRect);
  33588. pendingRect_1.union(rect);
  33589. mergedRepaintRects[i] = pendingRect_1;
  33590. isMerged = true;
  33591. break;
  33592. }
  33593. else if (full) {
  33594. pendingRect.copy(rect);
  33595. pendingRect.union(mergedRect);
  33596. var aArea = rect.width * rect.height;
  33597. var bArea = mergedRect.width * mergedRect.height;
  33598. var pendingArea = pendingRect.width * pendingRect.height;
  33599. var deltaArea = pendingArea - aArea - bArea;
  33600. if (deltaArea < minDeltaArea) {
  33601. minDeltaArea = deltaArea;
  33602. bestRectToMergeIdx = i;
  33603. }
  33604. }
  33605. }
  33606. if (full) {
  33607. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  33608. isMerged = true;
  33609. }
  33610. if (!isMerged) {
  33611. var boundingRect = new BoundingRect(0, 0, 0, 0);
  33612. boundingRect.copy(rect);
  33613. mergedRepaintRects.push(boundingRect);
  33614. }
  33615. if (!full) {
  33616. full = mergedRepaintRects.length >= maxRepaintRectCount;
  33617. }
  33618. }
  33619. }
  33620. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  33621. var el = displayList[i];
  33622. if (el) {
  33623. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  33624. var prevRect = el.__isRendered && ((el.__dirty & Element.REDARAW_BIT) || !shouldPaint)
  33625. ? el.getPrevPaintRect()
  33626. : null;
  33627. if (prevRect) {
  33628. addRectToMergePool(prevRect);
  33629. }
  33630. var curRect = shouldPaint && ((el.__dirty & Element.REDARAW_BIT) || !el.__isRendered)
  33631. ? el.getPaintRect()
  33632. : null;
  33633. if (curRect) {
  33634. addRectToMergePool(curRect);
  33635. }
  33636. }
  33637. }
  33638. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  33639. var el = prevList[i];
  33640. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  33641. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  33642. var prevRect = el.getPrevPaintRect();
  33643. if (prevRect) {
  33644. addRectToMergePool(prevRect);
  33645. }
  33646. }
  33647. }
  33648. var hasIntersections;
  33649. do {
  33650. hasIntersections = false;
  33651. for (var i = 0; i < mergedRepaintRects.length;) {
  33652. if (mergedRepaintRects[i].isZero()) {
  33653. mergedRepaintRects.splice(i, 1);
  33654. continue;
  33655. }
  33656. for (var j = i + 1; j < mergedRepaintRects.length;) {
  33657. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  33658. hasIntersections = true;
  33659. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  33660. mergedRepaintRects.splice(j, 1);
  33661. }
  33662. else {
  33663. j++;
  33664. }
  33665. }
  33666. i++;
  33667. }
  33668. } while (hasIntersections);
  33669. this._paintRects = mergedRepaintRects;
  33670. return mergedRepaintRects;
  33671. };
  33672. Layer.prototype.debugGetPaintRects = function () {
  33673. return (this._paintRects || []).slice();
  33674. };
  33675. Layer.prototype.resize = function (width, height) {
  33676. var dpr = this.dpr;
  33677. var dom = this.dom;
  33678. var domStyle = dom.style;
  33679. var domBack = this.domBack;
  33680. if (domStyle) {
  33681. domStyle.width = width + 'px';
  33682. domStyle.height = height + 'px';
  33683. }
  33684. dom.width = width * dpr;
  33685. dom.height = height * dpr;
  33686. if (domBack) {
  33687. domBack.width = width * dpr;
  33688. domBack.height = height * dpr;
  33689. if (dpr !== 1) {
  33690. this.ctxBack.scale(dpr, dpr);
  33691. }
  33692. }
  33693. };
  33694. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  33695. var dom = this.dom;
  33696. var ctx = this.ctx;
  33697. var width = dom.width;
  33698. var height = dom.height;
  33699. clearColor = clearColor || this.clearColor;
  33700. var haveMotionBLur = this.motionBlur && !clearAll;
  33701. var lastFrameAlpha = this.lastFrameAlpha;
  33702. var dpr = this.dpr;
  33703. var self = this;
  33704. if (haveMotionBLur) {
  33705. if (!this.domBack) {
  33706. this.createBackBuffer();
  33707. }
  33708. this.ctxBack.globalCompositeOperation = 'copy';
  33709. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  33710. }
  33711. var domBack = this.domBack;
  33712. function doClear(x, y, width, height) {
  33713. ctx.clearRect(x, y, width, height);
  33714. if (clearColor && clearColor !== 'transparent') {
  33715. var clearColorGradientOrPattern = void 0;
  33716. if (isGradientObject(clearColor)) {
  33717. clearColorGradientOrPattern = clearColor.__canvasGradient
  33718. || getCanvasGradient(ctx, clearColor, {
  33719. x: 0,
  33720. y: 0,
  33721. width: width,
  33722. height: height
  33723. });
  33724. clearColor.__canvasGradient = clearColorGradientOrPattern;
  33725. }
  33726. else if (isPatternObject(clearColor)) {
  33727. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  33728. dirty: function () {
  33729. self.setUnpainted();
  33730. self.__painter.refresh();
  33731. }
  33732. });
  33733. }
  33734. ctx.save();
  33735. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  33736. ctx.fillRect(x, y, width, height);
  33737. ctx.restore();
  33738. }
  33739. if (haveMotionBLur) {
  33740. ctx.save();
  33741. ctx.globalAlpha = lastFrameAlpha;
  33742. ctx.drawImage(domBack, x, y, width, height);
  33743. ctx.restore();
  33744. }
  33745. }
  33746. if (!repaintRects || haveMotionBLur) {
  33747. doClear(0, 0, width, height);
  33748. }
  33749. else if (repaintRects.length) {
  33750. each(repaintRects, function (rect) {
  33751. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  33752. });
  33753. }
  33754. };
  33755. return Layer;
  33756. }(Eventful));
  33757. var HOVER_LAYER_ZLEVEL = 1e5;
  33758. var CANVAS_ZLEVEL = 314159;
  33759. var EL_AFTER_INCREMENTAL_INC = 0.01;
  33760. var INCREMENTAL_INC = 0.001;
  33761. function parseInt10$1(val) {
  33762. return parseInt(val, 10);
  33763. }
  33764. function isLayerValid(layer) {
  33765. if (!layer) {
  33766. return false;
  33767. }
  33768. if (layer.__builtin__) {
  33769. return true;
  33770. }
  33771. if (typeof (layer.resize) !== 'function'
  33772. || typeof (layer.refresh) !== 'function') {
  33773. return false;
  33774. }
  33775. return true;
  33776. }
  33777. function createRoot(width, height) {
  33778. var domRoot = document.createElement('div');
  33779. domRoot.style.cssText = [
  33780. 'position:relative',
  33781. 'width:' + width + 'px',
  33782. 'height:' + height + 'px',
  33783. 'padding:0',
  33784. 'margin:0',
  33785. 'border-width:0'
  33786. ].join(';') + ';';
  33787. return domRoot;
  33788. }
  33789. var CanvasPainter = (function () {
  33790. function CanvasPainter(root, storage, opts, id) {
  33791. this.type = 'canvas';
  33792. this._zlevelList = [];
  33793. this._prevDisplayList = [];
  33794. this._layers = {};
  33795. this._layerConfig = {};
  33796. this._needsManuallyCompositing = false;
  33797. this.type = 'canvas';
  33798. var singleCanvas = !root.nodeName
  33799. || root.nodeName.toUpperCase() === 'CANVAS';
  33800. this._opts = opts = extend({}, opts || {});
  33801. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  33802. this._singleCanvas = singleCanvas;
  33803. this.root = root;
  33804. var rootStyle = root.style;
  33805. if (rootStyle) {
  33806. rootStyle.webkitTapHighlightColor = 'transparent';
  33807. rootStyle.webkitUserSelect = 'none';
  33808. rootStyle.userSelect = 'none';
  33809. rootStyle['-webkit-touch-callout'] = 'none';
  33810. root.innerHTML = '';
  33811. }
  33812. this.storage = storage;
  33813. var zlevelList = this._zlevelList;
  33814. this._prevDisplayList = [];
  33815. var layers = this._layers;
  33816. if (!singleCanvas) {
  33817. this._width = this._getSize(0);
  33818. this._height = this._getSize(1);
  33819. var domRoot = this._domRoot = createRoot(this._width, this._height);
  33820. root.appendChild(domRoot);
  33821. }
  33822. else {
  33823. var rootCanvas = root;
  33824. var width = rootCanvas.width;
  33825. var height = rootCanvas.height;
  33826. if (opts.width != null) {
  33827. width = opts.width;
  33828. }
  33829. if (opts.height != null) {
  33830. height = opts.height;
  33831. }
  33832. this.dpr = opts.devicePixelRatio || 1;
  33833. rootCanvas.width = width * this.dpr;
  33834. rootCanvas.height = height * this.dpr;
  33835. this._width = width;
  33836. this._height = height;
  33837. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  33838. mainLayer.__builtin__ = true;
  33839. mainLayer.initContext();
  33840. layers[CANVAS_ZLEVEL] = mainLayer;
  33841. mainLayer.zlevel = CANVAS_ZLEVEL;
  33842. zlevelList.push(CANVAS_ZLEVEL);
  33843. this._domRoot = root;
  33844. }
  33845. }
  33846. CanvasPainter.prototype.getType = function () {
  33847. return 'canvas';
  33848. };
  33849. CanvasPainter.prototype.isSingleCanvas = function () {
  33850. return this._singleCanvas;
  33851. };
  33852. CanvasPainter.prototype.getViewportRoot = function () {
  33853. return this._domRoot;
  33854. };
  33855. CanvasPainter.prototype.getViewportRootOffset = function () {
  33856. var viewportRoot = this.getViewportRoot();
  33857. if (viewportRoot) {
  33858. return {
  33859. offsetLeft: viewportRoot.offsetLeft || 0,
  33860. offsetTop: viewportRoot.offsetTop || 0
  33861. };
  33862. }
  33863. };
  33864. CanvasPainter.prototype.refresh = function (paintAll) {
  33865. var list = this.storage.getDisplayList(true);
  33866. var prevList = this._prevDisplayList;
  33867. var zlevelList = this._zlevelList;
  33868. this._redrawId = Math.random();
  33869. this._paintList(list, prevList, paintAll, this._redrawId);
  33870. for (var i = 0; i < zlevelList.length; i++) {
  33871. var z = zlevelList[i];
  33872. var layer = this._layers[z];
  33873. if (!layer.__builtin__ && layer.refresh) {
  33874. var clearColor = i === 0 ? this._backgroundColor : null;
  33875. layer.refresh(clearColor);
  33876. }
  33877. }
  33878. if (this._opts.useDirtyRect) {
  33879. this._prevDisplayList = list.slice();
  33880. }
  33881. return this;
  33882. };
  33883. CanvasPainter.prototype.refreshHover = function () {
  33884. this._paintHoverList(this.storage.getDisplayList(false));
  33885. };
  33886. CanvasPainter.prototype._paintHoverList = function (list) {
  33887. var len = list.length;
  33888. var hoverLayer = this._hoverlayer;
  33889. hoverLayer && hoverLayer.clear();
  33890. if (!len) {
  33891. return;
  33892. }
  33893. var scope = {
  33894. inHover: true,
  33895. viewWidth: this._width,
  33896. viewHeight: this._height
  33897. };
  33898. var ctx;
  33899. for (var i = 0; i < len; i++) {
  33900. var el = list[i];
  33901. if (el.__inHover) {
  33902. if (!hoverLayer) {
  33903. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  33904. }
  33905. if (!ctx) {
  33906. ctx = hoverLayer.ctx;
  33907. ctx.save();
  33908. }
  33909. brush(ctx, el, scope, i === len - 1);
  33910. }
  33911. }
  33912. if (ctx) {
  33913. ctx.restore();
  33914. }
  33915. };
  33916. CanvasPainter.prototype.getHoverLayer = function () {
  33917. return this.getLayer(HOVER_LAYER_ZLEVEL);
  33918. };
  33919. CanvasPainter.prototype.paintOne = function (ctx, el) {
  33920. brushSingle(ctx, el);
  33921. };
  33922. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  33923. if (this._redrawId !== redrawId) {
  33924. return;
  33925. }
  33926. paintAll = paintAll || false;
  33927. this._updateLayerStatus(list);
  33928. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  33929. if (this._needsManuallyCompositing) {
  33930. this._compositeManually();
  33931. }
  33932. if (needsRefreshHover) {
  33933. this._paintHoverList(list);
  33934. }
  33935. if (!finished) {
  33936. var self_1 = this;
  33937. requestAnimationFrame$1(function () {
  33938. self_1._paintList(list, prevList, paintAll, redrawId);
  33939. });
  33940. }
  33941. else {
  33942. this.eachLayer(function (layer) {
  33943. layer.afterBrush && layer.afterBrush();
  33944. });
  33945. }
  33946. };
  33947. CanvasPainter.prototype._compositeManually = function () {
  33948. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  33949. var width = this._domRoot.width;
  33950. var height = this._domRoot.height;
  33951. ctx.clearRect(0, 0, width, height);
  33952. this.eachBuiltinLayer(function (layer) {
  33953. if (layer.virtual) {
  33954. ctx.drawImage(layer.dom, 0, 0, width, height);
  33955. }
  33956. });
  33957. };
  33958. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  33959. var _this = this;
  33960. var layerList = [];
  33961. var useDirtyRect = this._opts.useDirtyRect;
  33962. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  33963. var zlevel = this._zlevelList[zi];
  33964. var layer = this._layers[zlevel];
  33965. if (layer.__builtin__
  33966. && layer !== this._hoverlayer
  33967. && (layer.__dirty || paintAll)) {
  33968. layerList.push(layer);
  33969. }
  33970. }
  33971. var finished = true;
  33972. var needsRefreshHover = false;
  33973. var _loop_1 = function (k) {
  33974. var layer = layerList[k];
  33975. var ctx = layer.ctx;
  33976. var repaintRects = useDirtyRect
  33977. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  33978. ctx.save();
  33979. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  33980. var useTimer = !paintAll && layer.incremental && Date.now;
  33981. var startTime = useTimer && Date.now();
  33982. var clearColor = layer.zlevel === this_1._zlevelList[0]
  33983. ? this_1._backgroundColor : null;
  33984. if (layer.__startIndex === layer.__endIndex) {
  33985. layer.clear(false, clearColor, repaintRects);
  33986. }
  33987. else if (start === layer.__startIndex) {
  33988. var firstEl = list[start];
  33989. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  33990. layer.clear(false, clearColor, repaintRects);
  33991. }
  33992. }
  33993. if (start === -1) {
  33994. console.error('For some unknown reason. drawIndex is -1');
  33995. start = layer.__startIndex;
  33996. }
  33997. var i;
  33998. var repaint = function (repaintRect) {
  33999. var scope = {
  34000. inHover: false,
  34001. allClipped: false,
  34002. prevEl: null,
  34003. viewWidth: _this._width,
  34004. viewHeight: _this._height
  34005. };
  34006. for (i = start; i < layer.__endIndex; i++) {
  34007. var el = list[i];
  34008. if (el.__inHover) {
  34009. needsRefreshHover = true;
  34010. }
  34011. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  34012. if (useTimer) {
  34013. var dTime = Date.now() - startTime;
  34014. if (dTime > 15) {
  34015. break;
  34016. }
  34017. }
  34018. }
  34019. if (scope.prevElClipPaths) {
  34020. ctx.restore();
  34021. }
  34022. };
  34023. if (repaintRects) {
  34024. if (repaintRects.length === 0) {
  34025. i = layer.__endIndex;
  34026. }
  34027. else {
  34028. var dpr = this_1.dpr;
  34029. for (var r = 0; r < repaintRects.length; ++r) {
  34030. var rect = repaintRects[r];
  34031. ctx.save();
  34032. ctx.beginPath();
  34033. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  34034. ctx.clip();
  34035. repaint(rect);
  34036. ctx.restore();
  34037. }
  34038. }
  34039. }
  34040. else {
  34041. ctx.save();
  34042. repaint();
  34043. ctx.restore();
  34044. }
  34045. layer.__drawIndex = i;
  34046. if (layer.__drawIndex < layer.__endIndex) {
  34047. finished = false;
  34048. }
  34049. };
  34050. var this_1 = this;
  34051. for (var k = 0; k < layerList.length; k++) {
  34052. _loop_1(k);
  34053. }
  34054. if (env.wxa) {
  34055. each(this._layers, function (layer) {
  34056. if (layer && layer.ctx && layer.ctx.draw) {
  34057. layer.ctx.draw();
  34058. }
  34059. });
  34060. }
  34061. return {
  34062. finished: finished,
  34063. needsRefreshHover: needsRefreshHover
  34064. };
  34065. };
  34066. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  34067. var ctx = currentLayer.ctx;
  34068. if (useDirtyRect) {
  34069. var paintRect = el.getPaintRect();
  34070. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  34071. brush(ctx, el, scope, isLast);
  34072. el.setPrevPaintRect(paintRect);
  34073. }
  34074. }
  34075. else {
  34076. brush(ctx, el, scope, isLast);
  34077. }
  34078. };
  34079. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  34080. if (this._singleCanvas && !this._needsManuallyCompositing) {
  34081. zlevel = CANVAS_ZLEVEL;
  34082. }
  34083. var layer = this._layers[zlevel];
  34084. if (!layer) {
  34085. layer = new Layer('zr_' + zlevel, this, this.dpr);
  34086. layer.zlevel = zlevel;
  34087. layer.__builtin__ = true;
  34088. if (this._layerConfig[zlevel]) {
  34089. merge(layer, this._layerConfig[zlevel], true);
  34090. }
  34091. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  34092. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  34093. }
  34094. if (virtual) {
  34095. layer.virtual = virtual;
  34096. }
  34097. this.insertLayer(zlevel, layer);
  34098. layer.initContext();
  34099. }
  34100. return layer;
  34101. };
  34102. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  34103. var layersMap = this._layers;
  34104. var zlevelList = this._zlevelList;
  34105. var len = zlevelList.length;
  34106. var domRoot = this._domRoot;
  34107. var prevLayer = null;
  34108. var i = -1;
  34109. if (layersMap[zlevel]) {
  34110. logError('ZLevel ' + zlevel + ' has been used already');
  34111. return;
  34112. }
  34113. if (!isLayerValid(layer)) {
  34114. logError('Layer of zlevel ' + zlevel + ' is not valid');
  34115. return;
  34116. }
  34117. if (len > 0 && zlevel > zlevelList[0]) {
  34118. for (i = 0; i < len - 1; i++) {
  34119. if (zlevelList[i] < zlevel
  34120. && zlevelList[i + 1] > zlevel) {
  34121. break;
  34122. }
  34123. }
  34124. prevLayer = layersMap[zlevelList[i]];
  34125. }
  34126. zlevelList.splice(i + 1, 0, zlevel);
  34127. layersMap[zlevel] = layer;
  34128. if (!layer.virtual) {
  34129. if (prevLayer) {
  34130. var prevDom = prevLayer.dom;
  34131. if (prevDom.nextSibling) {
  34132. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  34133. }
  34134. else {
  34135. domRoot.appendChild(layer.dom);
  34136. }
  34137. }
  34138. else {
  34139. if (domRoot.firstChild) {
  34140. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  34141. }
  34142. else {
  34143. domRoot.appendChild(layer.dom);
  34144. }
  34145. }
  34146. }
  34147. layer.__painter = this;
  34148. };
  34149. CanvasPainter.prototype.eachLayer = function (cb, context) {
  34150. var zlevelList = this._zlevelList;
  34151. for (var i = 0; i < zlevelList.length; i++) {
  34152. var z = zlevelList[i];
  34153. cb.call(context, this._layers[z], z);
  34154. }
  34155. };
  34156. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  34157. var zlevelList = this._zlevelList;
  34158. for (var i = 0; i < zlevelList.length; i++) {
  34159. var z = zlevelList[i];
  34160. var layer = this._layers[z];
  34161. if (layer.__builtin__) {
  34162. cb.call(context, layer, z);
  34163. }
  34164. }
  34165. };
  34166. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  34167. var zlevelList = this._zlevelList;
  34168. for (var i = 0; i < zlevelList.length; i++) {
  34169. var z = zlevelList[i];
  34170. var layer = this._layers[z];
  34171. if (!layer.__builtin__) {
  34172. cb.call(context, layer, z);
  34173. }
  34174. }
  34175. };
  34176. CanvasPainter.prototype.getLayers = function () {
  34177. return this._layers;
  34178. };
  34179. CanvasPainter.prototype._updateLayerStatus = function (list) {
  34180. this.eachBuiltinLayer(function (layer, z) {
  34181. layer.__dirty = layer.__used = false;
  34182. });
  34183. function updatePrevLayer(idx) {
  34184. if (prevLayer) {
  34185. if (prevLayer.__endIndex !== idx) {
  34186. prevLayer.__dirty = true;
  34187. }
  34188. prevLayer.__endIndex = idx;
  34189. }
  34190. }
  34191. if (this._singleCanvas) {
  34192. for (var i_1 = 1; i_1 < list.length; i_1++) {
  34193. var el = list[i_1];
  34194. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  34195. this._needsManuallyCompositing = true;
  34196. break;
  34197. }
  34198. }
  34199. }
  34200. var prevLayer = null;
  34201. var incrementalLayerCount = 0;
  34202. var prevZlevel;
  34203. var i;
  34204. for (i = 0; i < list.length; i++) {
  34205. var el = list[i];
  34206. var zlevel = el.zlevel;
  34207. var layer = void 0;
  34208. if (prevZlevel !== zlevel) {
  34209. prevZlevel = zlevel;
  34210. incrementalLayerCount = 0;
  34211. }
  34212. if (el.incremental) {
  34213. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  34214. layer.incremental = true;
  34215. incrementalLayerCount = 1;
  34216. }
  34217. else {
  34218. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  34219. }
  34220. if (!layer.__builtin__) {
  34221. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  34222. }
  34223. if (layer !== prevLayer) {
  34224. layer.__used = true;
  34225. if (layer.__startIndex !== i) {
  34226. layer.__dirty = true;
  34227. }
  34228. layer.__startIndex = i;
  34229. if (!layer.incremental) {
  34230. layer.__drawIndex = i;
  34231. }
  34232. else {
  34233. layer.__drawIndex = -1;
  34234. }
  34235. updatePrevLayer(i);
  34236. prevLayer = layer;
  34237. }
  34238. if ((el.__dirty & Element.REDARAW_BIT) && !el.__inHover) {
  34239. layer.__dirty = true;
  34240. if (layer.incremental && layer.__drawIndex < 0) {
  34241. layer.__drawIndex = i;
  34242. }
  34243. }
  34244. }
  34245. updatePrevLayer(i);
  34246. this.eachBuiltinLayer(function (layer, z) {
  34247. if (!layer.__used && layer.getElementCount() > 0) {
  34248. layer.__dirty = true;
  34249. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  34250. }
  34251. if (layer.__dirty && layer.__drawIndex < 0) {
  34252. layer.__drawIndex = layer.__startIndex;
  34253. }
  34254. });
  34255. };
  34256. CanvasPainter.prototype.clear = function () {
  34257. this.eachBuiltinLayer(this._clearLayer);
  34258. return this;
  34259. };
  34260. CanvasPainter.prototype._clearLayer = function (layer) {
  34261. layer.clear();
  34262. };
  34263. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  34264. this._backgroundColor = backgroundColor;
  34265. each(this._layers, function (layer) {
  34266. layer.setUnpainted();
  34267. });
  34268. };
  34269. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  34270. if (config) {
  34271. var layerConfig = this._layerConfig;
  34272. if (!layerConfig[zlevel]) {
  34273. layerConfig[zlevel] = config;
  34274. }
  34275. else {
  34276. merge(layerConfig[zlevel], config, true);
  34277. }
  34278. for (var i = 0; i < this._zlevelList.length; i++) {
  34279. var _zlevel = this._zlevelList[i];
  34280. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  34281. var layer = this._layers[_zlevel];
  34282. merge(layer, layerConfig[zlevel], true);
  34283. }
  34284. }
  34285. }
  34286. };
  34287. CanvasPainter.prototype.delLayer = function (zlevel) {
  34288. var layers = this._layers;
  34289. var zlevelList = this._zlevelList;
  34290. var layer = layers[zlevel];
  34291. if (!layer) {
  34292. return;
  34293. }
  34294. layer.dom.parentNode.removeChild(layer.dom);
  34295. delete layers[zlevel];
  34296. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  34297. };
  34298. CanvasPainter.prototype.resize = function (width, height) {
  34299. if (!this._domRoot.style) {
  34300. if (width == null || height == null) {
  34301. return;
  34302. }
  34303. this._width = width;
  34304. this._height = height;
  34305. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  34306. }
  34307. else {
  34308. var domRoot = this._domRoot;
  34309. domRoot.style.display = 'none';
  34310. var opts = this._opts;
  34311. width != null && (opts.width = width);
  34312. height != null && (opts.height = height);
  34313. width = this._getSize(0);
  34314. height = this._getSize(1);
  34315. domRoot.style.display = '';
  34316. if (this._width !== width || height !== this._height) {
  34317. domRoot.style.width = width + 'px';
  34318. domRoot.style.height = height + 'px';
  34319. for (var id in this._layers) {
  34320. if (this._layers.hasOwnProperty(id)) {
  34321. this._layers[id].resize(width, height);
  34322. }
  34323. }
  34324. this.refresh(true);
  34325. }
  34326. this._width = width;
  34327. this._height = height;
  34328. }
  34329. return this;
  34330. };
  34331. CanvasPainter.prototype.clearLayer = function (zlevel) {
  34332. var layer = this._layers[zlevel];
  34333. if (layer) {
  34334. layer.clear();
  34335. }
  34336. };
  34337. CanvasPainter.prototype.dispose = function () {
  34338. this.root.innerHTML = '';
  34339. this.root =
  34340. this.storage =
  34341. this._domRoot =
  34342. this._layers = null;
  34343. };
  34344. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  34345. opts = opts || {};
  34346. if (this._singleCanvas && !this._compositeManually) {
  34347. return this._layers[CANVAS_ZLEVEL].dom;
  34348. }
  34349. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  34350. imageLayer.initContext();
  34351. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  34352. var ctx = imageLayer.ctx;
  34353. if (opts.pixelRatio <= this.dpr) {
  34354. this.refresh();
  34355. var width_1 = imageLayer.dom.width;
  34356. var height_1 = imageLayer.dom.height;
  34357. this.eachLayer(function (layer) {
  34358. if (layer.__builtin__) {
  34359. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  34360. }
  34361. else if (layer.renderToCanvas) {
  34362. ctx.save();
  34363. layer.renderToCanvas(ctx);
  34364. ctx.restore();
  34365. }
  34366. });
  34367. }
  34368. else {
  34369. var scope = {
  34370. inHover: false,
  34371. viewWidth: this._width,
  34372. viewHeight: this._height
  34373. };
  34374. var displayList = this.storage.getDisplayList(true);
  34375. for (var i = 0, len = displayList.length; i < len; i++) {
  34376. var el = displayList[i];
  34377. brush(ctx, el, scope, i === len - 1);
  34378. }
  34379. }
  34380. return imageLayer.dom;
  34381. };
  34382. CanvasPainter.prototype.getWidth = function () {
  34383. return this._width;
  34384. };
  34385. CanvasPainter.prototype.getHeight = function () {
  34386. return this._height;
  34387. };
  34388. CanvasPainter.prototype._getSize = function (whIdx) {
  34389. var opts = this._opts;
  34390. var wh = ['width', 'height'][whIdx];
  34391. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  34392. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  34393. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  34394. if (opts[wh] != null && opts[wh] !== 'auto') {
  34395. return parseFloat(opts[wh]);
  34396. }
  34397. var root = this.root;
  34398. var stl = document.defaultView.getComputedStyle(root);
  34399. return ((root[cwh] || parseInt10$1(stl[wh]) || parseInt10$1(root.style[wh]))
  34400. - (parseInt10$1(stl[plt]) || 0)
  34401. - (parseInt10$1(stl[prb]) || 0)) | 0;
  34402. };
  34403. CanvasPainter.prototype.pathToImage = function (path, dpr) {
  34404. dpr = dpr || this.dpr;
  34405. var canvas = document.createElement('canvas');
  34406. var ctx = canvas.getContext('2d');
  34407. var rect = path.getBoundingRect();
  34408. var style = path.style;
  34409. var shadowBlurSize = style.shadowBlur * dpr;
  34410. var shadowOffsetX = style.shadowOffsetX * dpr;
  34411. var shadowOffsetY = style.shadowOffsetY * dpr;
  34412. var lineWidth = path.hasStroke() ? style.lineWidth : 0;
  34413. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  34414. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  34415. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  34416. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  34417. var width = rect.width + leftMargin + rightMargin;
  34418. var height = rect.height + topMargin + bottomMargin;
  34419. canvas.width = width * dpr;
  34420. canvas.height = height * dpr;
  34421. ctx.scale(dpr, dpr);
  34422. ctx.clearRect(0, 0, width, height);
  34423. ctx.dpr = dpr;
  34424. var pathTransform = {
  34425. x: path.x,
  34426. y: path.y,
  34427. scaleX: path.scaleX,
  34428. scaleY: path.scaleY,
  34429. rotation: path.rotation,
  34430. originX: path.originX,
  34431. originY: path.originY
  34432. };
  34433. path.x = leftMargin - rect.x;
  34434. path.y = topMargin - rect.y;
  34435. path.rotation = 0;
  34436. path.scaleX = 1;
  34437. path.scaleY = 1;
  34438. path.updateTransform();
  34439. if (path) {
  34440. brush(ctx, path, {
  34441. inHover: false,
  34442. viewWidth: this._width,
  34443. viewHeight: this._height
  34444. }, true);
  34445. }
  34446. var imgShape = new ZRImage({
  34447. style: {
  34448. x: 0,
  34449. y: 0,
  34450. image: canvas
  34451. }
  34452. });
  34453. extend(path, pathTransform);
  34454. return imgShape;
  34455. };
  34456. return CanvasPainter;
  34457. }());
  34458. function install$1(registers) {
  34459. registers.registerPainter('canvas', CanvasPainter);
  34460. }
  34461. var LineSeriesModel =
  34462. /** @class */
  34463. function (_super) {
  34464. __extends(LineSeriesModel, _super);
  34465. function LineSeriesModel() {
  34466. var _this = _super !== null && _super.apply(this, arguments) || this;
  34467. _this.type = LineSeriesModel.type;
  34468. _this.hasSymbolVisual = true;
  34469. _this.legendSymbol = 'line';
  34470. return _this;
  34471. }
  34472. LineSeriesModel.prototype.getInitialData = function (option) {
  34473. if ("development" !== 'production') {
  34474. var coordSys = option.coordinateSystem;
  34475. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  34476. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  34477. }
  34478. }
  34479. return createListFromArray(this.getSource(), this, {
  34480. useEncodeDefaulter: true
  34481. });
  34482. };
  34483. LineSeriesModel.type = 'series.line';
  34484. LineSeriesModel.dependencies = ['grid', 'polar'];
  34485. LineSeriesModel.defaultOption = {
  34486. zlevel: 0,
  34487. z: 3,
  34488. coordinateSystem: 'cartesian2d',
  34489. legendHoverLink: true,
  34490. clip: true,
  34491. label: {
  34492. position: 'top'
  34493. },
  34494. endLabel: {
  34495. show: false,
  34496. valueAnimation: true,
  34497. distance: 8
  34498. },
  34499. lineStyle: {
  34500. width: 2,
  34501. type: 'solid'
  34502. },
  34503. emphasis: {
  34504. scale: true,
  34505. lineStyle: {
  34506. width: 'bolder'
  34507. }
  34508. },
  34509. // areaStyle: {
  34510. // origin of areaStyle. Valid values:
  34511. // `'auto'/null/undefined`: from axisLine to data
  34512. // `'start'`: from min to data
  34513. // `'end'`: from data to max
  34514. // origin: 'auto'
  34515. // },
  34516. // false, 'start', 'end', 'middle'
  34517. step: false,
  34518. // Disabled if step is true
  34519. smooth: false,
  34520. smoothMonotone: null,
  34521. symbol: 'emptyCircle',
  34522. symbolSize: 4,
  34523. symbolRotate: null,
  34524. showSymbol: true,
  34525. // `false`: follow the label interval strategy.
  34526. // `true`: show all symbols.
  34527. // `'auto'`: If possible, show all symbols, otherwise
  34528. // follow the label interval strategy.
  34529. showAllSymbol: 'auto',
  34530. // Whether to connect break point.
  34531. connectNulls: false,
  34532. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  34533. sampling: 'none',
  34534. animationEasing: 'linear',
  34535. // Disable progressive
  34536. progressive: 0,
  34537. hoverLayerThreshold: Infinity
  34538. };
  34539. return LineSeriesModel;
  34540. }(SeriesModel);
  34541. /**
  34542. * @return label string. Not null/undefined
  34543. */
  34544. function getDefaultLabel(data, dataIndex) {
  34545. var labelDims = data.mapDimensionsAll('defaultedLabel');
  34546. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  34547. if (len === 1) {
  34548. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  34549. return rawVal != null ? rawVal + '' : null;
  34550. } else if (len) {
  34551. var vals = [];
  34552. for (var i = 0; i < labelDims.length; i++) {
  34553. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  34554. }
  34555. return vals.join(' ');
  34556. }
  34557. }
  34558. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  34559. var labelDims = data.mapDimensionsAll('defaultedLabel');
  34560. if (!isArray(interpolatedValue)) {
  34561. return interpolatedValue + '';
  34562. }
  34563. var vals = [];
  34564. for (var i = 0; i < labelDims.length; i++) {
  34565. var dimInfo = data.getDimensionInfo(labelDims[i]);
  34566. if (dimInfo) {
  34567. vals.push(interpolatedValue[dimInfo.index]);
  34568. }
  34569. }
  34570. return vals.join(' ');
  34571. }
  34572. var Symbol =
  34573. /** @class */
  34574. function (_super) {
  34575. __extends(Symbol, _super);
  34576. function Symbol(data, idx, seriesScope, opts) {
  34577. var _this = _super.call(this) || this;
  34578. _this.updateData(data, idx, seriesScope, opts);
  34579. return _this;
  34580. }
  34581. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  34582. // Remove paths created before
  34583. this.removeAll(); // let symbolPath = createSymbol(
  34584. // symbolType, -0.5, -0.5, 1, 1, color
  34585. // );
  34586. // If width/height are set too small (e.g., set to 1) on ios10
  34587. // and macOS Sierra, a circle stroke become a rect, no matter what
  34588. // the scale is set. So we set width/height as 2. See #4150.
  34589. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  34590. symbolPath.attr({
  34591. z2: 100,
  34592. culling: true,
  34593. scaleX: symbolSize[0] / 2,
  34594. scaleY: symbolSize[1] / 2
  34595. }); // Rewrite drift method
  34596. symbolPath.drift = driftSymbol;
  34597. this._symbolType = symbolType;
  34598. this.add(symbolPath);
  34599. };
  34600. /**
  34601. * Stop animation
  34602. * @param {boolean} toLastFrame
  34603. */
  34604. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  34605. this.childAt(0).stopAnimation(null, toLastFrame);
  34606. };
  34607. /**
  34608. * FIXME:
  34609. * Caution: This method breaks the encapsulation of this module,
  34610. * but it indeed brings convenience. So do not use the method
  34611. * unless you detailedly know all the implements of `Symbol`,
  34612. * especially animation.
  34613. *
  34614. * Get symbol path element.
  34615. */
  34616. Symbol.prototype.getSymbolPath = function () {
  34617. return this.childAt(0);
  34618. };
  34619. /**
  34620. * Highlight symbol
  34621. */
  34622. Symbol.prototype.highlight = function () {
  34623. enterEmphasis(this.childAt(0));
  34624. };
  34625. /**
  34626. * Downplay symbol
  34627. */
  34628. Symbol.prototype.downplay = function () {
  34629. leaveEmphasis(this.childAt(0));
  34630. };
  34631. /**
  34632. * @param {number} zlevel
  34633. * @param {number} z
  34634. */
  34635. Symbol.prototype.setZ = function (zlevel, z) {
  34636. var symbolPath = this.childAt(0);
  34637. symbolPath.zlevel = zlevel;
  34638. symbolPath.z = z;
  34639. };
  34640. Symbol.prototype.setDraggable = function (draggable) {
  34641. var symbolPath = this.childAt(0);
  34642. symbolPath.draggable = draggable;
  34643. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  34644. };
  34645. /**
  34646. * Update symbol properties
  34647. */
  34648. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  34649. this.silent = false;
  34650. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  34651. var seriesModel = data.hostModel;
  34652. var symbolSize = Symbol.getSymbolSize(data, idx);
  34653. var isInit = symbolType !== this._symbolType;
  34654. var disableAnimation = opts && opts.disableAnimation;
  34655. if (isInit) {
  34656. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  34657. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  34658. } else {
  34659. var symbolPath = this.childAt(0);
  34660. symbolPath.silent = false;
  34661. var target = {
  34662. scaleX: symbolSize[0] / 2,
  34663. scaleY: symbolSize[1] / 2
  34664. };
  34665. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  34666. }
  34667. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  34668. if (isInit) {
  34669. var symbolPath = this.childAt(0);
  34670. if (!disableAnimation) {
  34671. var target = {
  34672. scaleX: this._sizeX,
  34673. scaleY: this._sizeY,
  34674. style: {
  34675. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  34676. opacity: symbolPath.style.opacity
  34677. }
  34678. };
  34679. symbolPath.scaleX = symbolPath.scaleY = 0;
  34680. symbolPath.style.opacity = 0;
  34681. initProps(symbolPath, target, seriesModel, idx);
  34682. }
  34683. }
  34684. if (disableAnimation) {
  34685. // Must stop remove animation manually if don't call initProps or updateProps.
  34686. this.childAt(0).stopAnimation('remove');
  34687. }
  34688. this._seriesModel = seriesModel;
  34689. };
  34690. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  34691. var symbolPath = this.childAt(0);
  34692. var seriesModel = data.hostModel;
  34693. var emphasisItemStyle;
  34694. var blurItemStyle;
  34695. var selectItemStyle;
  34696. var focus;
  34697. var blurScope;
  34698. var symbolOffset;
  34699. var labelStatesModels;
  34700. var hoverScale;
  34701. var cursorStyle;
  34702. if (seriesScope) {
  34703. emphasisItemStyle = seriesScope.emphasisItemStyle;
  34704. blurItemStyle = seriesScope.blurItemStyle;
  34705. selectItemStyle = seriesScope.selectItemStyle;
  34706. focus = seriesScope.focus;
  34707. blurScope = seriesScope.blurScope;
  34708. symbolOffset = seriesScope.symbolOffset;
  34709. labelStatesModels = seriesScope.labelStatesModels;
  34710. hoverScale = seriesScope.hoverScale;
  34711. cursorStyle = seriesScope.cursorStyle;
  34712. }
  34713. if (!seriesScope || data.hasItemOption) {
  34714. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  34715. var emphasisModel = itemModel.getModel('emphasis');
  34716. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  34717. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  34718. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  34719. focus = emphasisModel.get('focus');
  34720. blurScope = emphasisModel.get('blurScope');
  34721. symbolOffset = itemModel.getShallow('symbolOffset');
  34722. labelStatesModels = getLabelStatesModels(itemModel);
  34723. hoverScale = emphasisModel.getShallow('scale');
  34724. cursorStyle = itemModel.getShallow('cursor');
  34725. }
  34726. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  34727. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  34728. if (symbolOffset) {
  34729. symbolPath.x = parsePercent$1(symbolOffset[0], symbolSize[0]);
  34730. symbolPath.y = parsePercent$1(symbolOffset[1], symbolSize[1]);
  34731. }
  34732. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  34733. var symbolStyle = data.getItemVisual(idx, 'style');
  34734. var visualColor = symbolStyle.fill;
  34735. if (symbolPath instanceof ZRImage) {
  34736. var pathStyle = symbolPath.style;
  34737. symbolPath.useStyle(extend({
  34738. // TODO other properties like x, y ?
  34739. image: pathStyle.image,
  34740. x: pathStyle.x,
  34741. y: pathStyle.y,
  34742. width: pathStyle.width,
  34743. height: pathStyle.height
  34744. }, symbolStyle));
  34745. } else {
  34746. if (symbolPath.__isEmptyBrush) {
  34747. // fill and stroke will be swapped if it's empty.
  34748. // So we cloned a new style to avoid it affecting the original style in visual storage.
  34749. // TODO Better implementation. No empty logic!
  34750. symbolPath.useStyle(extend({}, symbolStyle));
  34751. } else {
  34752. symbolPath.useStyle(symbolStyle);
  34753. } // Disable decal because symbol scale will been applied on the decal.
  34754. symbolPath.style.decal = null;
  34755. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  34756. symbolPath.style.strokeNoScale = true;
  34757. }
  34758. var liftZ = data.getItemVisual(idx, 'liftZ');
  34759. var z2Origin = this._z2;
  34760. if (liftZ != null) {
  34761. if (z2Origin == null) {
  34762. this._z2 = symbolPath.z2;
  34763. symbolPath.z2 += liftZ;
  34764. }
  34765. } else if (z2Origin != null) {
  34766. symbolPath.z2 = z2Origin;
  34767. this._z2 = null;
  34768. }
  34769. var useNameLabel = opts && opts.useNameLabel;
  34770. setLabelStyle(symbolPath, labelStatesModels, {
  34771. labelFetcher: seriesModel,
  34772. labelDataIndex: idx,
  34773. defaultText: getLabelDefaultText,
  34774. inheritColor: visualColor,
  34775. defaultOpacity: symbolStyle.opacity
  34776. }); // Do not execute util needed.
  34777. function getLabelDefaultText(idx) {
  34778. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  34779. }
  34780. this._sizeX = symbolSize[0] / 2;
  34781. this._sizeY = symbolSize[1] / 2;
  34782. var emphasisState = symbolPath.ensureState('emphasis');
  34783. emphasisState.style = emphasisItemStyle;
  34784. symbolPath.ensureState('select').style = selectItemStyle;
  34785. symbolPath.ensureState('blur').style = blurItemStyle;
  34786. if (hoverScale) {
  34787. var scaleRatio = Math.max(1.1, 3 / this._sizeY);
  34788. emphasisState.scaleX = this._sizeX * scaleRatio;
  34789. emphasisState.scaleY = this._sizeY * scaleRatio;
  34790. }
  34791. this.setSymbolScale(1);
  34792. enableHoverEmphasis(this, focus, blurScope);
  34793. };
  34794. Symbol.prototype.setSymbolScale = function (scale) {
  34795. this.scaleX = this.scaleY = scale;
  34796. };
  34797. Symbol.prototype.fadeOut = function (cb, opt) {
  34798. var symbolPath = this.childAt(0);
  34799. var seriesModel = this._seriesModel;
  34800. var dataIndex = getECData(this).dataIndex;
  34801. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  34802. this.silent = symbolPath.silent = true; // Not show text when animating
  34803. if (opt && opt.fadeLabel) {
  34804. var textContent = symbolPath.getTextContent();
  34805. if (textContent) {
  34806. removeElement(textContent, {
  34807. style: {
  34808. opacity: 0
  34809. }
  34810. }, seriesModel, {
  34811. dataIndex: dataIndex,
  34812. removeOpt: animationOpt,
  34813. cb: function () {
  34814. symbolPath.removeTextContent();
  34815. }
  34816. });
  34817. }
  34818. } else {
  34819. symbolPath.removeTextContent();
  34820. }
  34821. removeElement(symbolPath, {
  34822. style: {
  34823. opacity: 0
  34824. },
  34825. scaleX: 0,
  34826. scaleY: 0
  34827. }, seriesModel, {
  34828. dataIndex: dataIndex,
  34829. cb: cb,
  34830. removeOpt: animationOpt
  34831. });
  34832. };
  34833. Symbol.getSymbolSize = function (data, idx) {
  34834. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  34835. return symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize];
  34836. };
  34837. return Symbol;
  34838. }(Group);
  34839. function driftSymbol(dx, dy) {
  34840. this.parent.drift(dx, dy);
  34841. }
  34842. function symbolNeedsDraw(data, point, idx, opt) {
  34843. 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
  34844. // the symbol element shape. We use the same clip shape here as
  34845. // the line clip.
  34846. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  34847. }
  34848. function normalizeUpdateOpt(opt) {
  34849. if (opt != null && !isObject(opt)) {
  34850. opt = {
  34851. isIgnore: opt
  34852. };
  34853. }
  34854. return opt || {};
  34855. }
  34856. function makeSeriesScope(data) {
  34857. var seriesModel = data.hostModel;
  34858. var emphasisModel = seriesModel.getModel('emphasis');
  34859. return {
  34860. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  34861. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  34862. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  34863. focus: emphasisModel.get('focus'),
  34864. blurScope: emphasisModel.get('blurScope'),
  34865. symbolRotate: seriesModel.get('symbolRotate'),
  34866. symbolOffset: seriesModel.get('symbolOffset'),
  34867. hoverScale: emphasisModel.get('scale'),
  34868. labelStatesModels: getLabelStatesModels(seriesModel),
  34869. cursorStyle: seriesModel.get('cursor')
  34870. };
  34871. }
  34872. var SymbolDraw =
  34873. /** @class */
  34874. function () {
  34875. function SymbolDraw(SymbolCtor) {
  34876. this.group = new Group();
  34877. this._SymbolCtor = SymbolCtor || Symbol;
  34878. }
  34879. /**
  34880. * Update symbols draw by new data
  34881. */
  34882. SymbolDraw.prototype.updateData = function (data, opt) {
  34883. opt = normalizeUpdateOpt(opt);
  34884. var group = this.group;
  34885. var seriesModel = data.hostModel;
  34886. var oldData = this._data;
  34887. var SymbolCtor = this._SymbolCtor;
  34888. var disableAnimation = opt.disableAnimation;
  34889. var seriesScope = makeSeriesScope(data);
  34890. var symbolUpdateOpt = {
  34891. disableAnimation: disableAnimation
  34892. };
  34893. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  34894. return data.getItemLayout(idx);
  34895. }; // There is no oldLineData only when first rendering or switching from
  34896. // stream mode to normal mode, where previous elements should be removed.
  34897. if (!oldData) {
  34898. group.removeAll();
  34899. }
  34900. data.diff(oldData).add(function (newIdx) {
  34901. var point = getSymbolPoint(newIdx);
  34902. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  34903. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  34904. symbolEl.setPosition(point);
  34905. data.setItemGraphicEl(newIdx, symbolEl);
  34906. group.add(symbolEl);
  34907. }
  34908. }).update(function (newIdx, oldIdx) {
  34909. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  34910. var point = getSymbolPoint(newIdx);
  34911. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  34912. group.remove(symbolEl);
  34913. return;
  34914. }
  34915. if (!symbolEl) {
  34916. symbolEl = new SymbolCtor(data, newIdx);
  34917. symbolEl.setPosition(point);
  34918. } else {
  34919. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  34920. var target = {
  34921. x: point[0],
  34922. y: point[1]
  34923. };
  34924. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  34925. } // Add back
  34926. group.add(symbolEl);
  34927. data.setItemGraphicEl(newIdx, symbolEl);
  34928. }).remove(function (oldIdx) {
  34929. var el = oldData.getItemGraphicEl(oldIdx);
  34930. el && el.fadeOut(function () {
  34931. group.remove(el);
  34932. });
  34933. }).execute();
  34934. this._getSymbolPoint = getSymbolPoint;
  34935. this._data = data;
  34936. };
  34937. SymbolDraw.prototype.isPersistent = function () {
  34938. return true;
  34939. };
  34940. SymbolDraw.prototype.updateLayout = function () {
  34941. var _this = this;
  34942. var data = this._data;
  34943. if (data) {
  34944. // Not use animation
  34945. data.eachItemGraphicEl(function (el, idx) {
  34946. var point = _this._getSymbolPoint(idx);
  34947. el.setPosition(point);
  34948. el.markRedraw();
  34949. });
  34950. }
  34951. };
  34952. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  34953. this._seriesScope = makeSeriesScope(data);
  34954. this._data = null;
  34955. this.group.removeAll();
  34956. };
  34957. /**
  34958. * Update symbols draw by new data
  34959. */
  34960. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  34961. opt = normalizeUpdateOpt(opt);
  34962. function updateIncrementalAndHover(el) {
  34963. if (!el.isGroup) {
  34964. el.incremental = true;
  34965. el.ensureState('emphasis').hoverLayer = true;
  34966. }
  34967. }
  34968. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  34969. var point = data.getItemLayout(idx);
  34970. if (symbolNeedsDraw(data, point, idx, opt)) {
  34971. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  34972. el.traverse(updateIncrementalAndHover);
  34973. el.setPosition(point);
  34974. this.group.add(el);
  34975. data.setItemGraphicEl(idx, el);
  34976. }
  34977. }
  34978. };
  34979. SymbolDraw.prototype.remove = function (enableAnimation) {
  34980. var group = this.group;
  34981. var data = this._data; // Incremental model do not have this._data.
  34982. if (data && enableAnimation) {
  34983. data.eachItemGraphicEl(function (el) {
  34984. el.fadeOut(function () {
  34985. group.remove(el);
  34986. });
  34987. });
  34988. } else {
  34989. group.removeAll();
  34990. }
  34991. };
  34992. return SymbolDraw;
  34993. }();
  34994. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  34995. var baseAxis = coordSys.getBaseAxis();
  34996. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34997. var valueStart = getValueStart(valueAxis, valueOrigin);
  34998. var baseAxisDim = baseAxis.dim;
  34999. var valueAxisDim = valueAxis.dim;
  35000. var valueDim = data.mapDimension(valueAxisDim);
  35001. var baseDim = data.mapDimension(baseAxisDim);
  35002. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  35003. var dims = map(coordSys.dimensions, function (coordDim) {
  35004. return data.mapDimension(coordDim);
  35005. });
  35006. var stacked = false;
  35007. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  35008. if (isDimensionStacked(data, dims[0]
  35009. /*, dims[1]*/
  35010. )) {
  35011. // jshint ignore:line
  35012. stacked = true;
  35013. dims[0] = stackResultDim;
  35014. }
  35015. if (isDimensionStacked(data, dims[1]
  35016. /*, dims[0]*/
  35017. )) {
  35018. // jshint ignore:line
  35019. stacked = true;
  35020. dims[1] = stackResultDim;
  35021. }
  35022. return {
  35023. dataDimsForPoint: dims,
  35024. valueStart: valueStart,
  35025. valueAxisDim: valueAxisDim,
  35026. baseAxisDim: baseAxisDim,
  35027. stacked: !!stacked,
  35028. valueDim: valueDim,
  35029. baseDim: baseDim,
  35030. baseDataOffset: baseDataOffset,
  35031. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  35032. };
  35033. }
  35034. function getValueStart(valueAxis, valueOrigin) {
  35035. var valueStart = 0;
  35036. var extent = valueAxis.scale.getExtent();
  35037. if (valueOrigin === 'start') {
  35038. valueStart = extent[0];
  35039. } else if (valueOrigin === 'end') {
  35040. valueStart = extent[1];
  35041. } // auto
  35042. else {
  35043. // Both positive
  35044. if (extent[0] > 0) {
  35045. valueStart = extent[0];
  35046. } // Both negative
  35047. else if (extent[1] < 0) {
  35048. valueStart = extent[1];
  35049. } // If is one positive, and one negative, onZero shall be true
  35050. }
  35051. return valueStart;
  35052. }
  35053. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  35054. var value = NaN;
  35055. if (dataCoordInfo.stacked) {
  35056. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  35057. }
  35058. if (isNaN(value)) {
  35059. value = dataCoordInfo.valueStart;
  35060. }
  35061. var baseDataOffset = dataCoordInfo.baseDataOffset;
  35062. var stackedData = [];
  35063. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  35064. stackedData[1 - baseDataOffset] = value;
  35065. return coordSys.dataToPoint(stackedData);
  35066. }
  35067. /* global Float32Array */
  35068. var supportFloat32Array = typeof Float32Array !== 'undefined';
  35069. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  35070. function createFloat32Array(arg) {
  35071. if (isArray(arg)) {
  35072. // Return self directly if don't support TypedArray.
  35073. return supportFloat32Array ? new Float32Array(arg) : arg;
  35074. } // Else is number
  35075. return new Float32ArrayCtor(arg);
  35076. }
  35077. function diffData(oldData, newData) {
  35078. var diffResult = [];
  35079. newData.diff(oldData).add(function (idx) {
  35080. diffResult.push({
  35081. cmd: '+',
  35082. idx: idx
  35083. });
  35084. }).update(function (newIdx, oldIdx) {
  35085. diffResult.push({
  35086. cmd: '=',
  35087. idx: oldIdx,
  35088. idx1: newIdx
  35089. });
  35090. }).remove(function (idx) {
  35091. diffResult.push({
  35092. cmd: '-',
  35093. idx: idx
  35094. });
  35095. }).execute();
  35096. return diffResult;
  35097. }
  35098. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  35099. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  35100. // let oldIdList = oldData.mapArray(oldData.getId);
  35101. // convertToIntId(newIdList, oldIdList);
  35102. // // FIXME One data ?
  35103. // diff = arrayDiff(oldIdList, newIdList);
  35104. var currPoints = [];
  35105. var nextPoints = []; // Points for stacking base line
  35106. var currStackedPoints = [];
  35107. var nextStackedPoints = [];
  35108. var status = [];
  35109. var sortedIndices = [];
  35110. var rawIndices = [];
  35111. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  35112. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  35113. var oldPoints = oldData.getLayout('points') || [];
  35114. var newPoints = newData.getLayout('points') || [];
  35115. for (var i = 0; i < diff.length; i++) {
  35116. var diffItem = diff[i];
  35117. var pointAdded = true;
  35118. var oldIdx2 = void 0;
  35119. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  35120. // Which is in case remvoing or add more than one data in the tail or head
  35121. switch (diffItem.cmd) {
  35122. case '=':
  35123. oldIdx2 = diffItem.idx * 2;
  35124. newIdx2 = diffItem.idx1 * 2;
  35125. var currentX = oldPoints[oldIdx2];
  35126. var currentY = oldPoints[oldIdx2 + 1];
  35127. var nextX = newPoints[newIdx2];
  35128. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  35129. if (isNaN(currentX) || isNaN(currentY)) {
  35130. currentX = nextX;
  35131. currentY = nextY;
  35132. }
  35133. currPoints.push(currentX, currentY);
  35134. nextPoints.push(nextX, nextY);
  35135. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  35136. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  35137. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  35138. break;
  35139. case '+':
  35140. var newIdx = diffItem.idx;
  35141. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  35142. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  35143. newIdx2 = newIdx * 2;
  35144. currPoints.push(oldPt[0], oldPt[1]);
  35145. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  35146. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  35147. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  35148. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  35149. rawIndices.push(newData.getRawIndex(newIdx));
  35150. break;
  35151. case '-':
  35152. var oldIdx = diffItem.idx;
  35153. var rawIndex = oldData.getRawIndex(oldIdx);
  35154. var oldDataDimsForPoint = oldDataNewCoordInfo.dataDimsForPoint;
  35155. oldIdx2 = oldIdx * 2; // Data is replaced. In the case of dynamic data queue
  35156. // FIXME FIXME FIXME
  35157. if (rawIndex !== oldIdx) {
  35158. var newPt = newCoordSys.dataToPoint([oldData.get(oldDataDimsForPoint[0], oldIdx), oldData.get(oldDataDimsForPoint[1], oldIdx)]);
  35159. var newStackedOnPt = getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, oldIdx);
  35160. currPoints.push(oldPoints[oldIdx2], oldPoints[oldIdx2 + 1]);
  35161. nextPoints.push(newPt[0], newPt[1]);
  35162. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  35163. nextStackedPoints.push(newStackedOnPt[0], newStackedOnPt[1]);
  35164. rawIndices.push(rawIndex);
  35165. } else {
  35166. pointAdded = false;
  35167. }
  35168. } // Original indices
  35169. if (pointAdded) {
  35170. status.push(diffItem);
  35171. sortedIndices.push(sortedIndices.length);
  35172. }
  35173. } // Diff result may be crossed if all items are changed
  35174. // Sort by data index
  35175. sortedIndices.sort(function (a, b) {
  35176. return rawIndices[a] - rawIndices[b];
  35177. });
  35178. var len = currPoints.length;
  35179. var sortedCurrPoints = createFloat32Array(len);
  35180. var sortedNextPoints = createFloat32Array(len);
  35181. var sortedCurrStackedPoints = createFloat32Array(len);
  35182. var sortedNextStackedPoints = createFloat32Array(len);
  35183. var sortedStatus = [];
  35184. for (var i = 0; i < sortedIndices.length; i++) {
  35185. var idx = sortedIndices[i];
  35186. var i2 = i * 2;
  35187. var idx2 = idx * 2;
  35188. sortedCurrPoints[i2] = currPoints[idx2];
  35189. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  35190. sortedNextPoints[i2] = nextPoints[idx2];
  35191. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  35192. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  35193. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  35194. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  35195. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  35196. sortedStatus[i] = status[idx];
  35197. }
  35198. return {
  35199. current: sortedCurrPoints,
  35200. next: sortedNextPoints,
  35201. stackedOnCurrent: sortedCurrStackedPoints,
  35202. stackedOnNext: sortedNextStackedPoints,
  35203. status: sortedStatus
  35204. };
  35205. }
  35206. var mathMin$5 = Math.min;
  35207. var mathMax$5 = Math.max;
  35208. function isPointNull(x, y) {
  35209. return isNaN(x) || isNaN(y);
  35210. }
  35211. /**
  35212. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  35213. * situations. This should be used when points are non-monotone neither in x or
  35214. * y dimension.
  35215. */
  35216. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  35217. var prevX;
  35218. var prevY;
  35219. var cpx0;
  35220. var cpy0;
  35221. var cpx1;
  35222. var cpy1;
  35223. var idx = start;
  35224. var k = 0;
  35225. for (; k < segLen; k++) {
  35226. var x = points[idx * 2];
  35227. var y = points[idx * 2 + 1];
  35228. if (idx >= allLen || idx < 0) {
  35229. break;
  35230. }
  35231. if (isPointNull(x, y)) {
  35232. if (connectNulls) {
  35233. idx += dir;
  35234. continue;
  35235. }
  35236. break;
  35237. }
  35238. if (idx === start) {
  35239. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  35240. cpx0 = x;
  35241. cpy0 = y;
  35242. } else {
  35243. var dx = x - prevX;
  35244. var dy = y - prevY; // Ignore tiny segment.
  35245. if (dx * dx + dy * dy < 0.5) {
  35246. idx += dir;
  35247. continue;
  35248. }
  35249. if (smooth > 0) {
  35250. var nextIdx = idx + dir;
  35251. var nextX = points[nextIdx * 2];
  35252. var nextY = points[nextIdx * 2 + 1];
  35253. var tmpK = k + 1;
  35254. if (connectNulls) {
  35255. // Find next point not null
  35256. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  35257. tmpK++;
  35258. nextIdx += dir;
  35259. nextX = points[nextIdx * 2];
  35260. nextY = points[nextIdx * 2 + 1];
  35261. }
  35262. }
  35263. var ratioNextSeg = 0.5;
  35264. var vx = 0;
  35265. var vy = 0;
  35266. var nextCpx0 = void 0;
  35267. var nextCpy0 = void 0; // Is last point
  35268. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  35269. cpx1 = x;
  35270. cpy1 = y;
  35271. } else {
  35272. vx = nextX - prevX;
  35273. vy = nextY - prevY;
  35274. var dx0 = x - prevX;
  35275. var dx1 = nextX - x;
  35276. var dy0 = y - prevY;
  35277. var dy1 = nextY - y;
  35278. var lenPrevSeg = void 0;
  35279. var lenNextSeg = void 0;
  35280. if (smoothMonotone === 'x') {
  35281. lenPrevSeg = Math.abs(dx0);
  35282. lenNextSeg = Math.abs(dx1);
  35283. cpx1 = x - lenPrevSeg * smooth;
  35284. cpy1 = y;
  35285. nextCpx0 = x + lenPrevSeg * smooth;
  35286. nextCpy0 = y;
  35287. } else if (smoothMonotone === 'y') {
  35288. lenPrevSeg = Math.abs(dy0);
  35289. lenNextSeg = Math.abs(dy1);
  35290. cpx1 = x;
  35291. cpy1 = y - lenPrevSeg * smooth;
  35292. nextCpx0 = x;
  35293. nextCpy0 = y + lenPrevSeg * smooth;
  35294. } else {
  35295. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  35296. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  35297. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  35298. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  35299. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  35300. nextCpx0 = x + vx * smooth * ratioNextSeg;
  35301. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  35302. // Avoid exceeding extreme after smoothing.
  35303. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  35304. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  35305. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  35306. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  35307. vx = nextCpx0 - x;
  35308. vy = nextCpy0 - y;
  35309. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  35310. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  35311. // Avoid exceeding extreme after smoothing.
  35312. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  35313. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  35314. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  35315. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  35316. vx = x - cpx1;
  35317. vy = y - cpy1;
  35318. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  35319. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  35320. }
  35321. }
  35322. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  35323. cpx0 = nextCpx0;
  35324. cpy0 = nextCpy0;
  35325. } else {
  35326. ctx.lineTo(x, y);
  35327. }
  35328. }
  35329. prevX = x;
  35330. prevY = y;
  35331. idx += dir;
  35332. }
  35333. return k;
  35334. }
  35335. var ECPolylineShape =
  35336. /** @class */
  35337. function () {
  35338. function ECPolylineShape() {
  35339. this.smooth = 0;
  35340. this.smoothConstraint = true;
  35341. }
  35342. return ECPolylineShape;
  35343. }();
  35344. var ECPolyline =
  35345. /** @class */
  35346. function (_super) {
  35347. __extends(ECPolyline, _super);
  35348. function ECPolyline(opts) {
  35349. var _this = _super.call(this, opts) || this;
  35350. _this.type = 'ec-polyline';
  35351. return _this;
  35352. }
  35353. ECPolyline.prototype.getDefaultStyle = function () {
  35354. return {
  35355. stroke: '#000',
  35356. fill: null
  35357. };
  35358. };
  35359. ECPolyline.prototype.getDefaultShape = function () {
  35360. return new ECPolylineShape();
  35361. };
  35362. ECPolyline.prototype.buildPath = function (ctx, shape) {
  35363. var points = shape.points;
  35364. var i = 0;
  35365. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  35366. if (shape.connectNulls) {
  35367. // Must remove first and last null values avoid draw error in polygon
  35368. for (; len > 0; len--) {
  35369. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  35370. break;
  35371. }
  35372. }
  35373. for (; i < len; i++) {
  35374. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  35375. break;
  35376. }
  35377. }
  35378. }
  35379. while (i < len) {
  35380. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  35381. }
  35382. };
  35383. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  35384. if (!this.path) {
  35385. this.createPathProxy();
  35386. this.buildPath(this.path, this.shape);
  35387. }
  35388. var path = this.path;
  35389. var data = path.data;
  35390. var CMD = PathProxy.CMD;
  35391. var x0;
  35392. var y0;
  35393. var isDimX = dim === 'x';
  35394. var roots = [];
  35395. for (var i = 0; i < data.length;) {
  35396. var cmd = data[i++];
  35397. var x = void 0;
  35398. var y = void 0;
  35399. var x2 = void 0;
  35400. var y2 = void 0;
  35401. var x3 = void 0;
  35402. var y3 = void 0;
  35403. var t = void 0;
  35404. switch (cmd) {
  35405. case CMD.M:
  35406. x0 = data[i++];
  35407. y0 = data[i++];
  35408. break;
  35409. case CMD.L:
  35410. x = data[i++];
  35411. y = data[i++];
  35412. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  35413. if (t <= 1 && t >= 0) {
  35414. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  35415. return isDimX ? [xOrY, val] : [val, xOrY];
  35416. }
  35417. x0 = x;
  35418. y0 = y;
  35419. break;
  35420. case CMD.C:
  35421. x = data[i++];
  35422. y = data[i++];
  35423. x2 = data[i++];
  35424. y2 = data[i++];
  35425. x3 = data[i++];
  35426. y3 = data[i++];
  35427. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  35428. if (nRoot > 0) {
  35429. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  35430. var t_1 = roots[i_1];
  35431. if (t_1 <= 1 && t_1 >= 0) {
  35432. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  35433. return isDimX ? [xOrY, val] : [val, xOrY];
  35434. }
  35435. }
  35436. }
  35437. x0 = x3;
  35438. y0 = y3;
  35439. break;
  35440. }
  35441. }
  35442. };
  35443. return ECPolyline;
  35444. }(Path);
  35445. var ECPolygonShape =
  35446. /** @class */
  35447. function (_super) {
  35448. __extends(ECPolygonShape, _super);
  35449. function ECPolygonShape() {
  35450. return _super !== null && _super.apply(this, arguments) || this;
  35451. }
  35452. return ECPolygonShape;
  35453. }(ECPolylineShape);
  35454. var ECPolygon =
  35455. /** @class */
  35456. function (_super) {
  35457. __extends(ECPolygon, _super);
  35458. function ECPolygon(opts) {
  35459. var _this = _super.call(this, opts) || this;
  35460. _this.type = 'ec-polygon';
  35461. return _this;
  35462. }
  35463. ECPolygon.prototype.getDefaultShape = function () {
  35464. return new ECPolygonShape();
  35465. };
  35466. ECPolygon.prototype.buildPath = function (ctx, shape) {
  35467. var points = shape.points;
  35468. var stackedOnPoints = shape.stackedOnPoints;
  35469. var i = 0;
  35470. var len = points.length / 2;
  35471. var smoothMonotone = shape.smoothMonotone;
  35472. if (shape.connectNulls) {
  35473. // Must remove first and last null values avoid draw error in polygon
  35474. for (; len > 0; len--) {
  35475. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  35476. break;
  35477. }
  35478. }
  35479. for (; i < len; i++) {
  35480. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  35481. break;
  35482. }
  35483. }
  35484. }
  35485. while (i < len) {
  35486. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  35487. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  35488. i += k + 1;
  35489. ctx.closePath();
  35490. }
  35491. };
  35492. return ECPolygon;
  35493. }(Path);
  35494. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  35495. var rect = cartesian.getArea();
  35496. var x = rect.x;
  35497. var y = rect.y;
  35498. var width = rect.width;
  35499. var height = rect.height;
  35500. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  35501. x -= lineWidth / 2;
  35502. y -= lineWidth / 2;
  35503. width += lineWidth;
  35504. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  35505. x = Math.floor(x);
  35506. width = Math.round(width);
  35507. var clipPath = new Rect({
  35508. shape: {
  35509. x: x,
  35510. y: y,
  35511. width: width,
  35512. height: height
  35513. }
  35514. });
  35515. if (hasAnimation) {
  35516. var baseAxis = cartesian.getBaseAxis();
  35517. var isHorizontal = baseAxis.isHorizontal();
  35518. var isAxisInversed = baseAxis.inverse;
  35519. if (isHorizontal) {
  35520. if (isAxisInversed) {
  35521. clipPath.shape.x += width;
  35522. }
  35523. clipPath.shape.width = 0;
  35524. } else {
  35525. if (!isAxisInversed) {
  35526. clipPath.shape.y += height;
  35527. }
  35528. clipPath.shape.height = 0;
  35529. }
  35530. var duringCb = typeof during === 'function' ? function (percent) {
  35531. during(percent, clipPath);
  35532. } : null;
  35533. initProps(clipPath, {
  35534. shape: {
  35535. width: width,
  35536. height: height,
  35537. x: x,
  35538. y: y
  35539. }
  35540. }, seriesModel, null, done, duringCb);
  35541. }
  35542. return clipPath;
  35543. }
  35544. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  35545. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  35546. var r0 = round(sectorArea.r0, 1);
  35547. var r = round(sectorArea.r, 1);
  35548. var clipPath = new Sector({
  35549. shape: {
  35550. cx: round(polar.cx, 1),
  35551. cy: round(polar.cy, 1),
  35552. r0: r0,
  35553. r: r,
  35554. startAngle: sectorArea.startAngle,
  35555. endAngle: sectorArea.endAngle,
  35556. clockwise: sectorArea.clockwise
  35557. }
  35558. });
  35559. if (hasAnimation) {
  35560. var isRadial = polar.getBaseAxis().dim === 'angle';
  35561. if (isRadial) {
  35562. clipPath.shape.endAngle = sectorArea.startAngle;
  35563. } else {
  35564. clipPath.shape.r = r0;
  35565. }
  35566. initProps(clipPath, {
  35567. shape: {
  35568. endAngle: sectorArea.endAngle,
  35569. r: r
  35570. }
  35571. }, seriesModel);
  35572. }
  35573. return clipPath;
  35574. }
  35575. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  35576. if (!coordSys) {
  35577. return null;
  35578. } else if (coordSys.type === 'polar') {
  35579. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  35580. } else if (coordSys.type === 'cartesian2d') {
  35581. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  35582. }
  35583. return null;
  35584. }
  35585. /*
  35586. * Licensed to the Apache Software Foundation (ASF) under one
  35587. * or more contributor license agreements. See the NOTICE file
  35588. * distributed with this work for additional information
  35589. * regarding copyright ownership. The ASF licenses this file
  35590. * to you under the Apache License, Version 2.0 (the
  35591. * "License"); you may not use this file except in compliance
  35592. * with the License. You may obtain a copy of the License at
  35593. *
  35594. * http://www.apache.org/licenses/LICENSE-2.0
  35595. *
  35596. * Unless required by applicable law or agreed to in writing,
  35597. * software distributed under the License is distributed on an
  35598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35599. * KIND, either express or implied. See the License for the
  35600. * specific language governing permissions and limitations
  35601. * under the License.
  35602. */
  35603. /**
  35604. * AUTO-GENERATED FILE. DO NOT MODIFY.
  35605. */
  35606. /*
  35607. * Licensed to the Apache Software Foundation (ASF) under one
  35608. * or more contributor license agreements. See the NOTICE file
  35609. * distributed with this work for additional information
  35610. * regarding copyright ownership. The ASF licenses this file
  35611. * to you under the Apache License, Version 2.0 (the
  35612. * "License"); you may not use this file except in compliance
  35613. * with the License. You may obtain a copy of the License at
  35614. *
  35615. * http://www.apache.org/licenses/LICENSE-2.0
  35616. *
  35617. * Unless required by applicable law or agreed to in writing,
  35618. * software distributed under the License is distributed on an
  35619. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35620. * KIND, either express or implied. See the License for the
  35621. * specific language governing permissions and limitations
  35622. * under the License.
  35623. */
  35624. function isCoordinateSystemType(coordSys, type) {
  35625. return coordSys.type === type;
  35626. }
  35627. function isPointsSame(points1, points2) {
  35628. if (points1.length !== points2.length) {
  35629. return;
  35630. }
  35631. for (var i = 0; i < points1.length; i++) {
  35632. if (points1[i] !== points2[i]) {
  35633. return;
  35634. }
  35635. }
  35636. return true;
  35637. }
  35638. function bboxFromPoints(points) {
  35639. var minX = Infinity;
  35640. var minY = Infinity;
  35641. var maxX = -Infinity;
  35642. var maxY = -Infinity;
  35643. for (var i = 0; i < points.length;) {
  35644. var x = points[i++];
  35645. var y = points[i++];
  35646. if (!isNaN(x)) {
  35647. minX = Math.min(x, minX);
  35648. maxX = Math.max(x, maxX);
  35649. }
  35650. if (!isNaN(y)) {
  35651. minY = Math.min(y, minY);
  35652. maxY = Math.max(y, maxY);
  35653. }
  35654. }
  35655. return [[minX, minY], [maxX, maxY]];
  35656. }
  35657. function getBoundingDiff(points1, points2) {
  35658. var _a = bboxFromPoints(points1),
  35659. min1 = _a[0],
  35660. max1 = _a[1];
  35661. var _b = bboxFromPoints(points2),
  35662. min2 = _b[0],
  35663. max2 = _b[1]; // Get a max value from each corner of two boundings.
  35664. 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]));
  35665. }
  35666. function getSmooth(smooth) {
  35667. return typeof smooth === 'number' ? smooth : smooth ? 0.5 : 0;
  35668. }
  35669. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  35670. if (!dataCoordInfo.valueDim) {
  35671. return [];
  35672. }
  35673. var len = data.count();
  35674. var points = createFloat32Array(len * 2);
  35675. for (var idx = 0; idx < len; idx++) {
  35676. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  35677. points[idx * 2] = pt[0];
  35678. points[idx * 2 + 1] = pt[1];
  35679. }
  35680. return points;
  35681. }
  35682. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  35683. var baseAxis = coordSys.getBaseAxis();
  35684. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  35685. var stepPoints = [];
  35686. var i = 0;
  35687. var stepPt = [];
  35688. var pt = [];
  35689. var nextPt = [];
  35690. for (; i < points.length - 2; i += 2) {
  35691. nextPt[0] = points[i + 2];
  35692. nextPt[1] = points[i + 3];
  35693. pt[0] = points[i];
  35694. pt[1] = points[i + 1];
  35695. stepPoints.push(pt[0], pt[1]);
  35696. switch (stepTurnAt) {
  35697. case 'end':
  35698. stepPt[baseIndex] = nextPt[baseIndex];
  35699. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  35700. stepPoints.push(stepPt[0], stepPt[1]);
  35701. break;
  35702. case 'middle':
  35703. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  35704. var stepPt2 = [];
  35705. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  35706. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  35707. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  35708. stepPoints.push(stepPt[0], stepPt[1]);
  35709. stepPoints.push(stepPt2[0], stepPt2[1]);
  35710. break;
  35711. default:
  35712. // default is start
  35713. stepPt[baseIndex] = pt[baseIndex];
  35714. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  35715. stepPoints.push(stepPt[0], stepPt[1]);
  35716. }
  35717. } // Last points
  35718. stepPoints.push(points[i++], points[i++]);
  35719. return stepPoints;
  35720. }
  35721. function getVisualGradient(data, coordSys) {
  35722. var visualMetaList = data.getVisual('visualMeta');
  35723. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  35724. // When data.count() is 0, gradient range can not be calculated.
  35725. return;
  35726. }
  35727. if (coordSys.type !== 'cartesian2d') {
  35728. if ("development" !== 'production') {
  35729. console.warn('Visual map on line style is only supported on cartesian2d.');
  35730. }
  35731. return;
  35732. }
  35733. var coordDim;
  35734. var visualMeta;
  35735. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  35736. var dimIndex = visualMetaList[i].dimension;
  35737. var dimName = data.dimensions[dimIndex];
  35738. var dimInfo = data.getDimensionInfo(dimName);
  35739. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  35740. if (coordDim === 'x' || coordDim === 'y') {
  35741. visualMeta = visualMetaList[i];
  35742. break;
  35743. }
  35744. }
  35745. if (!visualMeta) {
  35746. if ("development" !== 'production') {
  35747. console.warn('Visual map on line style only support x or y dimension.');
  35748. }
  35749. return;
  35750. } // If the area to be rendered is bigger than area defined by LinearGradient,
  35751. // the canvas spec prescribes that the color of the first stop and the last
  35752. // stop should be used. But if two stops are added at offset 0, in effect
  35753. // browsers use the color of the second stop to render area outside
  35754. // LinearGradient. So we can only infinitesimally extend area defined in
  35755. // LinearGradient to render `outerColors`.
  35756. var axis = coordSys.getAxis(coordDim); // dataToCoor mapping may not be linear, but must be monotonic.
  35757. var colorStops = map(visualMeta.stops, function (stop) {
  35758. return {
  35759. offset: 0,
  35760. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  35761. color: stop.color
  35762. };
  35763. });
  35764. var stopLen = colorStops.length;
  35765. var outerColors = visualMeta.outerColors.slice();
  35766. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  35767. colorStops.reverse();
  35768. outerColors.reverse();
  35769. }
  35770. var tinyExtent = 10; // Arbitrary value: 10px
  35771. var minCoord = colorStops[0].coord - tinyExtent;
  35772. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  35773. var coordSpan = maxCoord - minCoord;
  35774. if (coordSpan < 1e-3) {
  35775. return 'transparent';
  35776. }
  35777. each(colorStops, function (stop) {
  35778. stop.offset = (stop.coord - minCoord) / coordSpan;
  35779. });
  35780. colorStops.push({
  35781. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  35782. color: outerColors[1] || 'transparent'
  35783. });
  35784. colorStops.unshift({
  35785. offset: stopLen ? colorStops[0].offset : 0.5,
  35786. color: outerColors[0] || 'transparent'
  35787. }); // zrUtil.each(colorStops, function (colorStop) {
  35788. // // Make sure each offset has rounded px to avoid not sharp edge
  35789. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  35790. // });
  35791. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  35792. gradient[coordDim] = minCoord;
  35793. gradient[coordDim + '2'] = maxCoord;
  35794. return gradient;
  35795. }
  35796. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  35797. var showAllSymbol = seriesModel.get('showAllSymbol');
  35798. var isAuto = showAllSymbol === 'auto';
  35799. if (showAllSymbol && !isAuto) {
  35800. return;
  35801. }
  35802. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  35803. if (!categoryAxis) {
  35804. return;
  35805. } // Note that category label interval strategy might bring some weird effect
  35806. // in some scenario: users may wonder why some of the symbols are not
  35807. // displayed. So we show all symbols as possible as we can.
  35808. if (isAuto // Simplify the logic, do not determine label overlap here.
  35809. && canShowAllSymbolForCategory(categoryAxis, data)) {
  35810. return;
  35811. } // Otherwise follow the label interval strategy on category axis.
  35812. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  35813. var labelMap = {};
  35814. each(categoryAxis.getViewLabels(), function (labelItem) {
  35815. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  35816. labelMap[ordinalNumber] = 1;
  35817. });
  35818. return function (dataIndex) {
  35819. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  35820. };
  35821. }
  35822. function canShowAllSymbolForCategory(categoryAxis, data) {
  35823. // In mose cases, line is monotonous on category axis, and the label size
  35824. // is close with each other. So we check the symbol size and some of the
  35825. // label size alone with the category axis to estimate whether all symbol
  35826. // can be shown without overlap.
  35827. var axisExtent = categoryAxis.getExtent();
  35828. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  35829. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  35830. // Sampling some points, max 5.
  35831. var dataLen = data.count();
  35832. var step = Math.max(1, Math.round(dataLen / 5));
  35833. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  35834. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  35835. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  35836. * 1.5 > availSize) {
  35837. return false;
  35838. }
  35839. }
  35840. return true;
  35841. }
  35842. function isPointNull$1(x, y) {
  35843. return isNaN(x) || isNaN(y);
  35844. }
  35845. function getLastIndexNotNull(points) {
  35846. var len = points.length / 2;
  35847. for (; len > 0; len--) {
  35848. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  35849. break;
  35850. }
  35851. }
  35852. return len - 1;
  35853. }
  35854. function getPointAtIndex(points, idx) {
  35855. return [points[idx * 2], points[idx * 2 + 1]];
  35856. }
  35857. function getIndexRange(points, xOrY, dim) {
  35858. var len = points.length / 2;
  35859. var dimIdx = dim === 'x' ? 0 : 1;
  35860. var a;
  35861. var b;
  35862. var prevIndex = 0;
  35863. var nextIndex = -1;
  35864. for (var i = 0; i < len; i++) {
  35865. b = points[i * 2 + dimIdx];
  35866. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  35867. continue;
  35868. }
  35869. if (i === 0) {
  35870. a = b;
  35871. continue;
  35872. }
  35873. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  35874. nextIndex = i;
  35875. break;
  35876. }
  35877. prevIndex = i;
  35878. a = b;
  35879. }
  35880. return {
  35881. range: [prevIndex, nextIndex],
  35882. t: (xOrY - a) / (b - a)
  35883. };
  35884. }
  35885. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  35886. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  35887. var endLabelModel_1 = seriesModel.getModel('endLabel');
  35888. var showEndLabel = endLabelModel_1.get('show');
  35889. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  35890. var data_1 = seriesModel.getData();
  35891. var labelAnimationRecord_1 = {
  35892. lastFrameIndex: 0
  35893. };
  35894. var during = showEndLabel ? function (percent, clipRect) {
  35895. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  35896. } : null;
  35897. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  35898. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  35899. var endLabel = lineView._endLabel;
  35900. if (endLabel && hasAnimation) {
  35901. if (labelAnimationRecord_1.originalX != null) {
  35902. endLabel.attr({
  35903. x: labelAnimationRecord_1.originalX,
  35904. y: labelAnimationRecord_1.originalY
  35905. });
  35906. }
  35907. }
  35908. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  35909. if (!seriesModel.get('clip', true)) {
  35910. var rectShape = clipPath.shape;
  35911. var expandSize = Math.max(rectShape.width, rectShape.height);
  35912. if (isHorizontal) {
  35913. rectShape.y -= expandSize;
  35914. rectShape.height += expandSize * 2;
  35915. } else {
  35916. rectShape.x -= expandSize;
  35917. rectShape.width += expandSize * 2;
  35918. }
  35919. } // Set to the final frame. To make sure label layout is right.
  35920. if (during) {
  35921. during(1, clipPath);
  35922. }
  35923. return clipPath;
  35924. } else {
  35925. if ("development" !== 'production') {
  35926. if (seriesModel.get(['endLabel', 'show'])) {
  35927. console.warn('endLabel is not supported for lines in polar systems.');
  35928. }
  35929. }
  35930. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  35931. }
  35932. }
  35933. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  35934. var baseAxis = coordSys.getBaseAxis();
  35935. var isHorizontal = baseAxis.isHorizontal();
  35936. var isBaseInversed = baseAxis.inverse;
  35937. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  35938. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  35939. return {
  35940. normal: {
  35941. align: endLabelModel.get('align') || align,
  35942. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  35943. }
  35944. };
  35945. }
  35946. var LineView =
  35947. /** @class */
  35948. function (_super) {
  35949. __extends(LineView, _super);
  35950. function LineView() {
  35951. return _super !== null && _super.apply(this, arguments) || this;
  35952. }
  35953. LineView.prototype.init = function () {
  35954. var lineGroup = new Group();
  35955. var symbolDraw = new SymbolDraw();
  35956. this.group.add(symbolDraw.group);
  35957. this._symbolDraw = symbolDraw;
  35958. this._lineGroup = lineGroup;
  35959. };
  35960. LineView.prototype.render = function (seriesModel, ecModel, api) {
  35961. var _this = this;
  35962. var coordSys = seriesModel.coordinateSystem;
  35963. var group = this.group;
  35964. var data = seriesModel.getData();
  35965. var lineStyleModel = seriesModel.getModel('lineStyle');
  35966. var areaStyleModel = seriesModel.getModel('areaStyle');
  35967. var points = data.getLayout('points') || [];
  35968. var isCoordSysPolar = coordSys.type === 'polar';
  35969. var prevCoordSys = this._coordSys;
  35970. var symbolDraw = this._symbolDraw;
  35971. var polyline = this._polyline;
  35972. var polygon = this._polygon;
  35973. var lineGroup = this._lineGroup;
  35974. var hasAnimation = seriesModel.get('animation');
  35975. var isAreaChart = !areaStyleModel.isEmpty();
  35976. var valueOrigin = areaStyleModel.get('origin');
  35977. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  35978. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  35979. var showSymbol = seriesModel.get('showSymbol');
  35980. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  35981. var oldData = this._data;
  35982. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  35983. if (el.__temp) {
  35984. group.remove(el);
  35985. oldData.setItemGraphicEl(idx, null);
  35986. }
  35987. }); // Remove previous created symbols if showSymbol changed to false
  35988. if (!showSymbol) {
  35989. symbolDraw.remove();
  35990. }
  35991. group.add(lineGroup); // FIXME step not support polar
  35992. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  35993. var clipShapeForSymbol;
  35994. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  35995. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  35996. // See #7913 and `test/dataZoom-clip.html`.
  35997. if (clipShapeForSymbol.width != null) {
  35998. clipShapeForSymbol.x -= 0.1;
  35999. clipShapeForSymbol.y -= 0.1;
  36000. clipShapeForSymbol.width += 0.2;
  36001. clipShapeForSymbol.height += 0.2;
  36002. } else if (clipShapeForSymbol.r0) {
  36003. clipShapeForSymbol.r0 -= 0.5;
  36004. clipShapeForSymbol.r += 0.5;
  36005. }
  36006. }
  36007. this._clipShapeForSymbol = clipShapeForSymbol;
  36008. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  36009. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  36010. showSymbol && symbolDraw.updateData(data, {
  36011. isIgnore: isIgnoreFunc,
  36012. clipShape: clipShapeForSymbol,
  36013. disableAnimation: true,
  36014. getSymbolPoint: function (idx) {
  36015. return [points[idx * 2], points[idx * 2 + 1]];
  36016. }
  36017. });
  36018. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  36019. if (step) {
  36020. // TODO If stacked series is not step
  36021. points = turnPointsIntoStep(points, coordSys, step);
  36022. if (stackedOnPoints) {
  36023. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  36024. }
  36025. }
  36026. polyline = this._newPolyline(points);
  36027. if (isAreaChart) {
  36028. polygon = this._newPolygon(points, stackedOnPoints);
  36029. } // NOTE: Must update _endLabel before setClipPath.
  36030. if (!isCoordSysPolar) {
  36031. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  36032. }
  36033. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  36034. } else {
  36035. if (isAreaChart && !polygon) {
  36036. // If areaStyle is added
  36037. polygon = this._newPolygon(points, stackedOnPoints);
  36038. } else if (polygon && !isAreaChart) {
  36039. // If areaStyle is removed
  36040. lineGroup.remove(polygon);
  36041. polygon = this._polygon = null;
  36042. } // NOTE: Must update _endLabel before setClipPath.
  36043. if (!isCoordSysPolar) {
  36044. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  36045. } // Update clipPath
  36046. lineGroup.setClipPath(createLineClipPath(this, coordSys, false, seriesModel)); // Always update, or it is wrong in the case turning on legend
  36047. // because points are not changed
  36048. showSymbol && symbolDraw.updateData(data, {
  36049. isIgnore: isIgnoreFunc,
  36050. clipShape: clipShapeForSymbol,
  36051. disableAnimation: true,
  36052. getSymbolPoint: function (idx) {
  36053. return [points[idx * 2], points[idx * 2 + 1]];
  36054. }
  36055. }); // In the case data zoom triggerred refreshing frequently
  36056. // Data may not change if line has a category axis. So it should animate nothing
  36057. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  36058. if (hasAnimation) {
  36059. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin);
  36060. } else {
  36061. // Not do it in update with animation
  36062. if (step) {
  36063. // TODO If stacked series is not step
  36064. points = turnPointsIntoStep(points, coordSys, step);
  36065. if (stackedOnPoints) {
  36066. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  36067. }
  36068. }
  36069. polyline.setShape({
  36070. points: points
  36071. });
  36072. polygon && polygon.setShape({
  36073. points: points,
  36074. stackedOnPoints: stackedOnPoints
  36075. });
  36076. }
  36077. }
  36078. }
  36079. var focus = seriesModel.get(['emphasis', 'focus']);
  36080. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  36081. polyline.useStyle(defaults( // Use color in lineStyle first
  36082. lineStyleModel.getLineStyle(), {
  36083. fill: 'none',
  36084. stroke: visualColor,
  36085. lineJoin: 'bevel'
  36086. }));
  36087. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  36088. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  36089. var emphasisLineStyle = polyline.getState('emphasis').style;
  36090. emphasisLineStyle.lineWidth = polyline.style.lineWidth + 1;
  36091. } // Needs seriesIndex for focus
  36092. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  36093. enableHoverEmphasis(polyline, focus, blurScope);
  36094. var smooth = getSmooth(seriesModel.get('smooth'));
  36095. var smoothMonotone = seriesModel.get('smoothMonotone');
  36096. var connectNulls = seriesModel.get('connectNulls');
  36097. polyline.setShape({
  36098. smooth: smooth,
  36099. smoothMonotone: smoothMonotone,
  36100. connectNulls: connectNulls
  36101. });
  36102. if (polygon) {
  36103. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  36104. var stackedOnSmooth = 0;
  36105. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  36106. fill: visualColor,
  36107. opacity: 0.7,
  36108. lineJoin: 'bevel',
  36109. decal: data.getVisual('style').decal
  36110. }));
  36111. if (stackedOnSeries) {
  36112. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  36113. }
  36114. polygon.setShape({
  36115. smooth: smooth,
  36116. stackedOnSmooth: stackedOnSmooth,
  36117. smoothMonotone: smoothMonotone,
  36118. connectNulls: connectNulls
  36119. });
  36120. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  36121. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  36122. enableHoverEmphasis(polygon, focus, blurScope);
  36123. }
  36124. var changePolyState = function (toState) {
  36125. _this._changePolyState(toState);
  36126. };
  36127. data.eachItemGraphicEl(function (el) {
  36128. // Switch polyline / polygon state if element changed its state.
  36129. el && (el.onHoverStateChange = changePolyState);
  36130. });
  36131. this._polyline.onHoverStateChange = changePolyState;
  36132. this._data = data; // Save the coordinate system for transition animation when data changed
  36133. this._coordSys = coordSys;
  36134. this._stackedOnPoints = stackedOnPoints;
  36135. this._points = points;
  36136. this._step = step;
  36137. this._valueOrigin = valueOrigin;
  36138. };
  36139. LineView.prototype.dispose = function () {};
  36140. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  36141. var data = seriesModel.getData();
  36142. var dataIndex = queryDataIndex(data, payload);
  36143. this._changePolyState('emphasis');
  36144. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  36145. var points = data.getLayout('points');
  36146. var symbol = data.getItemGraphicEl(dataIndex);
  36147. if (!symbol) {
  36148. // Create a temporary symbol if it is not exists
  36149. var x = points[dataIndex * 2];
  36150. var y = points[dataIndex * 2 + 1];
  36151. if (isNaN(x) || isNaN(y)) {
  36152. // Null data
  36153. return;
  36154. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  36155. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  36156. return;
  36157. }
  36158. symbol = new Symbol(data, dataIndex);
  36159. symbol.x = x;
  36160. symbol.y = y;
  36161. symbol.setZ(seriesModel.get('zlevel'), seriesModel.get('z'));
  36162. symbol.__temp = true;
  36163. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  36164. symbol.stopSymbolAnimation(true);
  36165. this.group.add(symbol);
  36166. }
  36167. symbol.highlight();
  36168. } else {
  36169. // Highlight whole series
  36170. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  36171. }
  36172. };
  36173. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  36174. var data = seriesModel.getData();
  36175. var dataIndex = queryDataIndex(data, payload);
  36176. this._changePolyState('normal');
  36177. if (dataIndex != null && dataIndex >= 0) {
  36178. var symbol = data.getItemGraphicEl(dataIndex);
  36179. if (symbol) {
  36180. if (symbol.__temp) {
  36181. data.setItemGraphicEl(dataIndex, null);
  36182. this.group.remove(symbol);
  36183. } else {
  36184. symbol.downplay();
  36185. }
  36186. }
  36187. } else {
  36188. // FIXME
  36189. // can not downplay completely.
  36190. // Downplay whole series
  36191. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  36192. }
  36193. };
  36194. LineView.prototype._changePolyState = function (toState) {
  36195. var polygon = this._polygon;
  36196. setStatesFlag(this._polyline, toState);
  36197. polygon && setStatesFlag(polygon, toState);
  36198. };
  36199. LineView.prototype._newPolyline = function (points) {
  36200. var polyline = this._polyline; // Remove previous created polyline
  36201. if (polyline) {
  36202. this._lineGroup.remove(polyline);
  36203. }
  36204. polyline = new ECPolyline({
  36205. shape: {
  36206. points: points
  36207. },
  36208. segmentIgnoreThreshold: 2,
  36209. z2: 10
  36210. });
  36211. this._lineGroup.add(polyline);
  36212. this._polyline = polyline;
  36213. return polyline;
  36214. };
  36215. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  36216. var polygon = this._polygon; // Remove previous created polygon
  36217. if (polygon) {
  36218. this._lineGroup.remove(polygon);
  36219. }
  36220. polygon = new ECPolygon({
  36221. shape: {
  36222. points: points,
  36223. stackedOnPoints: stackedOnPoints
  36224. },
  36225. segmentIgnoreThreshold: 2
  36226. });
  36227. this._lineGroup.add(polygon);
  36228. this._polygon = polygon;
  36229. return polygon;
  36230. };
  36231. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  36232. var isHorizontalOrRadial;
  36233. var isCoordSysPolar;
  36234. var baseAxis = coordSys.getBaseAxis();
  36235. var isAxisInverse = baseAxis.inverse;
  36236. if (coordSys.type === 'cartesian2d') {
  36237. isHorizontalOrRadial = baseAxis.isHorizontal();
  36238. isCoordSysPolar = false;
  36239. } else if (coordSys.type === 'polar') {
  36240. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36241. isCoordSysPolar = true;
  36242. }
  36243. var seriesModel = data.hostModel;
  36244. var seriesDuration = seriesModel.get('animationDuration');
  36245. if (typeof seriesDuration === 'function') {
  36246. seriesDuration = seriesDuration(null);
  36247. }
  36248. var seriesDalay = seriesModel.get('animationDelay') || 0;
  36249. var seriesDalayValue = typeof seriesDalay === 'function' ? seriesDalay(null) : seriesDalay;
  36250. data.eachItemGraphicEl(function (symbol, idx) {
  36251. var el = symbol;
  36252. if (el) {
  36253. var point = [symbol.x, symbol.y];
  36254. var start = void 0;
  36255. var end = void 0;
  36256. var current = void 0;
  36257. if (isCoordSysPolar) {
  36258. var polarClip = clipShape;
  36259. var coord = coordSys.pointToCoord(point);
  36260. if (isHorizontalOrRadial) {
  36261. start = polarClip.startAngle;
  36262. end = polarClip.endAngle;
  36263. current = -coord[1] / 180 * Math.PI;
  36264. } else {
  36265. start = polarClip.r0;
  36266. end = polarClip.r;
  36267. current = coord[0];
  36268. }
  36269. } else {
  36270. var gridClip = clipShape;
  36271. if (isHorizontalOrRadial) {
  36272. start = gridClip.x;
  36273. end = gridClip.x + gridClip.width;
  36274. current = symbol.x;
  36275. } else {
  36276. start = gridClip.y + gridClip.height;
  36277. end = gridClip.y;
  36278. current = symbol.y;
  36279. }
  36280. }
  36281. var ratio = end === start ? 0 : (current - start) / (end - start);
  36282. if (isAxisInverse) {
  36283. ratio = 1 - ratio;
  36284. }
  36285. var delay = typeof seriesDalay === 'function' ? seriesDalay(idx) : seriesDuration * ratio + seriesDalayValue;
  36286. var symbolPath = el.getSymbolPath();
  36287. var text = symbolPath.getTextContent();
  36288. el.attr({
  36289. scaleX: 0,
  36290. scaleY: 0
  36291. });
  36292. el.animateTo({
  36293. scaleX: 1,
  36294. scaleY: 1
  36295. }, {
  36296. duration: 200,
  36297. delay: delay
  36298. });
  36299. if (text) {
  36300. text.animateFrom({
  36301. style: {
  36302. opacity: 0
  36303. }
  36304. }, {
  36305. duration: 300,
  36306. delay: delay
  36307. });
  36308. }
  36309. symbolPath.disableLabelAnimation = true;
  36310. }
  36311. });
  36312. };
  36313. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  36314. var endLabelModel = seriesModel.getModel('endLabel');
  36315. if (endLabelModel.get('show')) {
  36316. var data_2 = seriesModel.getData();
  36317. var polyline = this._polyline;
  36318. var endLabel = this._endLabel;
  36319. if (!endLabel) {
  36320. endLabel = this._endLabel = new ZRText({
  36321. z2: 200 // should be higher than item symbol
  36322. });
  36323. endLabel.ignoreClip = true;
  36324. polyline.setTextContent(this._endLabel);
  36325. polyline.disableLabelAnimation = true;
  36326. } // Find last non-NaN data to display data
  36327. var dataIndex = getLastIndexNotNull(data_2.getLayout('points'));
  36328. if (dataIndex >= 0) {
  36329. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  36330. inheritColor: inheritColor,
  36331. labelFetcher: seriesModel,
  36332. labelDataIndex: dataIndex,
  36333. defaultText: function (dataIndex, opt, interpolatedValue) {
  36334. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  36335. },
  36336. enableTextSetter: true
  36337. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  36338. polyline.textConfig.position = null;
  36339. }
  36340. } else if (this._endLabel) {
  36341. this._polyline.removeTextContent();
  36342. this._endLabel = null;
  36343. }
  36344. };
  36345. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  36346. var endLabel = this._endLabel;
  36347. var polyline = this._polyline;
  36348. if (endLabel) {
  36349. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  36350. // The label is not prepared at this time.
  36351. if (percent < 1 && animationRecord.originalX == null) {
  36352. animationRecord.originalX = endLabel.x;
  36353. animationRecord.originalY = endLabel.y;
  36354. }
  36355. var points = data.getLayout('points');
  36356. var seriesModel = data.hostModel;
  36357. var connectNulls = seriesModel.get('connectNulls');
  36358. var precision = endLabelModel.get('precision');
  36359. var distance = endLabelModel.get('distance') || 0;
  36360. var baseAxis = coordSys.getBaseAxis();
  36361. var isHorizontal = baseAxis.isHorizontal();
  36362. var isBaseInversed = baseAxis.inverse;
  36363. var clipShape = clipRect.shape;
  36364. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  36365. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  36366. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  36367. var dim = isHorizontal ? 'x' : 'y';
  36368. var dataIndexRange = getIndexRange(points, xOrY, dim);
  36369. var indices = dataIndexRange.range;
  36370. var diff = indices[1] - indices[0];
  36371. var value = void 0;
  36372. if (diff >= 1) {
  36373. // diff > 1 && connectNulls, which is on the null data.
  36374. if (diff > 1 && !connectNulls) {
  36375. var pt = getPointAtIndex(points, indices[0]);
  36376. endLabel.attr({
  36377. x: pt[0] + distanceX,
  36378. y: pt[1] + distanceY
  36379. });
  36380. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  36381. } else {
  36382. var pt = polyline.getPointOn(xOrY, dim);
  36383. pt && endLabel.attr({
  36384. x: pt[0] + distanceX,
  36385. y: pt[1] + distanceY
  36386. });
  36387. var startValue = seriesModel.getRawValue(indices[0]);
  36388. var endValue = seriesModel.getRawValue(indices[1]);
  36389. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  36390. }
  36391. animationRecord.lastFrameIndex = indices[0];
  36392. } else {
  36393. // If diff <= 0, which is the range is not found(Include NaN)
  36394. // Choose the first point or last point.
  36395. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  36396. var pt = getPointAtIndex(points, idx);
  36397. valueAnimation && (value = seriesModel.getRawValue(idx));
  36398. endLabel.attr({
  36399. x: pt[0] + distanceX,
  36400. y: pt[1] + distanceY
  36401. });
  36402. }
  36403. if (valueAnimation) {
  36404. labelInner(endLabel).setLabelText(value);
  36405. }
  36406. }
  36407. };
  36408. /**
  36409. * @private
  36410. */
  36411. // FIXME Two value axis
  36412. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  36413. var polyline = this._polyline;
  36414. var polygon = this._polygon;
  36415. var seriesModel = data.hostModel;
  36416. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin, valueOrigin);
  36417. var current = diff.current;
  36418. var stackedOnCurrent = diff.stackedOnCurrent;
  36419. var next = diff.next;
  36420. var stackedOnNext = diff.stackedOnNext;
  36421. if (step) {
  36422. // TODO If stacked series is not step
  36423. current = turnPointsIntoStep(diff.current, coordSys, step);
  36424. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  36425. next = turnPointsIntoStep(diff.next, coordSys, step);
  36426. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  36427. } // Don't apply animation if diff is large.
  36428. // For better result and avoid memory explosion problems like
  36429. // https://github.com/apache/incubator-echarts/issues/12229
  36430. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  36431. polyline.setShape({
  36432. points: next
  36433. });
  36434. if (polygon) {
  36435. polygon.setShape({
  36436. points: next,
  36437. stackedOnPoints: stackedOnNext
  36438. });
  36439. }
  36440. return;
  36441. }
  36442. polyline.shape.__points = diff.current;
  36443. polyline.shape.points = current;
  36444. var target = {
  36445. shape: {
  36446. points: next
  36447. }
  36448. }; // Also animate the original points.
  36449. // If points reference is changed when turning into step line.
  36450. if (diff.current !== current) {
  36451. target.shape.__points = diff.next;
  36452. } // Stop previous animation.
  36453. polyline.stopAnimation();
  36454. updateProps(polyline, target, seriesModel);
  36455. if (polygon) {
  36456. polygon.setShape({
  36457. // Reuse the points with polyline.
  36458. points: current,
  36459. stackedOnPoints: stackedOnCurrent
  36460. });
  36461. polygon.stopAnimation();
  36462. updateProps(polygon, {
  36463. shape: {
  36464. stackedOnPoints: stackedOnNext
  36465. }
  36466. }, seriesModel); // If use attr directly in updateProps.
  36467. if (polyline.shape.points !== polygon.shape.points) {
  36468. polygon.shape.points = polyline.shape.points;
  36469. }
  36470. }
  36471. var updatedDataInfo = [];
  36472. var diffStatus = diff.status;
  36473. for (var i = 0; i < diffStatus.length; i++) {
  36474. var cmd = diffStatus[i].cmd;
  36475. if (cmd === '=') {
  36476. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  36477. if (el) {
  36478. updatedDataInfo.push({
  36479. el: el,
  36480. ptIdx: i // Index of points
  36481. });
  36482. }
  36483. }
  36484. }
  36485. if (polyline.animators && polyline.animators.length) {
  36486. polyline.animators[0].during(function () {
  36487. polygon && polygon.dirtyShape();
  36488. var points = polyline.shape.__points;
  36489. for (var i = 0; i < updatedDataInfo.length; i++) {
  36490. var el = updatedDataInfo[i].el;
  36491. var offset = updatedDataInfo[i].ptIdx * 2;
  36492. el.x = points[offset];
  36493. el.y = points[offset + 1];
  36494. el.markRedraw();
  36495. }
  36496. });
  36497. }
  36498. };
  36499. LineView.prototype.remove = function (ecModel) {
  36500. var group = this.group;
  36501. var oldData = this._data;
  36502. this._lineGroup.removeAll();
  36503. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  36504. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  36505. if (el.__temp) {
  36506. group.remove(el);
  36507. oldData.setItemGraphicEl(idx, null);
  36508. }
  36509. });
  36510. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  36511. };
  36512. LineView.type = 'line';
  36513. return LineView;
  36514. }(ChartView);
  36515. function pointsLayout(seriesType, forceStoreInTypedArray) {
  36516. return {
  36517. seriesType: seriesType,
  36518. plan: createRenderPlanner(),
  36519. reset: function (seriesModel) {
  36520. var data = seriesModel.getData();
  36521. var coordSys = seriesModel.coordinateSystem;
  36522. var pipelineContext = seriesModel.pipelineContext;
  36523. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  36524. if (!coordSys) {
  36525. return;
  36526. }
  36527. var dims = map(coordSys.dimensions, function (dim) {
  36528. return data.mapDimension(dim);
  36529. }).slice(0, 2);
  36530. var dimLen = dims.length;
  36531. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  36532. if (isDimensionStacked(data, dims[0]
  36533. /*, dims[1]*/
  36534. )) {
  36535. dims[0] = stackResultDim;
  36536. }
  36537. if (isDimensionStacked(data, dims[1]
  36538. /*, dims[0]*/
  36539. )) {
  36540. dims[1] = stackResultDim;
  36541. }
  36542. var dimInfo0 = data.getDimensionInfo(dims[0]);
  36543. var dimInfo1 = data.getDimensionInfo(dims[1]);
  36544. var dimIdx0 = dimInfo0 && dimInfo0.index;
  36545. var dimIdx1 = dimInfo1 && dimInfo1.index;
  36546. return dimLen && {
  36547. progress: function (params, data) {
  36548. var segCount = params.end - params.start;
  36549. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  36550. var tmpIn = [];
  36551. var tmpOut = [];
  36552. for (var i = params.start, offset = 0; i < params.end; i++) {
  36553. var point = void 0;
  36554. if (dimLen === 1) {
  36555. var x = data.getByDimIdx(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  36556. point = coordSys.dataToPoint(x, null, tmpOut);
  36557. } else {
  36558. tmpIn[0] = data.getByDimIdx(dimIdx0, i);
  36559. tmpIn[1] = data.getByDimIdx(dimIdx1, i); // Let coordinate system to handle the NaN data.
  36560. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  36561. }
  36562. if (useTypedArray) {
  36563. points[offset++] = point[0];
  36564. points[offset++] = point[1];
  36565. } else {
  36566. data.setItemLayout(i, point.slice());
  36567. }
  36568. }
  36569. useTypedArray && data.setLayout('points', points);
  36570. }
  36571. };
  36572. }
  36573. };
  36574. }
  36575. /*
  36576. * Licensed to the Apache Software Foundation (ASF) under one
  36577. * or more contributor license agreements. See the NOTICE file
  36578. * distributed with this work for additional information
  36579. * regarding copyright ownership. The ASF licenses this file
  36580. * to you under the Apache License, Version 2.0 (the
  36581. * "License"); you may not use this file except in compliance
  36582. * with the License. You may obtain a copy of the License at
  36583. *
  36584. * http://www.apache.org/licenses/LICENSE-2.0
  36585. *
  36586. * Unless required by applicable law or agreed to in writing,
  36587. * software distributed under the License is distributed on an
  36588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36589. * KIND, either express or implied. See the License for the
  36590. * specific language governing permissions and limitations
  36591. * under the License.
  36592. */
  36593. /**
  36594. * AUTO-GENERATED FILE. DO NOT MODIFY.
  36595. */
  36596. /*
  36597. * Licensed to the Apache Software Foundation (ASF) under one
  36598. * or more contributor license agreements. See the NOTICE file
  36599. * distributed with this work for additional information
  36600. * regarding copyright ownership. The ASF licenses this file
  36601. * to you under the Apache License, Version 2.0 (the
  36602. * "License"); you may not use this file except in compliance
  36603. * with the License. You may obtain a copy of the License at
  36604. *
  36605. * http://www.apache.org/licenses/LICENSE-2.0
  36606. *
  36607. * Unless required by applicable law or agreed to in writing,
  36608. * software distributed under the License is distributed on an
  36609. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36610. * KIND, either express or implied. See the License for the
  36611. * specific language governing permissions and limitations
  36612. * under the License.
  36613. */
  36614. var samplers = {
  36615. average: function (frame) {
  36616. var sum = 0;
  36617. var count = 0;
  36618. for (var i = 0; i < frame.length; i++) {
  36619. if (!isNaN(frame[i])) {
  36620. sum += frame[i];
  36621. count++;
  36622. }
  36623. } // Return NaN if count is 0
  36624. return count === 0 ? NaN : sum / count;
  36625. },
  36626. sum: function (frame) {
  36627. var sum = 0;
  36628. for (var i = 0; i < frame.length; i++) {
  36629. // Ignore NaN
  36630. sum += frame[i] || 0;
  36631. }
  36632. return sum;
  36633. },
  36634. max: function (frame) {
  36635. var max = -Infinity;
  36636. for (var i = 0; i < frame.length; i++) {
  36637. frame[i] > max && (max = frame[i]);
  36638. } // NaN will cause illegal axis extent.
  36639. return isFinite(max) ? max : NaN;
  36640. },
  36641. min: function (frame) {
  36642. var min = Infinity;
  36643. for (var i = 0; i < frame.length; i++) {
  36644. frame[i] < min && (min = frame[i]);
  36645. } // NaN will cause illegal axis extent.
  36646. return isFinite(min) ? min : NaN;
  36647. },
  36648. // TODO
  36649. // Median
  36650. nearest: function (frame) {
  36651. return frame[0];
  36652. }
  36653. };
  36654. var indexSampler = function (frame) {
  36655. return Math.round(frame.length / 2);
  36656. };
  36657. function dataSample(seriesType) {
  36658. return {
  36659. seriesType: seriesType,
  36660. // FIXME:TS never used, so comment it
  36661. // modifyOutputEnd: true,
  36662. reset: function (seriesModel, ecModel, api) {
  36663. var data = seriesModel.getData();
  36664. var sampling = seriesModel.get('sampling');
  36665. var coordSys = seriesModel.coordinateSystem;
  36666. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  36667. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  36668. var baseAxis = coordSys.getBaseAxis();
  36669. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36670. var extent = baseAxis.getExtent();
  36671. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  36672. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  36673. var rate = Math.round(count / size);
  36674. if (rate > 1) {
  36675. if (sampling === 'lttb') {
  36676. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  36677. }
  36678. var sampler = void 0;
  36679. if (typeof sampling === 'string') {
  36680. sampler = samplers[sampling];
  36681. } else if (typeof sampling === 'function') {
  36682. sampler = sampling;
  36683. }
  36684. if (sampler) {
  36685. // Only support sample the first dim mapped from value axis.
  36686. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  36687. }
  36688. }
  36689. }
  36690. }
  36691. };
  36692. }
  36693. function install$2(registers) {
  36694. registers.registerChartView(LineView);
  36695. registers.registerSeriesModel(LineSeriesModel);
  36696. registers.registerLayout(pointsLayout('line', true)); // Down sample after filter
  36697. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  36698. }
  36699. var BaseBarSeriesModel =
  36700. /** @class */
  36701. function (_super) {
  36702. __extends(BaseBarSeriesModel, _super);
  36703. function BaseBarSeriesModel() {
  36704. var _this = _super !== null && _super.apply(this, arguments) || this;
  36705. _this.type = BaseBarSeriesModel.type;
  36706. return _this;
  36707. }
  36708. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  36709. return createListFromArray(this.getSource(), this, {
  36710. useEncodeDefaulter: true
  36711. });
  36712. };
  36713. BaseBarSeriesModel.prototype.getMarkerPosition = function (value) {
  36714. var coordSys = this.coordinateSystem;
  36715. if (coordSys) {
  36716. // PENDING if clamp ?
  36717. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  36718. var data = this.getData();
  36719. var offset = data.getLayout('offset');
  36720. var size = data.getLayout('size');
  36721. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  36722. pt[offsetIndex] += offset + size / 2;
  36723. return pt;
  36724. }
  36725. return [NaN, NaN];
  36726. };
  36727. BaseBarSeriesModel.type = 'series.__base_bar__';
  36728. BaseBarSeriesModel.defaultOption = {
  36729. zlevel: 0,
  36730. z: 2,
  36731. coordinateSystem: 'cartesian2d',
  36732. legendHoverLink: true,
  36733. // stack: null
  36734. // Cartesian coordinate system
  36735. // xAxisIndex: 0,
  36736. // yAxisIndex: 0,
  36737. barMinHeight: 0,
  36738. barMinAngle: 0,
  36739. // cursor: null,
  36740. large: false,
  36741. largeThreshold: 400,
  36742. progressive: 3e3,
  36743. progressiveChunkMode: 'mod'
  36744. };
  36745. return BaseBarSeriesModel;
  36746. }(SeriesModel);
  36747. SeriesModel.registerClass(BaseBarSeriesModel);
  36748. var BarSeriesModel =
  36749. /** @class */
  36750. function (_super) {
  36751. __extends(BarSeriesModel, _super);
  36752. function BarSeriesModel() {
  36753. var _this = _super !== null && _super.apply(this, arguments) || this;
  36754. _this.type = BarSeriesModel.type;
  36755. return _this;
  36756. }
  36757. BarSeriesModel.prototype.getInitialData = function () {
  36758. return createListFromArray(this.getSource(), this, {
  36759. useEncodeDefaulter: true,
  36760. createInvertedIndices: !!this.get('realtimeSort', true) || null
  36761. });
  36762. };
  36763. /**
  36764. * @override
  36765. */
  36766. BarSeriesModel.prototype.getProgressive = function () {
  36767. // Do not support progressive in normal mode.
  36768. return this.get('large') ? this.get('progressive') : false;
  36769. };
  36770. /**
  36771. * @override
  36772. */
  36773. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  36774. // Do not support progressive in normal mode.
  36775. var progressiveThreshold = this.get('progressiveThreshold');
  36776. var largeThreshold = this.get('largeThreshold');
  36777. if (largeThreshold > progressiveThreshold) {
  36778. progressiveThreshold = largeThreshold;
  36779. }
  36780. return progressiveThreshold;
  36781. };
  36782. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  36783. return selectors.rect(data.getItemLayout(dataIndex));
  36784. };
  36785. BarSeriesModel.type = 'series.bar';
  36786. BarSeriesModel.dependencies = ['grid', 'polar'];
  36787. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  36788. // If clipped
  36789. // Only available on cartesian2d
  36790. clip: true,
  36791. roundCap: false,
  36792. showBackground: false,
  36793. backgroundStyle: {
  36794. color: 'rgba(180, 180, 180, 0.2)',
  36795. borderColor: null,
  36796. borderWidth: 0,
  36797. borderType: 'solid',
  36798. borderRadius: 0,
  36799. shadowBlur: 0,
  36800. shadowColor: null,
  36801. shadowOffsetX: 0,
  36802. shadowOffsetY: 0,
  36803. opacity: 1
  36804. },
  36805. select: {
  36806. itemStyle: {
  36807. borderColor: '#212121'
  36808. }
  36809. },
  36810. realtimeSort: false
  36811. });
  36812. return BarSeriesModel;
  36813. }(BaseBarSeriesModel);
  36814. /**
  36815. * Sausage: similar to sector, but have half circle on both sides
  36816. */
  36817. var SausageShape =
  36818. /** @class */
  36819. function () {
  36820. function SausageShape() {
  36821. this.cx = 0;
  36822. this.cy = 0;
  36823. this.r0 = 0;
  36824. this.r = 0;
  36825. this.startAngle = 0;
  36826. this.endAngle = Math.PI * 2;
  36827. this.clockwise = true;
  36828. }
  36829. return SausageShape;
  36830. }();
  36831. var SausagePath =
  36832. /** @class */
  36833. function (_super) {
  36834. __extends(SausagePath, _super);
  36835. function SausagePath(opts) {
  36836. var _this = _super.call(this, opts) || this;
  36837. _this.type = 'sausage';
  36838. return _this;
  36839. }
  36840. SausagePath.prototype.getDefaultShape = function () {
  36841. return new SausageShape();
  36842. };
  36843. SausagePath.prototype.buildPath = function (ctx, shape) {
  36844. var x = shape.cx;
  36845. var y = shape.cy;
  36846. var r0 = Math.max(shape.r0 || 0, 0);
  36847. var r = Math.max(shape.r, 0);
  36848. var dr = (r - r0) * 0.5;
  36849. var rCenter = r0 + dr;
  36850. var startAngle = shape.startAngle;
  36851. var endAngle = shape.endAngle;
  36852. var clockwise = shape.clockwise;
  36853. var unitStartX = Math.cos(startAngle);
  36854. var unitStartY = Math.sin(startAngle);
  36855. var unitEndX = Math.cos(endAngle);
  36856. var unitEndY = Math.sin(endAngle);
  36857. var lessThanCircle = clockwise ? endAngle - startAngle < Math.PI * 2 : startAngle - endAngle < Math.PI * 2;
  36858. if (lessThanCircle) {
  36859. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  36860. ctx.arc(unitStartX * rCenter + x, unitStartY * rCenter + y, dr, -Math.PI + startAngle, startAngle, !clockwise);
  36861. }
  36862. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  36863. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  36864. ctx.arc(unitEndX * rCenter + x, unitEndY * rCenter + y, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  36865. if (r0 !== 0) {
  36866. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  36867. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  36868. }
  36869. ctx.closePath();
  36870. };
  36871. return SausagePath;
  36872. }(Path);
  36873. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth'];
  36874. var BAR_BORDER_RADIUS_QUERY = ['itemStyle', 'borderRadius'];
  36875. var _eventPos = [0, 0];
  36876. var mathMax$6 = Math.max;
  36877. var mathMin$6 = Math.min;
  36878. function getClipArea(coord, data) {
  36879. var coordSysClipArea = coord.getArea && coord.getArea();
  36880. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  36881. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  36882. // We should not clip this part.
  36883. // See test/bar2.html
  36884. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  36885. var expandWidth = data.getLayout('bandWidth');
  36886. if (baseAxis.isHorizontal()) {
  36887. coordSysClipArea.x -= expandWidth;
  36888. coordSysClipArea.width += expandWidth * 2;
  36889. } else {
  36890. coordSysClipArea.y -= expandWidth;
  36891. coordSysClipArea.height += expandWidth * 2;
  36892. }
  36893. }
  36894. }
  36895. return coordSysClipArea;
  36896. }
  36897. var BarView =
  36898. /** @class */
  36899. function (_super) {
  36900. __extends(BarView, _super);
  36901. function BarView() {
  36902. var _this = _super.call(this) || this;
  36903. _this.type = BarView.type;
  36904. _this._isFirstFrame = true;
  36905. return _this;
  36906. }
  36907. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  36908. this._model = seriesModel;
  36909. this._removeOnRenderedListener(api);
  36910. this._updateDrawMode(seriesModel);
  36911. var coordinateSystemType = seriesModel.get('coordinateSystem');
  36912. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  36913. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  36914. } else if ("development" !== 'production') {
  36915. warn('Only cartesian2d and polar supported for bar.');
  36916. }
  36917. };
  36918. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  36919. this._clear();
  36920. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  36921. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  36922. this._updateLargeClip(seriesModel);
  36923. };
  36924. BarView.prototype.incrementalRender = function (params, seriesModel) {
  36925. // Do not support progressive in normal mode.
  36926. this._incrementalRenderLarge(params, seriesModel);
  36927. };
  36928. BarView.prototype._updateDrawMode = function (seriesModel) {
  36929. var isLargeDraw = seriesModel.pipelineContext.large;
  36930. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  36931. this._isLargeDraw = isLargeDraw;
  36932. this._clear();
  36933. }
  36934. };
  36935. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  36936. var group = this.group;
  36937. var data = seriesModel.getData();
  36938. var oldData = this._data;
  36939. var coord = seriesModel.coordinateSystem;
  36940. var baseAxis = coord.getBaseAxis();
  36941. var isHorizontalOrRadial;
  36942. if (coord.type === 'cartesian2d') {
  36943. isHorizontalOrRadial = baseAxis.isHorizontal();
  36944. } else if (coord.type === 'polar') {
  36945. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36946. }
  36947. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  36948. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  36949. if (realtimeSortCfg) {
  36950. this._enableRealtimeSort(realtimeSortCfg, data, api);
  36951. }
  36952. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  36953. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  36954. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  36955. // And don't want the label are clipped.
  36956. var roundCap = seriesModel.get('roundCap', true);
  36957. var drawBackground = seriesModel.get('showBackground', true);
  36958. var backgroundModel = seriesModel.getModel('backgroundStyle');
  36959. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  36960. var bgEls = [];
  36961. var oldBgEls = this._backgroundEls;
  36962. var isInitSort = payload && payload.isInitSort;
  36963. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  36964. function createBackground(dataIndex) {
  36965. var bgLayout = getLayout[coord.type](data, dataIndex);
  36966. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  36967. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  36968. if (coord.type === 'cartesian2d') {
  36969. bgEl.setShape('r', barBorderRadius);
  36970. }
  36971. bgEls[dataIndex] = bgEl;
  36972. return bgEl;
  36973. }
  36974. data.diff(oldData).add(function (dataIndex) {
  36975. var itemModel = data.getItemModel(dataIndex);
  36976. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36977. if (drawBackground) {
  36978. createBackground(dataIndex);
  36979. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  36980. if (!data.hasValue(dataIndex)) {
  36981. return;
  36982. }
  36983. var isClipped = false;
  36984. if (needsClip) {
  36985. // Clip will modify the layout params.
  36986. // And return a boolean to determine if the shape are fully clipped.
  36987. isClipped = clip[coord.type](coordSysClipArea, layout);
  36988. }
  36989. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  36990. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  36991. if (isInitSort) {
  36992. el.attr({
  36993. shape: layout
  36994. });
  36995. } else if (realtimeSortCfg) {
  36996. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  36997. } else {
  36998. initProps(el, {
  36999. shape: layout
  37000. }, seriesModel, dataIndex);
  37001. }
  37002. data.setItemGraphicEl(dataIndex, el);
  37003. group.add(el);
  37004. el.ignore = isClipped;
  37005. }).update(function (newIndex, oldIndex) {
  37006. var itemModel = data.getItemModel(newIndex);
  37007. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37008. if (drawBackground) {
  37009. var bgEl = void 0;
  37010. if (oldBgEls.length === 0) {
  37011. bgEl = createBackground(oldIndex);
  37012. } else {
  37013. bgEl = oldBgEls[oldIndex];
  37014. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  37015. if (coord.type === 'cartesian2d') {
  37016. bgEl.setShape('r', barBorderRadius);
  37017. }
  37018. bgEls[newIndex] = bgEl;
  37019. }
  37020. var bgLayout = getLayout[coord.type](data, newIndex);
  37021. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  37022. updateProps(bgEl, {
  37023. shape: shape
  37024. }, animationModel, newIndex);
  37025. }
  37026. var el = oldData.getItemGraphicEl(oldIndex);
  37027. if (!data.hasValue(newIndex)) {
  37028. group.remove(el);
  37029. el = null;
  37030. return;
  37031. }
  37032. var isClipped = false;
  37033. if (needsClip) {
  37034. isClipped = clip[coord.type](coordSysClipArea, layout);
  37035. if (isClipped) {
  37036. group.remove(el);
  37037. }
  37038. }
  37039. if (!el) {
  37040. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  37041. } // Not change anything if only order changed.
  37042. // Especially not change label.
  37043. if (!isChangeOrder) {
  37044. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  37045. }
  37046. if (isInitSort) {
  37047. el.attr({
  37048. shape: layout
  37049. });
  37050. } else if (realtimeSortCfg) {
  37051. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  37052. } else {
  37053. updateProps(el, {
  37054. shape: layout
  37055. }, seriesModel, newIndex, null);
  37056. }
  37057. data.setItemGraphicEl(newIndex, el);
  37058. el.ignore = isClipped;
  37059. group.add(el);
  37060. }).remove(function (dataIndex) {
  37061. var el = oldData.getItemGraphicEl(dataIndex);
  37062. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  37063. }).execute();
  37064. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  37065. bgGroup.removeAll();
  37066. for (var i = 0; i < bgEls.length; ++i) {
  37067. bgGroup.add(bgEls[i]);
  37068. }
  37069. group.add(bgGroup);
  37070. this._backgroundEls = bgEls;
  37071. this._data = data;
  37072. };
  37073. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  37074. this._clear();
  37075. createLarge(seriesModel, this.group);
  37076. this._updateLargeClip(seriesModel);
  37077. };
  37078. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  37079. this._removeBackground();
  37080. createLarge(seriesModel, this.group, true);
  37081. };
  37082. BarView.prototype._updateLargeClip = function (seriesModel) {
  37083. // Use clipPath in large mode.
  37084. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  37085. if (clipPath) {
  37086. this.group.setClipPath(clipPath);
  37087. } else {
  37088. this.group.removeClipPath();
  37089. }
  37090. };
  37091. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  37092. var _this = this; // If no data in the first frame, wait for data to initSort
  37093. if (!data.count()) {
  37094. return;
  37095. }
  37096. var baseAxis = realtimeSortCfg.baseAxis;
  37097. if (this._isFirstFrame) {
  37098. this._dispatchInitSort(data, realtimeSortCfg, api);
  37099. this._isFirstFrame = false;
  37100. } else {
  37101. var orderMapping_1 = function (idx) {
  37102. var el = data.getItemGraphicEl(idx);
  37103. if (el) {
  37104. var shape = el.shape; // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  37105. return (baseAxis.isHorizontal() // The result should be consistent with the initial sort by data value.
  37106. // Do not support the case that both positive and negative exist.
  37107. ? Math.abs(shape.height) : Math.abs(shape.width)) || 0;
  37108. } else {
  37109. return 0;
  37110. }
  37111. };
  37112. this._onRendered = function () {
  37113. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  37114. };
  37115. api.getZr().on('rendered', this._onRendered);
  37116. }
  37117. };
  37118. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  37119. var info = [];
  37120. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  37121. var mappedValue = orderMapping(dataIdx);
  37122. mappedValue = mappedValue == null ? NaN : mappedValue;
  37123. info.push({
  37124. dataIndex: dataIdx,
  37125. mappedValue: mappedValue,
  37126. ordinalNumber: ordinalNumber
  37127. });
  37128. });
  37129. info.sort(function (a, b) {
  37130. // If NaN, it will be treated as min val.
  37131. return b.mappedValue - a.mappedValue;
  37132. });
  37133. return {
  37134. ordinalNumbers: map(info, function (item) {
  37135. return item.ordinalNumber;
  37136. })
  37137. };
  37138. };
  37139. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  37140. var scale = baseAxis.scale;
  37141. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  37142. var lastValue = Number.MAX_VALUE;
  37143. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  37144. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  37145. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  37146. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  37147. : orderMapping(data.indexOfRawIndex(rawIdx));
  37148. if (value > lastValue) {
  37149. return true;
  37150. }
  37151. lastValue = value;
  37152. }
  37153. return false;
  37154. };
  37155. /*
  37156. * Consider the case when A and B changed order, whose representing
  37157. * bars are both out of sight, we don't wish to trigger reorder action
  37158. * as long as the order in the view doesn't change.
  37159. */
  37160. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  37161. var scale = baseAxis.scale;
  37162. var extent = scale.getExtent();
  37163. var tickNum = Math.max(0, extent[0]);
  37164. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  37165. for (; tickNum <= tickMax; ++tickNum) {
  37166. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  37167. return true;
  37168. }
  37169. }
  37170. };
  37171. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  37172. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  37173. return;
  37174. }
  37175. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  37176. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  37177. this._removeOnRenderedListener(api);
  37178. api.dispatchAction({
  37179. type: 'changeAxisOrder',
  37180. componentType: baseAxis.dim + 'Axis',
  37181. axisId: baseAxis.index,
  37182. sortInfo: sortInfo
  37183. });
  37184. }
  37185. };
  37186. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  37187. var baseAxis = realtimeSortCfg.baseAxis;
  37188. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  37189. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  37190. });
  37191. api.dispatchAction({
  37192. type: 'changeAxisOrder',
  37193. componentType: baseAxis.dim + 'Axis',
  37194. isInitSort: true,
  37195. axisId: baseAxis.index,
  37196. sortInfo: sortResult,
  37197. animation: {
  37198. // Update the axis label from the natural initial layout to
  37199. // sorted layout should has no animation.
  37200. duration: 0
  37201. }
  37202. });
  37203. };
  37204. BarView.prototype.remove = function (ecModel, api) {
  37205. this._clear(this._model);
  37206. this._removeOnRenderedListener(api);
  37207. };
  37208. BarView.prototype.dispose = function (ecModel, api) {
  37209. this._removeOnRenderedListener(api);
  37210. };
  37211. BarView.prototype._removeOnRenderedListener = function (api) {
  37212. if (this._onRendered) {
  37213. api.getZr().off('rendered', this._onRendered);
  37214. this._onRendered = null;
  37215. }
  37216. };
  37217. BarView.prototype._clear = function (model) {
  37218. var group = this.group;
  37219. var data = this._data;
  37220. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  37221. this._removeBackground();
  37222. this._backgroundEls = [];
  37223. data.eachItemGraphicEl(function (el) {
  37224. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  37225. });
  37226. } else {
  37227. group.removeAll();
  37228. }
  37229. this._data = null;
  37230. this._isFirstFrame = true;
  37231. };
  37232. BarView.prototype._removeBackground = function () {
  37233. this.group.remove(this._backgroundGroup);
  37234. this._backgroundGroup = null;
  37235. };
  37236. BarView.type = 'bar';
  37237. return BarView;
  37238. }(ChartView);
  37239. var clip = {
  37240. cartesian2d: function (coordSysBoundingRect, layout) {
  37241. var signWidth = layout.width < 0 ? -1 : 1;
  37242. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  37243. if (signWidth < 0) {
  37244. layout.x += layout.width;
  37245. layout.width = -layout.width;
  37246. }
  37247. if (signHeight < 0) {
  37248. layout.y += layout.height;
  37249. layout.height = -layout.height;
  37250. }
  37251. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  37252. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  37253. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  37254. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  37255. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  37256. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  37257. var xClipped = x2 < x;
  37258. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  37259. // But we should also place the element at the edge of the coord sys bounding rect.
  37260. // Beause if data changed and the bar show again, its transition animaiton
  37261. // will begin at this place.
  37262. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  37263. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  37264. layout.width = xClipped ? 0 : x2 - x;
  37265. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  37266. if (signWidth < 0) {
  37267. layout.x += layout.width;
  37268. layout.width = -layout.width;
  37269. }
  37270. if (signHeight < 0) {
  37271. layout.y += layout.height;
  37272. layout.height = -layout.height;
  37273. }
  37274. return xClipped || yClipped;
  37275. },
  37276. polar: function (coordSysClipArea, layout) {
  37277. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  37278. if (signR < 0) {
  37279. var tmp = layout.r;
  37280. layout.r = layout.r0;
  37281. layout.r0 = tmp;
  37282. }
  37283. var r = mathMin$6(layout.r, coordSysClipArea.r);
  37284. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  37285. layout.r = r;
  37286. layout.r0 = r0;
  37287. var clipped = r - r0 < 0; // Reverse back
  37288. if (signR < 0) {
  37289. var tmp = layout.r;
  37290. layout.r = layout.r0;
  37291. layout.r0 = tmp;
  37292. }
  37293. return clipped;
  37294. }
  37295. };
  37296. var elementCreator = {
  37297. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  37298. var rect = new Rect({
  37299. shape: extend({}, layout),
  37300. z2: 1
  37301. });
  37302. rect.__dataIndex = newIndex;
  37303. rect.name = 'item';
  37304. if (animationModel) {
  37305. var rectShape = rect.shape;
  37306. var animateProperty = isHorizontal ? 'height' : 'width';
  37307. rectShape[animateProperty] = 0;
  37308. }
  37309. return rect;
  37310. },
  37311. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  37312. // Keep the same logic with bar in catesion: use end value to control
  37313. // direction. Notice that if clockwise is true (by default), the sector
  37314. // will always draw clockwisely, no matter whether endAngle is greater
  37315. // or less than startAngle.
  37316. var clockwise = layout.startAngle < layout.endAngle;
  37317. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  37318. var sector = new ShapeClass({
  37319. shape: defaults({
  37320. clockwise: clockwise
  37321. }, layout),
  37322. z2: 1
  37323. });
  37324. sector.name = 'item'; // Animation
  37325. if (animationModel) {
  37326. var sectorShape = sector.shape;
  37327. var animateProperty = isRadial ? 'r' : 'endAngle';
  37328. var animateTarget = {};
  37329. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  37330. animateTarget[animateProperty] = layout[animateProperty];
  37331. (isUpdate ? updateProps : initProps)(sector, {
  37332. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  37333. }, animationModel);
  37334. }
  37335. return sector;
  37336. }
  37337. };
  37338. function shouldRealtimeSort(seriesModel, coordSys) {
  37339. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  37340. var baseAxis = coordSys.getBaseAxis();
  37341. if ("development" !== 'production') {
  37342. if (realtimeSortOption) {
  37343. if (baseAxis.type !== 'category') {
  37344. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  37345. }
  37346. if (coordSys.type !== 'cartesian2d') {
  37347. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  37348. }
  37349. }
  37350. }
  37351. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  37352. return {
  37353. baseAxis: baseAxis,
  37354. otherAxis: coordSys.getOtherAxis(baseAxis)
  37355. };
  37356. }
  37357. }
  37358. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  37359. var seriesTarget;
  37360. var axisTarget;
  37361. if (isHorizontal) {
  37362. axisTarget = {
  37363. x: layout.x,
  37364. width: layout.width
  37365. };
  37366. seriesTarget = {
  37367. y: layout.y,
  37368. height: layout.height
  37369. };
  37370. } else {
  37371. axisTarget = {
  37372. y: layout.y,
  37373. height: layout.height
  37374. };
  37375. seriesTarget = {
  37376. x: layout.x,
  37377. width: layout.width
  37378. };
  37379. }
  37380. if (!isChangeOrder) {
  37381. // Keep the original growth animation if only axis order changed.
  37382. // Not start a new animation.
  37383. (isUpdate ? updateProps : initProps)(el, {
  37384. shape: seriesTarget
  37385. }, seriesAnimationModel, newIndex, null);
  37386. }
  37387. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  37388. (isUpdate ? updateProps : initProps)(el, {
  37389. shape: axisTarget
  37390. }, axisAnimationModel, newIndex);
  37391. }
  37392. var getLayout = {
  37393. // itemModel is only used to get borderWidth, which is not needed
  37394. // when calculating bar background layout.
  37395. cartesian2d: function (data, dataIndex, itemModel) {
  37396. var layout = data.getItemLayout(dataIndex);
  37397. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  37398. var signX = layout.width > 0 ? 1 : -1;
  37399. var signY = layout.height > 0 ? 1 : -1;
  37400. return {
  37401. x: layout.x + signX * fixedLineWidth / 2,
  37402. y: layout.y + signY * fixedLineWidth / 2,
  37403. width: layout.width - signX * fixedLineWidth,
  37404. height: layout.height - signY * fixedLineWidth
  37405. };
  37406. },
  37407. polar: function (data, dataIndex, itemModel) {
  37408. var layout = data.getItemLayout(dataIndex);
  37409. return {
  37410. cx: layout.cx,
  37411. cy: layout.cy,
  37412. r0: layout.r0,
  37413. r: layout.r,
  37414. startAngle: layout.startAngle,
  37415. endAngle: layout.endAngle
  37416. };
  37417. }
  37418. };
  37419. function isZeroOnPolar(layout) {
  37420. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  37421. }
  37422. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar) {
  37423. var style = data.getItemVisual(dataIndex, 'style');
  37424. if (!isPolar) {
  37425. el.setShape('r', itemModel.get(BAR_BORDER_RADIUS_QUERY) || 0);
  37426. }
  37427. el.useStyle(style);
  37428. var cursorStyle = itemModel.getShallow('cursor');
  37429. cursorStyle && el.attr('cursor', cursorStyle);
  37430. if (!isPolar) {
  37431. var labelPositionOutside = isHorizontal ? layout.height > 0 ? 'bottom' : 'top' : layout.width > 0 ? 'left' : 'right';
  37432. var labelStatesModels = getLabelStatesModels(itemModel);
  37433. setLabelStyle(el, labelStatesModels, {
  37434. labelFetcher: seriesModel,
  37435. labelDataIndex: dataIndex,
  37436. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37437. inheritColor: style.fill,
  37438. defaultOpacity: style.opacity,
  37439. defaultOutsidePosition: labelPositionOutside
  37440. });
  37441. var label = el.getTextContent();
  37442. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  37443. return getDefaultInterpolatedLabel(data, value);
  37444. });
  37445. }
  37446. var emphasisModel = itemModel.getModel(['emphasis']);
  37447. enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  37448. setStatesStylesFromModel(el, itemModel);
  37449. if (isZeroOnPolar(layout)) {
  37450. el.style.fill = 'none';
  37451. el.style.stroke = 'none';
  37452. each(el.states, function (state) {
  37453. if (state.style) {
  37454. state.style.fill = state.style.stroke = 'none';
  37455. }
  37456. });
  37457. }
  37458. } // In case width or height are too small.
  37459. function getLineWidth(itemModel, rawLayout) {
  37460. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0; // width or height may be NaN for empty data
  37461. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  37462. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  37463. return Math.min(lineWidth, width, height);
  37464. }
  37465. var LagePathShape =
  37466. /** @class */
  37467. function () {
  37468. function LagePathShape() {}
  37469. return LagePathShape;
  37470. }();
  37471. var LargePath =
  37472. /** @class */
  37473. function (_super) {
  37474. __extends(LargePath, _super);
  37475. function LargePath(opts) {
  37476. var _this = _super.call(this, opts) || this;
  37477. _this.type = 'largeBar';
  37478. return _this;
  37479. }
  37480. LargePath.prototype.getDefaultShape = function () {
  37481. return new LagePathShape();
  37482. };
  37483. LargePath.prototype.buildPath = function (ctx, shape) {
  37484. // Drawing lines is more efficient than drawing
  37485. // a whole line or drawing rects.
  37486. var points = shape.points;
  37487. var startPoint = this.__startPoint;
  37488. var baseDimIdx = this.__baseDimIdx;
  37489. for (var i = 0; i < points.length; i += 2) {
  37490. startPoint[baseDimIdx] = points[i + baseDimIdx];
  37491. ctx.moveTo(startPoint[0], startPoint[1]);
  37492. ctx.lineTo(points[i], points[i + 1]);
  37493. }
  37494. };
  37495. return LargePath;
  37496. }(Path);
  37497. function createLarge(seriesModel, group, incremental) {
  37498. // TODO support polar
  37499. var data = seriesModel.getData();
  37500. var startPoint = [];
  37501. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  37502. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  37503. var largeDataIndices = data.getLayout('largeDataIndices');
  37504. var barWidth = data.getLayout('barWidth');
  37505. var backgroundModel = seriesModel.getModel('backgroundStyle');
  37506. var drawBackground = seriesModel.get('showBackground', true);
  37507. if (drawBackground) {
  37508. var points = data.getLayout('largeBackgroundPoints');
  37509. var backgroundStartPoint = [];
  37510. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  37511. var bgEl = new LargePath({
  37512. shape: {
  37513. points: points
  37514. },
  37515. incremental: !!incremental,
  37516. silent: true,
  37517. z2: 0
  37518. });
  37519. bgEl.__startPoint = backgroundStartPoint;
  37520. bgEl.__baseDimIdx = baseDimIdx;
  37521. bgEl.__largeDataIndices = largeDataIndices;
  37522. bgEl.__barWidth = barWidth;
  37523. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  37524. group.add(bgEl);
  37525. }
  37526. var el = new LargePath({
  37527. shape: {
  37528. points: data.getLayout('largePoints')
  37529. },
  37530. incremental: !!incremental
  37531. });
  37532. el.__startPoint = startPoint;
  37533. el.__baseDimIdx = baseDimIdx;
  37534. el.__largeDataIndices = largeDataIndices;
  37535. el.__barWidth = barWidth;
  37536. group.add(el);
  37537. setLargeStyle(el, seriesModel, data); // Enable tooltip and user mouse/touch event handlers.
  37538. getECData(el).seriesIndex = seriesModel.seriesIndex;
  37539. if (!seriesModel.get('silent')) {
  37540. el.on('mousedown', largePathUpdateDataIndex);
  37541. el.on('mousemove', largePathUpdateDataIndex);
  37542. }
  37543. } // Use throttle to avoid frequently traverse to find dataIndex.
  37544. var largePathUpdateDataIndex = throttle(function (event) {
  37545. var largePath = this;
  37546. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  37547. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  37548. }, 30, false);
  37549. function largePathFindDataIndex(largePath, x, y) {
  37550. var baseDimIdx = largePath.__baseDimIdx;
  37551. var valueDimIdx = 1 - baseDimIdx;
  37552. var points = largePath.shape.points;
  37553. var largeDataIndices = largePath.__largeDataIndices;
  37554. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  37555. var startValueVal = largePath.__startPoint[valueDimIdx];
  37556. _eventPos[0] = x;
  37557. _eventPos[1] = y;
  37558. var pointerBaseVal = _eventPos[baseDimIdx];
  37559. var pointerValueVal = _eventPos[1 - baseDimIdx];
  37560. var baseLowerBound = pointerBaseVal - barWidthHalf;
  37561. var baseUpperBound = pointerBaseVal + barWidthHalf;
  37562. for (var i = 0, len = points.length / 2; i < len; i++) {
  37563. var ii = i * 2;
  37564. var barBaseVal = points[ii + baseDimIdx];
  37565. var barValueVal = points[ii + valueDimIdx];
  37566. if (barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound && (startValueVal <= barValueVal ? pointerValueVal >= startValueVal && pointerValueVal <= barValueVal : pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)) {
  37567. return largeDataIndices[i];
  37568. }
  37569. }
  37570. return -1;
  37571. }
  37572. function setLargeStyle(el, seriesModel, data) {
  37573. var globalStyle = data.getVisual('style');
  37574. el.useStyle(extend({}, globalStyle)); // Use stroke instead of fill.
  37575. el.style.fill = null;
  37576. el.style.stroke = globalStyle.fill;
  37577. el.style.lineWidth = data.getLayout('barWidth');
  37578. }
  37579. function setLargeBackgroundStyle(el, backgroundModel, data) {
  37580. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  37581. var itemStyle = backgroundModel.getItemStyle();
  37582. el.useStyle(itemStyle);
  37583. el.style.fill = null;
  37584. el.style.stroke = borderColor;
  37585. el.style.lineWidth = data.getLayout('barWidth');
  37586. }
  37587. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  37588. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  37589. var rectShape = layout;
  37590. var coordLayout = coord.getArea();
  37591. return {
  37592. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  37593. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  37594. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  37595. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  37596. };
  37597. } else {
  37598. var coordLayout = coord.getArea();
  37599. var sectorShape = layout;
  37600. return {
  37601. cx: coordLayout.cx,
  37602. cy: coordLayout.cy,
  37603. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  37604. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  37605. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  37606. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  37607. };
  37608. }
  37609. }
  37610. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  37611. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  37612. return new ElementClz({
  37613. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  37614. silent: true,
  37615. z2: 0
  37616. });
  37617. }
  37618. function install$3(registers) {
  37619. registers.registerChartView(BarView);
  37620. registers.registerSeriesModel(BarSeriesModel);
  37621. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Use higher prority to avoid to be blocked by other overall layout, which do not
  37622. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  37623. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  37624. registers.registerVisual({
  37625. seriesType: 'bar',
  37626. reset: function (seriesModel) {
  37627. // Visual coding for legend
  37628. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  37629. }
  37630. }); // Down sample after filter
  37631. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  37632. /**
  37633. * @payload
  37634. * @property {string} [componentType=series]
  37635. * @property {number} [dx]
  37636. * @property {number} [dy]
  37637. * @property {number} [zoom]
  37638. * @property {number} [originX]
  37639. * @property {number} [originY]
  37640. */
  37641. registers.registerAction({
  37642. type: 'changeAxisOrder',
  37643. event: 'changeAxisOrder',
  37644. update: 'update'
  37645. }, function (payload, ecModel) {
  37646. var componentType = payload.componentType || 'series';
  37647. ecModel.eachComponent({
  37648. mainType: componentType,
  37649. query: payload
  37650. }, function (componentModel) {
  37651. if (payload.sortInfo) {
  37652. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  37653. }
  37654. });
  37655. });
  37656. }
  37657. var PI2$8 = Math.PI * 2;
  37658. var RADIAN = Math.PI / 180;
  37659. function getViewRect(seriesModel, api) {
  37660. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  37661. width: api.getWidth(),
  37662. height: api.getHeight()
  37663. });
  37664. }
  37665. function pieLayout(seriesType, ecModel, api) {
  37666. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37667. var data = seriesModel.getData();
  37668. var valueDim = data.mapDimension('value');
  37669. var viewRect = getViewRect(seriesModel, api);
  37670. var center = seriesModel.get('center');
  37671. var radius = seriesModel.get('radius');
  37672. if (!isArray(radius)) {
  37673. radius = [0, radius];
  37674. }
  37675. if (!isArray(center)) {
  37676. center = [center, center];
  37677. }
  37678. var width = parsePercent$1(viewRect.width, api.getWidth());
  37679. var height = parsePercent$1(viewRect.height, api.getHeight());
  37680. var size = Math.min(width, height);
  37681. var cx = parsePercent$1(center[0], width) + viewRect.x;
  37682. var cy = parsePercent$1(center[1], height) + viewRect.y;
  37683. var r0 = parsePercent$1(radius[0], size / 2);
  37684. var r = parsePercent$1(radius[1], size / 2);
  37685. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  37686. var minAngle = seriesModel.get('minAngle') * RADIAN;
  37687. var validDataCount = 0;
  37688. data.each(valueDim, function (value) {
  37689. !isNaN(value) && validDataCount++;
  37690. });
  37691. var sum = data.getSum(valueDim); // Sum may be 0
  37692. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  37693. var clockwise = seriesModel.get('clockwise');
  37694. var roseType = seriesModel.get('roseType');
  37695. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  37696. var extent = data.getDataExtent(valueDim);
  37697. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  37698. var restAngle = PI2$8;
  37699. var valueSumLargerThanMinAngle = 0;
  37700. var currentAngle = startAngle;
  37701. var dir = clockwise ? 1 : -1;
  37702. data.setLayout({
  37703. viewRect: viewRect,
  37704. r: r
  37705. });
  37706. data.each(valueDim, function (value, idx) {
  37707. var angle;
  37708. if (isNaN(value)) {
  37709. data.setItemLayout(idx, {
  37710. angle: NaN,
  37711. startAngle: NaN,
  37712. endAngle: NaN,
  37713. clockwise: clockwise,
  37714. cx: cx,
  37715. cy: cy,
  37716. r0: r0,
  37717. r: roseType ? NaN : r
  37718. });
  37719. return;
  37720. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  37721. if (roseType !== 'area') {
  37722. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  37723. } else {
  37724. angle = PI2$8 / validDataCount;
  37725. }
  37726. if (angle < minAngle) {
  37727. angle = minAngle;
  37728. restAngle -= minAngle;
  37729. } else {
  37730. valueSumLargerThanMinAngle += value;
  37731. }
  37732. var endAngle = currentAngle + dir * angle;
  37733. data.setItemLayout(idx, {
  37734. angle: angle,
  37735. startAngle: currentAngle,
  37736. endAngle: endAngle,
  37737. clockwise: clockwise,
  37738. cx: cx,
  37739. cy: cy,
  37740. r0: r0,
  37741. r: roseType ? linearMap(value, extent, [r0, r]) : r
  37742. });
  37743. currentAngle = endAngle;
  37744. }); // Some sector is constrained by minAngle
  37745. // Rest sectors needs recalculate angle
  37746. if (restAngle < PI2$8 && validDataCount) {
  37747. // Average the angle if rest angle is not enough after all angles is
  37748. // Constrained by minAngle
  37749. if (restAngle <= 1e-3) {
  37750. var angle_1 = PI2$8 / validDataCount;
  37751. data.each(valueDim, function (value, idx) {
  37752. if (!isNaN(value)) {
  37753. var layout_1 = data.getItemLayout(idx);
  37754. layout_1.angle = angle_1;
  37755. layout_1.startAngle = startAngle + dir * idx * angle_1;
  37756. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  37757. }
  37758. });
  37759. } else {
  37760. unitRadian = restAngle / valueSumLargerThanMinAngle;
  37761. currentAngle = startAngle;
  37762. data.each(valueDim, function (value, idx) {
  37763. if (!isNaN(value)) {
  37764. var layout_2 = data.getItemLayout(idx);
  37765. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  37766. layout_2.startAngle = currentAngle;
  37767. layout_2.endAngle = currentAngle + dir * angle;
  37768. currentAngle += dir * angle;
  37769. }
  37770. });
  37771. }
  37772. }
  37773. });
  37774. }
  37775. /*
  37776. * Licensed to the Apache Software Foundation (ASF) under one
  37777. * or more contributor license agreements. See the NOTICE file
  37778. * distributed with this work for additional information
  37779. * regarding copyright ownership. The ASF licenses this file
  37780. * to you under the Apache License, Version 2.0 (the
  37781. * "License"); you may not use this file except in compliance
  37782. * with the License. You may obtain a copy of the License at
  37783. *
  37784. * http://www.apache.org/licenses/LICENSE-2.0
  37785. *
  37786. * Unless required by applicable law or agreed to in writing,
  37787. * software distributed under the License is distributed on an
  37788. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37789. * KIND, either express or implied. See the License for the
  37790. * specific language governing permissions and limitations
  37791. * under the License.
  37792. */
  37793. /**
  37794. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37795. */
  37796. /*
  37797. * Licensed to the Apache Software Foundation (ASF) under one
  37798. * or more contributor license agreements. See the NOTICE file
  37799. * distributed with this work for additional information
  37800. * regarding copyright ownership. The ASF licenses this file
  37801. * to you under the Apache License, Version 2.0 (the
  37802. * "License"); you may not use this file except in compliance
  37803. * with the License. You may obtain a copy of the License at
  37804. *
  37805. * http://www.apache.org/licenses/LICENSE-2.0
  37806. *
  37807. * Unless required by applicable law or agreed to in writing,
  37808. * software distributed under the License is distributed on an
  37809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37810. * KIND, either express or implied. See the License for the
  37811. * specific language governing permissions and limitations
  37812. * under the License.
  37813. */
  37814. function dataFilter(seriesType) {
  37815. return {
  37816. seriesType: seriesType,
  37817. reset: function (seriesModel, ecModel) {
  37818. var legendModels = ecModel.findComponents({
  37819. mainType: 'legend'
  37820. });
  37821. if (!legendModels || !legendModels.length) {
  37822. return;
  37823. }
  37824. var data = seriesModel.getData();
  37825. data.filterSelf(function (idx) {
  37826. var name = data.getName(idx); // If in any legend component the status is not selected.
  37827. for (var i = 0; i < legendModels.length; i++) {
  37828. // @ts-ignore FIXME: LegendModel
  37829. if (!legendModels[i].isSelected(name)) {
  37830. return false;
  37831. }
  37832. }
  37833. return true;
  37834. });
  37835. }
  37836. };
  37837. }
  37838. var RADIAN$1 = Math.PI / 180;
  37839. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  37840. if (list.length < 2) {
  37841. return;
  37842. }
  37843. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  37844. var rB = semi.rB;
  37845. var rB2 = rB * rB;
  37846. for (var i = 0; i < semi.list.length; i++) {
  37847. var item = semi.list[i];
  37848. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  37849. var rA = r + item.len;
  37850. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  37851. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  37852. item.label.x = cx + (dx + item.len2) * dir;
  37853. }
  37854. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  37855. function recalculateX(items) {
  37856. // Extremes of
  37857. var topSemi = {
  37858. list: [],
  37859. maxY: 0
  37860. };
  37861. var bottomSemi = {
  37862. list: [],
  37863. maxY: 0
  37864. };
  37865. for (var i = 0; i < items.length; i++) {
  37866. if (items[i].labelAlignTo !== 'none') {
  37867. continue;
  37868. }
  37869. var item = items[i];
  37870. var semi = item.label.y > cy ? bottomSemi : topSemi;
  37871. var dy = Math.abs(item.label.y - cy);
  37872. if (dy > semi.maxY) {
  37873. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  37874. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  37875. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  37876. semi.rB = rB;
  37877. semi.maxY = dy;
  37878. }
  37879. semi.list.push(item);
  37880. }
  37881. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  37882. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  37883. }
  37884. var len = list.length;
  37885. for (var i = 0; i < len; i++) {
  37886. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  37887. var dx = list[i].label.x - farthestX;
  37888. list[i].linePoints[1][0] += dx;
  37889. list[i].label.x = farthestX;
  37890. }
  37891. }
  37892. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  37893. recalculateX(list);
  37894. }
  37895. }
  37896. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  37897. var leftList = [];
  37898. var rightList = [];
  37899. var leftmostX = Number.MAX_VALUE;
  37900. var rightmostX = -Number.MAX_VALUE;
  37901. for (var i = 0; i < labelLayoutList.length; i++) {
  37902. var label = labelLayoutList[i].label;
  37903. if (isPositionCenter(labelLayoutList[i])) {
  37904. continue;
  37905. }
  37906. if (label.x < cx) {
  37907. leftmostX = Math.min(leftmostX, label.x);
  37908. leftList.push(labelLayoutList[i]);
  37909. } else {
  37910. rightmostX = Math.max(rightmostX, label.x);
  37911. rightList.push(labelLayoutList[i]);
  37912. }
  37913. }
  37914. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  37915. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  37916. for (var i = 0; i < labelLayoutList.length; i++) {
  37917. var layout = labelLayoutList[i];
  37918. var label = layout.label;
  37919. if (isPositionCenter(layout)) {
  37920. continue;
  37921. }
  37922. var linePoints = layout.linePoints;
  37923. if (linePoints) {
  37924. var isAlignToEdge = layout.labelAlignTo === 'edge';
  37925. var realTextWidth = layout.rect.width;
  37926. var targetTextWidth = void 0;
  37927. if (isAlignToEdge) {
  37928. if (label.x < cx) {
  37929. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  37930. } else {
  37931. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  37932. }
  37933. } else {
  37934. if (label.x < cx) {
  37935. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  37936. } else {
  37937. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  37938. }
  37939. }
  37940. if (targetTextWidth < layout.rect.width) {
  37941. // TODOTODO
  37942. // layout.text = textContain.truncateText(layout.text, targetTextWidth, layout.font);
  37943. layout.label.style.width = targetTextWidth;
  37944. if (layout.labelAlignTo === 'edge') {
  37945. realTextWidth = targetTextWidth; // realTextWidth = textContain.getWidth(layout.text, layout.font);
  37946. }
  37947. }
  37948. var dist = linePoints[1][0] - linePoints[2][0];
  37949. if (isAlignToEdge) {
  37950. if (label.x < cx) {
  37951. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  37952. } else {
  37953. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  37954. }
  37955. } else {
  37956. if (label.x < cx) {
  37957. linePoints[2][0] = label.x + layout.labelDistance;
  37958. } else {
  37959. linePoints[2][0] = label.x - layout.labelDistance;
  37960. }
  37961. linePoints[1][0] = linePoints[2][0] + dist;
  37962. }
  37963. linePoints[1][1] = linePoints[2][1] = label.y;
  37964. }
  37965. }
  37966. }
  37967. function isPositionCenter(sectorShape) {
  37968. // Not change x for center label
  37969. return sectorShape.position === 'center';
  37970. }
  37971. function pieLabelLayout(seriesModel) {
  37972. var data = seriesModel.getData();
  37973. var labelLayoutList = [];
  37974. var cx;
  37975. var cy;
  37976. var hasLabelRotate = false;
  37977. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  37978. var viewRect = data.getLayout('viewRect');
  37979. var r = data.getLayout('r');
  37980. var viewWidth = viewRect.width;
  37981. var viewLeft = viewRect.x;
  37982. var viewTop = viewRect.y;
  37983. var viewHeight = viewRect.height;
  37984. function setNotShow(el) {
  37985. el.ignore = true;
  37986. }
  37987. function isLabelShown(label) {
  37988. if (!label.ignore) {
  37989. return true;
  37990. }
  37991. for (var key in label.states) {
  37992. if (label.states[key].ignore === false) {
  37993. return true;
  37994. }
  37995. }
  37996. return false;
  37997. }
  37998. data.each(function (idx) {
  37999. var sector = data.getItemGraphicEl(idx);
  38000. var sectorShape = sector.shape;
  38001. var label = sector.getTextContent();
  38002. var labelLine = sector.getTextGuideLine();
  38003. var itemModel = data.getItemModel(idx);
  38004. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  38005. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  38006. var labelDistance = labelModel.get('distanceToLabelLine');
  38007. var labelAlignTo = labelModel.get('alignTo');
  38008. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  38009. var bleedMargin = labelModel.get('bleedMargin');
  38010. var labelLineModel = itemModel.getModel('labelLine');
  38011. var labelLineLen = labelLineModel.get('length');
  38012. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  38013. var labelLineLen2 = labelLineModel.get('length2');
  38014. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  38015. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  38016. each(label.states, setNotShow);
  38017. label.ignore = true;
  38018. return;
  38019. }
  38020. if (!isLabelShown(label)) {
  38021. return;
  38022. }
  38023. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  38024. var nx = Math.cos(midAngle);
  38025. var ny = Math.sin(midAngle);
  38026. var textX;
  38027. var textY;
  38028. var linePoints;
  38029. var textAlign;
  38030. cx = sectorShape.cx;
  38031. cy = sectorShape.cy;
  38032. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  38033. if (labelPosition === 'center') {
  38034. textX = sectorShape.cx;
  38035. textY = sectorShape.cy;
  38036. textAlign = 'center';
  38037. } else {
  38038. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  38039. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  38040. textX = x1 + nx * 3;
  38041. textY = y1 + ny * 3;
  38042. if (!isLabelInside) {
  38043. // For roseType
  38044. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  38045. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  38046. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  38047. var y3 = y2;
  38048. if (labelAlignTo === 'edge') {
  38049. // Adjust textX because text align of edge is opposite
  38050. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  38051. } else {
  38052. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  38053. }
  38054. textY = y3;
  38055. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  38056. }
  38057. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  38058. }
  38059. var labelRotate;
  38060. var rotate = labelModel.get('rotate');
  38061. if (typeof rotate === 'number') {
  38062. labelRotate = rotate * (Math.PI / 180);
  38063. } else {
  38064. labelRotate = rotate ? nx < 0 ? -midAngle + Math.PI : -midAngle : 0;
  38065. }
  38066. hasLabelRotate = !!labelRotate;
  38067. label.x = textX;
  38068. label.y = textY;
  38069. label.rotation = labelRotate;
  38070. label.setStyle({
  38071. verticalAlign: 'middle'
  38072. }); // Not sectorShape the inside label
  38073. if (!isLabelInside) {
  38074. var textRect = label.getBoundingRect().clone();
  38075. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  38076. var margin = (label.style.margin || 0) + 2.1;
  38077. textRect.y -= margin / 2;
  38078. textRect.height += margin;
  38079. labelLayoutList.push({
  38080. label: label,
  38081. labelLine: labelLine,
  38082. position: labelPosition,
  38083. len: labelLineLen,
  38084. len2: labelLineLen2,
  38085. minTurnAngle: labelLineModel.get('minTurnAngle'),
  38086. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  38087. surfaceNormal: new Point(nx, ny),
  38088. linePoints: linePoints,
  38089. textAlign: textAlign,
  38090. labelDistance: labelDistance,
  38091. labelAlignTo: labelAlignTo,
  38092. edgeDistance: edgeDistance,
  38093. bleedMargin: bleedMargin,
  38094. rect: textRect
  38095. });
  38096. } else {
  38097. label.setStyle({
  38098. align: textAlign
  38099. });
  38100. var selectState = label.states.select;
  38101. if (selectState) {
  38102. selectState.x += label.x;
  38103. selectState.y += label.y;
  38104. }
  38105. }
  38106. sector.setTextConfig({
  38107. inside: isLabelInside
  38108. });
  38109. });
  38110. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  38111. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  38112. }
  38113. for (var i = 0; i < labelLayoutList.length; i++) {
  38114. var layout = labelLayoutList[i];
  38115. var label = layout.label;
  38116. var labelLine = layout.labelLine;
  38117. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  38118. if (label) {
  38119. label.setStyle({
  38120. align: layout.textAlign
  38121. });
  38122. if (notShowLabel) {
  38123. each(label.states, setNotShow);
  38124. label.ignore = true;
  38125. }
  38126. var selectState = label.states.select;
  38127. if (selectState) {
  38128. selectState.x += label.x;
  38129. selectState.y += label.y;
  38130. }
  38131. }
  38132. if (labelLine) {
  38133. var linePoints = layout.linePoints;
  38134. if (notShowLabel || !linePoints) {
  38135. each(labelLine.states, setNotShow);
  38136. labelLine.ignore = true;
  38137. } else {
  38138. limitTurnAngle(linePoints, layout.minTurnAngle);
  38139. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  38140. labelLine.setShape({
  38141. points: linePoints
  38142. }); // Set the anchor to the midpoint of sector
  38143. label.__hostTarget.textGuideLineConfig = {
  38144. anchor: new Point(linePoints[0][0], linePoints[0][1])
  38145. };
  38146. }
  38147. }
  38148. }
  38149. }
  38150. function getSectorCornerRadius(model, shape) {
  38151. var cornerRadius = model.get('borderRadius');
  38152. if (cornerRadius == null) {
  38153. return null;
  38154. }
  38155. if (!isArray(cornerRadius)) {
  38156. cornerRadius = [cornerRadius, cornerRadius];
  38157. }
  38158. return {
  38159. innerCornerRadius: parsePercent(cornerRadius[0], shape.r0),
  38160. cornerRadius: parsePercent(cornerRadius[1], shape.r)
  38161. };
  38162. }
  38163. /**
  38164. * Piece of pie including Sector, Label, LabelLine
  38165. */
  38166. var PiePiece =
  38167. /** @class */
  38168. function (_super) {
  38169. __extends(PiePiece, _super);
  38170. function PiePiece(data, idx, startAngle) {
  38171. var _this = _super.call(this) || this;
  38172. _this.z2 = 2;
  38173. var polyline = new Polyline();
  38174. var text = new ZRText();
  38175. _this.setTextGuideLine(polyline);
  38176. _this.setTextContent(text);
  38177. _this.updateData(data, idx, startAngle, true);
  38178. return _this;
  38179. }
  38180. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  38181. var sector = this;
  38182. var seriesModel = data.hostModel;
  38183. var itemModel = data.getItemModel(idx);
  38184. var emphasisModel = itemModel.getModel('emphasis');
  38185. var layout = data.getItemLayout(idx);
  38186. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout) || {}, layout);
  38187. if (firstCreate) {
  38188. sector.setShape(sectorShape);
  38189. var animationType = seriesModel.getShallow('animationType');
  38190. if (animationType === 'scale') {
  38191. sector.shape.r = layout.r0;
  38192. initProps(sector, {
  38193. shape: {
  38194. r: layout.r
  38195. }
  38196. }, seriesModel, idx);
  38197. } // Expansion
  38198. else {
  38199. if (startAngle != null) {
  38200. sector.setShape({
  38201. startAngle: startAngle,
  38202. endAngle: startAngle
  38203. });
  38204. initProps(sector, {
  38205. shape: {
  38206. startAngle: layout.startAngle,
  38207. endAngle: layout.endAngle
  38208. }
  38209. }, seriesModel, idx);
  38210. } else {
  38211. sector.shape.endAngle = layout.startAngle;
  38212. updateProps(sector, {
  38213. shape: {
  38214. endAngle: layout.endAngle
  38215. }
  38216. }, seriesModel, idx);
  38217. }
  38218. }
  38219. } else {
  38220. // Transition animation from the old shape
  38221. updateProps(sector, {
  38222. shape: sectorShape
  38223. }, seriesModel, idx);
  38224. }
  38225. sector.useStyle(data.getItemVisual(idx, 'style'));
  38226. setStatesStylesFromModel(sector, itemModel);
  38227. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38228. var offset = seriesModel.get('selectedOffset');
  38229. var dx = Math.cos(midAngle) * offset;
  38230. var dy = Math.sin(midAngle) * offset;
  38231. var cursorStyle = itemModel.getShallow('cursor');
  38232. cursorStyle && sector.attr('cursor', cursorStyle);
  38233. this._updateLabel(seriesModel, data, idx);
  38234. sector.ensureState('emphasis').shape = __assign({
  38235. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  38236. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  38237. extend(sector.ensureState('select'), {
  38238. x: dx,
  38239. y: dy,
  38240. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  38241. });
  38242. extend(sector.ensureState('blur'), {
  38243. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  38244. });
  38245. var labelLine = sector.getTextGuideLine();
  38246. var labelText = sector.getTextContent();
  38247. labelLine && extend(labelLine.ensureState('select'), {
  38248. x: dx,
  38249. y: dy
  38250. }); // TODO: needs dx, dy in zrender?
  38251. extend(labelText.ensureState('select'), {
  38252. x: dx,
  38253. y: dy
  38254. });
  38255. enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  38256. };
  38257. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  38258. var _a;
  38259. var sector = this;
  38260. var itemModel = data.getItemModel(idx);
  38261. var labelLineModel = itemModel.getModel('labelLine');
  38262. var style = data.getItemVisual(idx, 'style');
  38263. var visualColor = style && style.fill;
  38264. var visualOpacity = style && style.opacity;
  38265. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  38266. labelFetcher: data.hostModel,
  38267. labelDataIndex: idx,
  38268. inheritColor: visualColor,
  38269. defaultOpacity: visualOpacity,
  38270. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  38271. });
  38272. var labelText = sector.getTextContent(); // Set textConfig on sector.
  38273. sector.setTextConfig({
  38274. // reset position, rotation
  38275. position: null,
  38276. rotation: null
  38277. }); // Make sure update style on labelText after setLabelStyle.
  38278. // Because setLabelStyle will replace a new style on it.
  38279. labelText.attr({
  38280. z2: 10
  38281. });
  38282. var labelPosition = seriesModel.get(['label', 'position']);
  38283. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  38284. (_a = sector.getTextGuideLine()) === null || _a === void 0 ? void 0 : _a.hide();
  38285. return;
  38286. } // Default use item visual color
  38287. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  38288. stroke: visualColor,
  38289. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  38290. });
  38291. };
  38292. return PiePiece;
  38293. }(Sector); // Pie view
  38294. var PieView =
  38295. /** @class */
  38296. function (_super) {
  38297. __extends(PieView, _super);
  38298. function PieView() {
  38299. var _this = _super !== null && _super.apply(this, arguments) || this;
  38300. _this.ignoreLabelLineUpdate = true;
  38301. return _this;
  38302. }
  38303. PieView.prototype.init = function () {
  38304. var sectorGroup = new Group();
  38305. this._sectorGroup = sectorGroup;
  38306. };
  38307. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  38308. var data = seriesModel.getData();
  38309. var oldData = this._data;
  38310. var group = this.group;
  38311. var startAngle; // First render
  38312. if (!oldData && data.count() > 0) {
  38313. var shape = data.getItemLayout(0);
  38314. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  38315. shape = data.getItemLayout(s);
  38316. }
  38317. if (shape) {
  38318. startAngle = shape.startAngle;
  38319. }
  38320. }
  38321. data.diff(oldData).add(function (idx) {
  38322. var piePiece = new PiePiece(data, idx, startAngle);
  38323. data.setItemGraphicEl(idx, piePiece);
  38324. group.add(piePiece);
  38325. }).update(function (newIdx, oldIdx) {
  38326. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38327. piePiece.updateData(data, newIdx, startAngle);
  38328. piePiece.off('click');
  38329. group.add(piePiece);
  38330. data.setItemGraphicEl(newIdx, piePiece);
  38331. }).remove(function (idx) {
  38332. var piePiece = oldData.getItemGraphicEl(idx);
  38333. removeElementWithFadeOut(piePiece, seriesModel, idx);
  38334. }).execute();
  38335. pieLabelLayout(seriesModel); // Always use initial animation.
  38336. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  38337. this._data = data;
  38338. }
  38339. };
  38340. PieView.prototype.dispose = function () {};
  38341. PieView.prototype.containPoint = function (point, seriesModel) {
  38342. var data = seriesModel.getData();
  38343. var itemLayout = data.getItemLayout(0);
  38344. if (itemLayout) {
  38345. var dx = point[0] - itemLayout.cx;
  38346. var dy = point[1] - itemLayout.cy;
  38347. var radius = Math.sqrt(dx * dx + dy * dy);
  38348. return radius <= itemLayout.r && radius >= itemLayout.r0;
  38349. }
  38350. };
  38351. PieView.type = 'pie';
  38352. return PieView;
  38353. }(ChartView);
  38354. /**
  38355. * [Usage]:
  38356. * (1)
  38357. * createListSimply(seriesModel, ['value']);
  38358. * (2)
  38359. * createListSimply(seriesModel, {
  38360. * coordDimensions: ['value'],
  38361. * dimensionsCount: 5
  38362. * });
  38363. */
  38364. function createListSimply(seriesModel, opt, nameList) {
  38365. opt = isArray(opt) && {
  38366. coordDimensions: opt
  38367. } || extend({}, opt);
  38368. var source = seriesModel.getSource();
  38369. var dimensionsInfo = createDimensions(source, opt);
  38370. var list = new List(dimensionsInfo, seriesModel);
  38371. list.initData(source, nameList);
  38372. return list;
  38373. }
  38374. /*
  38375. * Licensed to the Apache Software Foundation (ASF) under one
  38376. * or more contributor license agreements. See the NOTICE file
  38377. * distributed with this work for additional information
  38378. * regarding copyright ownership. The ASF licenses this file
  38379. * to you under the Apache License, Version 2.0 (the
  38380. * "License"); you may not use this file except in compliance
  38381. * with the License. You may obtain a copy of the License at
  38382. *
  38383. * http://www.apache.org/licenses/LICENSE-2.0
  38384. *
  38385. * Unless required by applicable law or agreed to in writing,
  38386. * software distributed under the License is distributed on an
  38387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38388. * KIND, either express or implied. See the License for the
  38389. * specific language governing permissions and limitations
  38390. * under the License.
  38391. */
  38392. /**
  38393. * AUTO-GENERATED FILE. DO NOT MODIFY.
  38394. */
  38395. /*
  38396. * Licensed to the Apache Software Foundation (ASF) under one
  38397. * or more contributor license agreements. See the NOTICE file
  38398. * distributed with this work for additional information
  38399. * regarding copyright ownership. The ASF licenses this file
  38400. * to you under the Apache License, Version 2.0 (the
  38401. * "License"); you may not use this file except in compliance
  38402. * with the License. You may obtain a copy of the License at
  38403. *
  38404. * http://www.apache.org/licenses/LICENSE-2.0
  38405. *
  38406. * Unless required by applicable law or agreed to in writing,
  38407. * software distributed under the License is distributed on an
  38408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38409. * KIND, either express or implied. See the License for the
  38410. * specific language governing permissions and limitations
  38411. * under the License.
  38412. */
  38413. /**
  38414. * LegendVisualProvider is an bridge that pick encoded color from data and
  38415. * provide to the legend component.
  38416. */
  38417. var LegendVisualProvider =
  38418. /** @class */
  38419. function () {
  38420. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  38421. getDataWithEncodedVisual, // Function to get raw data before filtered.
  38422. getRawData) {
  38423. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  38424. this._getRawData = getRawData;
  38425. }
  38426. LegendVisualProvider.prototype.getAllNames = function () {
  38427. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  38428. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38429. return rawData.mapArray(rawData.getName);
  38430. };
  38431. LegendVisualProvider.prototype.containName = function (name) {
  38432. var rawData = this._getRawData();
  38433. return rawData.indexOfName(name) >= 0;
  38434. };
  38435. LegendVisualProvider.prototype.indexOfName = function (name) {
  38436. // Only get data when necessary.
  38437. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38438. // Invoking Series#getData immediately will throw an error.
  38439. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  38440. return dataWithEncodedVisual.indexOfName(name);
  38441. };
  38442. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  38443. // Get encoded visual properties from final filtered data.
  38444. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  38445. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38446. };
  38447. return LegendVisualProvider;
  38448. }();
  38449. var PieSeriesModel =
  38450. /** @class */
  38451. function (_super) {
  38452. __extends(PieSeriesModel, _super);
  38453. function PieSeriesModel() {
  38454. var _this = _super !== null && _super.apply(this, arguments) || this;
  38455. _this.useColorPaletteOnData = true;
  38456. return _this;
  38457. }
  38458. /**
  38459. * @overwrite
  38460. */
  38461. PieSeriesModel.prototype.init = function (option) {
  38462. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  38463. // Use a function instead of direct access because data reference may changed
  38464. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  38465. this._defaultLabelLine(option);
  38466. };
  38467. /**
  38468. * @overwrite
  38469. */
  38470. PieSeriesModel.prototype.mergeOption = function () {
  38471. _super.prototype.mergeOption.apply(this, arguments);
  38472. };
  38473. /**
  38474. * @overwrite
  38475. */
  38476. PieSeriesModel.prototype.getInitialData = function () {
  38477. return createListSimply(this, {
  38478. coordDimensions: ['value'],
  38479. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38480. });
  38481. };
  38482. /**
  38483. * @overwrite
  38484. */
  38485. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  38486. var data = this.getData();
  38487. var params = _super.prototype.getDataParams.call(this, dataIndex); // FIXME toFixed?
  38488. var valueList = [];
  38489. data.each(data.mapDimension('value'), function (value) {
  38490. valueList.push(value);
  38491. });
  38492. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  38493. params.$vars.push('percent');
  38494. return params;
  38495. };
  38496. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  38497. // Extend labelLine emphasis
  38498. defaultEmphasis(option, 'labelLine', ['show']);
  38499. var labelLineNormalOpt = option.labelLine;
  38500. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  38501. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  38502. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  38503. };
  38504. PieSeriesModel.type = 'series.pie';
  38505. PieSeriesModel.defaultOption = {
  38506. zlevel: 0,
  38507. z: 2,
  38508. legendHoverLink: true,
  38509. // 默认全局居中
  38510. center: ['50%', '50%'],
  38511. radius: [0, '75%'],
  38512. // 默认顺时针
  38513. clockwise: true,
  38514. startAngle: 90,
  38515. // 最小角度改为0
  38516. minAngle: 0,
  38517. // If the angle of a sector less than `minShowLabelAngle`,
  38518. // the label will not be displayed.
  38519. minShowLabelAngle: 0,
  38520. // 选中时扇区偏移量
  38521. selectedOffset: 10,
  38522. // 选择模式,默认关闭,可选single,multiple
  38523. // selectedMode: false,
  38524. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38525. // roseType: null,
  38526. percentPrecision: 2,
  38527. // If still show when all data zero.
  38528. stillShowZeroSum: true,
  38529. // cursor: null,
  38530. left: 0,
  38531. top: 0,
  38532. right: 0,
  38533. bottom: 0,
  38534. width: null,
  38535. height: null,
  38536. label: {
  38537. // color: 'inherit',
  38538. // If rotate around circle
  38539. rotate: 0,
  38540. show: true,
  38541. overflow: 'truncate',
  38542. // 'outer', 'inside', 'center'
  38543. position: 'outer',
  38544. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38545. alignTo: 'none',
  38546. // Closest distance between label and chart edge.
  38547. // Works only position is 'outer' and alignTo is 'edge'.
  38548. edgeDistance: '25%',
  38549. // Works only position is 'outer' and alignTo is not 'edge'.
  38550. bleedMargin: 10,
  38551. // Distance between text and label line.
  38552. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38553. // 默认使用全局文本样式,详见TEXTSTYLE
  38554. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38555. },
  38556. // Enabled when label.normal.position is 'outer'
  38557. labelLine: {
  38558. show: true,
  38559. // 引导线两段中的第一段长度
  38560. length: 15,
  38561. // 引导线两段中的第二段长度
  38562. length2: 15,
  38563. smooth: false,
  38564. minTurnAngle: 90,
  38565. maxSurfaceAngle: 90,
  38566. lineStyle: {
  38567. // color: 各异,
  38568. width: 1,
  38569. type: 'solid'
  38570. }
  38571. },
  38572. itemStyle: {
  38573. borderWidth: 1
  38574. },
  38575. labelLayout: {
  38576. // Hide the overlapped label.
  38577. hideOverlap: true
  38578. },
  38579. emphasis: {
  38580. scale: true,
  38581. scaleSize: 5
  38582. },
  38583. // If use strategy to avoid label overlapping
  38584. avoidLabelOverlap: true,
  38585. // Animation type. Valid values: expansion, scale
  38586. animationType: 'expansion',
  38587. animationDuration: 1000,
  38588. // Animation type when update. Valid values: transition, expansion
  38589. animationTypeUpdate: 'transition',
  38590. animationEasingUpdate: 'cubicInOut',
  38591. animationDurationUpdate: 500,
  38592. animationEasing: 'cubicInOut'
  38593. };
  38594. return PieSeriesModel;
  38595. }(SeriesModel);
  38596. function install$4(registers) {
  38597. registers.registerChartView(PieView);
  38598. registers.registerSeriesModel(PieSeriesModel);
  38599. createLegacyDataSelectAction('pie', registers.registerAction);
  38600. registers.registerLayout(curry(pieLayout, 'pie'));
  38601. registers.registerProcessor(dataFilter('pie'));
  38602. }
  38603. var ScatterSeriesModel =
  38604. /** @class */
  38605. function (_super) {
  38606. __extends(ScatterSeriesModel, _super);
  38607. function ScatterSeriesModel() {
  38608. var _this = _super !== null && _super.apply(this, arguments) || this;
  38609. _this.type = ScatterSeriesModel.type;
  38610. _this.hasSymbolVisual = true;
  38611. return _this;
  38612. }
  38613. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  38614. return createListFromArray(this.getSource(), this, {
  38615. useEncodeDefaulter: true
  38616. });
  38617. };
  38618. ScatterSeriesModel.prototype.getProgressive = function () {
  38619. var progressive = this.option.progressive;
  38620. if (progressive == null) {
  38621. // PENDING
  38622. return this.option.large ? 5e3 : this.get('progressive');
  38623. }
  38624. return progressive;
  38625. };
  38626. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  38627. var progressiveThreshold = this.option.progressiveThreshold;
  38628. if (progressiveThreshold == null) {
  38629. // PENDING
  38630. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  38631. }
  38632. return progressiveThreshold;
  38633. };
  38634. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  38635. return selectors.point(data.getItemLayout(dataIndex));
  38636. };
  38637. ScatterSeriesModel.type = 'series.scatter';
  38638. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  38639. ScatterSeriesModel.defaultOption = {
  38640. coordinateSystem: 'cartesian2d',
  38641. zlevel: 0,
  38642. z: 2,
  38643. legendHoverLink: true,
  38644. symbolSize: 10,
  38645. // symbolRotate: null, // 图形旋转控制
  38646. large: false,
  38647. // Available when large is true
  38648. largeThreshold: 2000,
  38649. // cursor: null,
  38650. itemStyle: {
  38651. opacity: 0.8 // color: 各异
  38652. },
  38653. emphasis: {
  38654. scale: true
  38655. },
  38656. // If clip the overflow graphics
  38657. // Works on cartesian / polar series
  38658. clip: true,
  38659. select: {
  38660. itemStyle: {
  38661. borderColor: '#212121'
  38662. }
  38663. } // progressive: null
  38664. };
  38665. return ScatterSeriesModel;
  38666. }(SeriesModel);
  38667. var BOOST_SIZE_THRESHOLD = 4;
  38668. var LargeSymbolPathShape =
  38669. /** @class */
  38670. function () {
  38671. function LargeSymbolPathShape() {}
  38672. return LargeSymbolPathShape;
  38673. }();
  38674. var LargeSymbolPath =
  38675. /** @class */
  38676. function (_super) {
  38677. __extends(LargeSymbolPath, _super);
  38678. function LargeSymbolPath(opts) {
  38679. return _super.call(this, opts) || this;
  38680. }
  38681. LargeSymbolPath.prototype.getDefaultShape = function () {
  38682. return new LargeSymbolPathShape();
  38683. };
  38684. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  38685. var points = shape.points;
  38686. var size = shape.size;
  38687. var symbolProxy = this.symbolProxy;
  38688. var symbolProxyShape = symbolProxy.shape;
  38689. var ctx = path.getContext ? path.getContext() : path;
  38690. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD; // Do draw in afterBrush.
  38691. if (canBoost) {
  38692. this._ctx = ctx;
  38693. return;
  38694. }
  38695. this._ctx = null;
  38696. for (var i = 0; i < points.length;) {
  38697. var x = points[i++];
  38698. var y = points[i++];
  38699. if (isNaN(x) || isNaN(y)) {
  38700. continue;
  38701. }
  38702. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  38703. continue;
  38704. }
  38705. symbolProxyShape.x = x - size[0] / 2;
  38706. symbolProxyShape.y = y - size[1] / 2;
  38707. symbolProxyShape.width = size[0];
  38708. symbolProxyShape.height = size[1];
  38709. symbolProxy.buildPath(path, symbolProxyShape, true);
  38710. }
  38711. };
  38712. LargeSymbolPath.prototype.afterBrush = function () {
  38713. var shape = this.shape;
  38714. var points = shape.points;
  38715. var size = shape.size;
  38716. var ctx = this._ctx;
  38717. if (!ctx) {
  38718. return;
  38719. } // PENDING If style or other canvas status changed?
  38720. for (var i = 0; i < points.length;) {
  38721. var x = points[i++];
  38722. var y = points[i++];
  38723. if (isNaN(x) || isNaN(y)) {
  38724. continue;
  38725. }
  38726. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  38727. continue;
  38728. } // fillRect is faster than building a rect path and draw.
  38729. // And it support light globalCompositeOperation.
  38730. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  38731. }
  38732. };
  38733. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  38734. // TODO ???
  38735. // Consider transform
  38736. var shape = this.shape;
  38737. var points = shape.points;
  38738. var size = shape.size;
  38739. var w = Math.max(size[0], 4);
  38740. var h = Math.max(size[1], 4); // Not consider transform
  38741. // Treat each element as a rect
  38742. // top down traverse
  38743. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  38744. var i = idx * 2;
  38745. var x0 = points[i] - w / 2;
  38746. var y0 = points[i + 1] - h / 2;
  38747. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  38748. return idx;
  38749. }
  38750. }
  38751. return -1;
  38752. };
  38753. return LargeSymbolPath;
  38754. }(Path);
  38755. var LargeSymbolDraw =
  38756. /** @class */
  38757. function () {
  38758. function LargeSymbolDraw() {
  38759. this.group = new Group();
  38760. }
  38761. LargeSymbolDraw.prototype.isPersistent = function () {
  38762. return !this._incremental;
  38763. };
  38764. /**
  38765. * Update symbols draw by new data
  38766. */
  38767. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  38768. this.group.removeAll();
  38769. var symbolEl = new LargeSymbolPath({
  38770. rectHover: true,
  38771. cursor: 'default'
  38772. });
  38773. symbolEl.setShape({
  38774. points: data.getLayout('points')
  38775. });
  38776. this._setCommon(symbolEl, data, false, opt);
  38777. this.group.add(symbolEl);
  38778. this._incremental = null;
  38779. };
  38780. LargeSymbolDraw.prototype.updateLayout = function (data) {
  38781. if (this._incremental) {
  38782. return;
  38783. }
  38784. var points = data.getLayout('points');
  38785. this.group.eachChild(function (child) {
  38786. if (child.startIndex != null) {
  38787. var len = (child.endIndex - child.startIndex) * 2;
  38788. var byteOffset = child.startIndex * 4 * 2;
  38789. points = new Float32Array(points.buffer, byteOffset, len);
  38790. }
  38791. child.setShape('points', points);
  38792. });
  38793. };
  38794. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  38795. this.group.removeAll();
  38796. this._clearIncremental(); // Only use incremental displayables when data amount is larger than 2 million.
  38797. // PENDING Incremental data?
  38798. if (data.count() > 2e6) {
  38799. if (!this._incremental) {
  38800. this._incremental = new IncrementalDisplayable({
  38801. silent: true
  38802. });
  38803. }
  38804. this.group.add(this._incremental);
  38805. } else {
  38806. this._incremental = null;
  38807. }
  38808. };
  38809. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  38810. var symbolEl;
  38811. if (this._incremental) {
  38812. symbolEl = new LargeSymbolPath();
  38813. this._incremental.addDisplayable(symbolEl, true);
  38814. } else {
  38815. symbolEl = new LargeSymbolPath({
  38816. rectHover: true,
  38817. cursor: 'default',
  38818. startIndex: taskParams.start,
  38819. endIndex: taskParams.end
  38820. });
  38821. symbolEl.incremental = true;
  38822. this.group.add(symbolEl);
  38823. }
  38824. symbolEl.setShape({
  38825. points: data.getLayout('points')
  38826. });
  38827. this._setCommon(symbolEl, data, !!this._incremental, opt);
  38828. };
  38829. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, isIncremental, opt) {
  38830. var hostModel = data.hostModel;
  38831. opt = opt || {};
  38832. var size = data.getVisual('symbolSize');
  38833. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  38834. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  38835. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  38836. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  38837. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  38838. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  38839. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  38840. var globalStyle = data.getVisual('style');
  38841. var visualColor = globalStyle && globalStyle.fill;
  38842. if (visualColor) {
  38843. symbolEl.setColor(visualColor);
  38844. }
  38845. if (!isIncremental) {
  38846. var ecData_1 = getECData(symbolEl); // Enable tooltip
  38847. // PENDING May have performance issue when path is extremely large
  38848. ecData_1.seriesIndex = hostModel.seriesIndex;
  38849. symbolEl.on('mousemove', function (e) {
  38850. ecData_1.dataIndex = null;
  38851. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  38852. if (dataIndex >= 0) {
  38853. // Provide dataIndex for tooltip
  38854. ecData_1.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  38855. }
  38856. });
  38857. }
  38858. };
  38859. LargeSymbolDraw.prototype.remove = function () {
  38860. this._clearIncremental();
  38861. this._incremental = null;
  38862. this.group.removeAll();
  38863. };
  38864. LargeSymbolDraw.prototype._clearIncremental = function () {
  38865. var incremental = this._incremental;
  38866. if (incremental) {
  38867. incremental.clearDisplaybles();
  38868. }
  38869. };
  38870. return LargeSymbolDraw;
  38871. }();
  38872. var ScatterView =
  38873. /** @class */
  38874. function (_super) {
  38875. __extends(ScatterView, _super);
  38876. function ScatterView() {
  38877. var _this = _super !== null && _super.apply(this, arguments) || this;
  38878. _this.type = ScatterView.type;
  38879. return _this;
  38880. }
  38881. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  38882. var data = seriesModel.getData();
  38883. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  38884. symbolDraw.updateData(data, {
  38885. // TODO
  38886. // If this parameter should be a shape or a bounding volume
  38887. // shape will be more general.
  38888. // But bounding volume like bounding rect will be much faster in the contain calculation
  38889. clipShape: this._getClipShape(seriesModel)
  38890. });
  38891. this._finished = true;
  38892. };
  38893. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  38894. var data = seriesModel.getData();
  38895. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  38896. symbolDraw.incrementalPrepareUpdate(data);
  38897. this._finished = false;
  38898. };
  38899. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  38900. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  38901. clipShape: this._getClipShape(seriesModel)
  38902. });
  38903. this._finished = taskParams.end === seriesModel.getData().count();
  38904. };
  38905. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  38906. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  38907. // PENDING
  38908. this.group.dirty();
  38909. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  38910. return {
  38911. update: true
  38912. };
  38913. } else {
  38914. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  38915. if (res.progress) {
  38916. res.progress({
  38917. start: 0,
  38918. end: data.count(),
  38919. count: data.count()
  38920. }, data);
  38921. }
  38922. this._symbolDraw.updateLayout(data);
  38923. }
  38924. };
  38925. ScatterView.prototype._getClipShape = function (seriesModel) {
  38926. var coordSys = seriesModel.coordinateSystem;
  38927. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  38928. return seriesModel.get('clip', true) ? clipArea : null;
  38929. };
  38930. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  38931. var symbolDraw = this._symbolDraw;
  38932. var pipelineContext = seriesModel.pipelineContext;
  38933. var isLargeDraw = pipelineContext.large;
  38934. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  38935. symbolDraw && symbolDraw.remove();
  38936. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  38937. this._isLargeDraw = isLargeDraw;
  38938. this.group.removeAll();
  38939. }
  38940. this.group.add(symbolDraw.group);
  38941. return symbolDraw;
  38942. };
  38943. ScatterView.prototype.remove = function (ecModel, api) {
  38944. this._symbolDraw && this._symbolDraw.remove(true);
  38945. this._symbolDraw = null;
  38946. };
  38947. ScatterView.prototype.dispose = function () {};
  38948. ScatterView.type = 'scatter';
  38949. return ScatterView;
  38950. }(ChartView);
  38951. var GridModel =
  38952. /** @class */
  38953. function (_super) {
  38954. __extends(GridModel, _super);
  38955. function GridModel() {
  38956. return _super !== null && _super.apply(this, arguments) || this;
  38957. }
  38958. GridModel.type = 'grid';
  38959. GridModel.dependencies = ['xAxis', 'yAxis'];
  38960. GridModel.layoutMode = 'box';
  38961. GridModel.defaultOption = {
  38962. show: false,
  38963. zlevel: 0,
  38964. z: 0,
  38965. left: '10%',
  38966. top: 60,
  38967. right: '10%',
  38968. bottom: 70,
  38969. // If grid size contain label
  38970. containLabel: false,
  38971. // width: {totalWidth} - left - right,
  38972. // height: {totalHeight} - top - bottom,
  38973. backgroundColor: 'rgba(0,0,0,0)',
  38974. borderWidth: 1,
  38975. borderColor: '#ccc'
  38976. };
  38977. return GridModel;
  38978. }(ComponentModel);
  38979. var CartesianAxisModel =
  38980. /** @class */
  38981. function (_super) {
  38982. __extends(CartesianAxisModel, _super);
  38983. function CartesianAxisModel() {
  38984. return _super !== null && _super.apply(this, arguments) || this;
  38985. }
  38986. CartesianAxisModel.prototype.getCoordSysModel = function () {
  38987. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  38988. };
  38989. CartesianAxisModel.type = 'cartesian2dAxis';
  38990. return CartesianAxisModel;
  38991. }(ComponentModel);
  38992. mixin(CartesianAxisModel, AxisModelCommonMixin);
  38993. var defaultOption = {
  38994. show: true,
  38995. zlevel: 0,
  38996. z: 0,
  38997. // Inverse the axis.
  38998. inverse: false,
  38999. // Axis name displayed.
  39000. name: '',
  39001. // 'start' | 'middle' | 'end'
  39002. nameLocation: 'end',
  39003. // By degree. By default auto rotate by nameLocation.
  39004. nameRotate: null,
  39005. nameTruncate: {
  39006. maxWidth: null,
  39007. ellipsis: '...',
  39008. placeholder: '.'
  39009. },
  39010. // Use global text style by default.
  39011. nameTextStyle: {},
  39012. // The gap between axisName and axisLine.
  39013. nameGap: 15,
  39014. // Default `false` to support tooltip.
  39015. silent: false,
  39016. // Default `false` to avoid legacy user event listener fail.
  39017. triggerEvent: false,
  39018. tooltip: {
  39019. show: false
  39020. },
  39021. axisPointer: {},
  39022. axisLine: {
  39023. show: true,
  39024. onZero: true,
  39025. onZeroAxisIndex: null,
  39026. lineStyle: {
  39027. color: '#6E7079',
  39028. width: 1,
  39029. type: 'solid'
  39030. },
  39031. // The arrow at both ends the the axis.
  39032. symbol: ['none', 'none'],
  39033. symbolSize: [10, 15]
  39034. },
  39035. axisTick: {
  39036. show: true,
  39037. // Whether axisTick is inside the grid or outside the grid.
  39038. inside: false,
  39039. // The length of axisTick.
  39040. length: 5,
  39041. lineStyle: {
  39042. width: 1
  39043. }
  39044. },
  39045. axisLabel: {
  39046. show: true,
  39047. // Whether axisLabel is inside the grid or outside the grid.
  39048. inside: false,
  39049. rotate: 0,
  39050. // true | false | null/undefined (auto)
  39051. showMinLabel: null,
  39052. // true | false | null/undefined (auto)
  39053. showMaxLabel: null,
  39054. margin: 8,
  39055. // formatter: null,
  39056. fontSize: 12
  39057. },
  39058. splitLine: {
  39059. show: true,
  39060. lineStyle: {
  39061. color: ['#E0E6F1'],
  39062. width: 1,
  39063. type: 'solid'
  39064. }
  39065. },
  39066. splitArea: {
  39067. show: false,
  39068. areaStyle: {
  39069. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  39070. }
  39071. }
  39072. };
  39073. var categoryAxis = merge({
  39074. // The gap at both ends of the axis. For categoryAxis, boolean.
  39075. boundaryGap: true,
  39076. // Set false to faster category collection.
  39077. deduplication: null,
  39078. // splitArea: {
  39079. // show: false
  39080. // },
  39081. splitLine: {
  39082. show: false
  39083. },
  39084. axisTick: {
  39085. // If tick is align with label when boundaryGap is true
  39086. alignWithLabel: false,
  39087. interval: 'auto'
  39088. },
  39089. axisLabel: {
  39090. interval: 'auto'
  39091. }
  39092. }, defaultOption);
  39093. var valueAxis = merge({
  39094. boundaryGap: [0, 0],
  39095. axisLine: {
  39096. // Not shown when other axis is categoryAxis in cartesian
  39097. show: 'auto'
  39098. },
  39099. axisTick: {
  39100. // Not shown when other axis is categoryAxis in cartesian
  39101. show: 'auto'
  39102. },
  39103. // TODO
  39104. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  39105. splitNumber: 5,
  39106. minorTick: {
  39107. // Minor tick, not available for cateogry axis.
  39108. show: false,
  39109. // Split number of minor ticks. The value should be in range of (0, 100)
  39110. splitNumber: 5,
  39111. // Lenght of minor tick
  39112. length: 3,
  39113. // Line style
  39114. lineStyle: {// Default to be same with axisTick
  39115. }
  39116. },
  39117. minorSplitLine: {
  39118. show: false,
  39119. lineStyle: {
  39120. color: '#F4F7FD',
  39121. width: 1
  39122. }
  39123. }
  39124. }, defaultOption);
  39125. var timeAxis = merge({
  39126. scale: true,
  39127. splitNumber: 6,
  39128. axisLabel: {
  39129. // To eliminate labels that are not nice
  39130. showMinLabel: false,
  39131. showMaxLabel: false,
  39132. rich: {
  39133. primary: {
  39134. fontWeight: 'bold'
  39135. }
  39136. }
  39137. },
  39138. splitLine: {
  39139. show: false
  39140. }
  39141. }, valueAxis);
  39142. var logAxis = defaults({
  39143. scale: true,
  39144. logBase: 10
  39145. }, valueAxis);
  39146. var axisDefault = {
  39147. category: categoryAxis,
  39148. value: valueAxis,
  39149. time: timeAxis,
  39150. log: logAxis
  39151. };
  39152. /*
  39153. * Licensed to the Apache Software Foundation (ASF) under one
  39154. * or more contributor license agreements. See the NOTICE file
  39155. * distributed with this work for additional information
  39156. * regarding copyright ownership. The ASF licenses this file
  39157. * to you under the Apache License, Version 2.0 (the
  39158. * "License"); you may not use this file except in compliance
  39159. * with the License. You may obtain a copy of the License at
  39160. *
  39161. * http://www.apache.org/licenses/LICENSE-2.0
  39162. *
  39163. * Unless required by applicable law or agreed to in writing,
  39164. * software distributed under the License is distributed on an
  39165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39166. * KIND, either express or implied. See the License for the
  39167. * specific language governing permissions and limitations
  39168. * under the License.
  39169. */
  39170. /**
  39171. * AUTO-GENERATED FILE. DO NOT MODIFY.
  39172. */
  39173. /*
  39174. * Licensed to the Apache Software Foundation (ASF) under one
  39175. * or more contributor license agreements. See the NOTICE file
  39176. * distributed with this work for additional information
  39177. * regarding copyright ownership. The ASF licenses this file
  39178. * to you under the Apache License, Version 2.0 (the
  39179. * "License"); you may not use this file except in compliance
  39180. * with the License. You may obtain a copy of the License at
  39181. *
  39182. * http://www.apache.org/licenses/LICENSE-2.0
  39183. *
  39184. * Unless required by applicable law or agreed to in writing,
  39185. * software distributed under the License is distributed on an
  39186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39187. * KIND, either express or implied. See the License for the
  39188. * specific language governing permissions and limitations
  39189. * under the License.
  39190. */
  39191. var AXIS_TYPES = {
  39192. value: 1,
  39193. category: 1,
  39194. time: 1,
  39195. log: 1
  39196. };
  39197. /**
  39198. * Generate sub axis model class
  39199. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  39200. */
  39201. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  39202. each(AXIS_TYPES, function (v, axisType) {
  39203. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  39204. var AxisModel =
  39205. /** @class */
  39206. function (_super) {
  39207. __extends(AxisModel, _super);
  39208. function AxisModel() {
  39209. var args = [];
  39210. for (var _i = 0; _i < arguments.length; _i++) {
  39211. args[_i] = arguments[_i];
  39212. }
  39213. var _this = _super.apply(this, args) || this;
  39214. _this.type = axisName + 'Axis.' + axisType;
  39215. return _this;
  39216. }
  39217. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  39218. var layoutMode = fetchLayoutMode(this);
  39219. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  39220. var themeModel = ecModel.getTheme();
  39221. merge(option, themeModel.get(axisType + 'Axis'));
  39222. merge(option, this.getDefaultOption());
  39223. option.type = getAxisType(option);
  39224. if (layoutMode) {
  39225. mergeLayoutParam(option, inputPositionParams, layoutMode);
  39226. }
  39227. };
  39228. AxisModel.prototype.optionUpdated = function () {
  39229. var thisOption = this.option;
  39230. if (thisOption.type === 'category') {
  39231. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  39232. }
  39233. };
  39234. /**
  39235. * Should not be called before all of 'getInitailData' finished.
  39236. * Because categories are collected during initializing data.
  39237. */
  39238. AxisModel.prototype.getCategories = function (rawData) {
  39239. var option = this.option; // FIXME
  39240. // warning if called before all of 'getInitailData' finished.
  39241. if (option.type === 'category') {
  39242. if (rawData) {
  39243. return option.data;
  39244. }
  39245. return this.__ordinalMeta.categories;
  39246. }
  39247. };
  39248. AxisModel.prototype.getOrdinalMeta = function () {
  39249. return this.__ordinalMeta;
  39250. };
  39251. AxisModel.type = axisName + 'Axis.' + axisType;
  39252. AxisModel.defaultOption = defaultOption;
  39253. return AxisModel;
  39254. }(BaseAxisModelClass);
  39255. registers.registerComponentModel(AxisModel);
  39256. });
  39257. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  39258. }
  39259. function getAxisType(option) {
  39260. // Default axis with data is category axis
  39261. return option.type || (option.data ? 'category' : 'value');
  39262. }
  39263. var Cartesian =
  39264. /** @class */
  39265. function () {
  39266. function Cartesian(name) {
  39267. this.type = 'cartesian';
  39268. this._dimList = [];
  39269. this._axes = {};
  39270. this.name = name || '';
  39271. }
  39272. Cartesian.prototype.getAxis = function (dim) {
  39273. return this._axes[dim];
  39274. };
  39275. Cartesian.prototype.getAxes = function () {
  39276. return map(this._dimList, function (dim) {
  39277. return this._axes[dim];
  39278. }, this);
  39279. };
  39280. Cartesian.prototype.getAxesByScale = function (scaleType) {
  39281. scaleType = scaleType.toLowerCase();
  39282. return filter(this.getAxes(), function (axis) {
  39283. return axis.scale.type === scaleType;
  39284. });
  39285. };
  39286. Cartesian.prototype.addAxis = function (axis) {
  39287. var dim = axis.dim;
  39288. this._axes[dim] = axis;
  39289. this._dimList.push(dim);
  39290. };
  39291. return Cartesian;
  39292. }();
  39293. var cartesian2DDimensions = ['x', 'y'];
  39294. function canCalculateAffineTransform(scale) {
  39295. return scale.type === 'interval' || scale.type === 'time';
  39296. }
  39297. var Cartesian2D =
  39298. /** @class */
  39299. function (_super) {
  39300. __extends(Cartesian2D, _super);
  39301. function Cartesian2D() {
  39302. var _this = _super !== null && _super.apply(this, arguments) || this;
  39303. _this.type = 'cartesian2d';
  39304. _this.dimensions = cartesian2DDimensions;
  39305. return _this;
  39306. }
  39307. /**
  39308. * Calculate an affine transform matrix if two axes are time or value.
  39309. * It's mainly for accelartion on the large time series data.
  39310. */
  39311. Cartesian2D.prototype.calcAffineTransform = function () {
  39312. this._transform = this._invTransform = null;
  39313. var xAxisScale = this.getAxis('x').scale;
  39314. var yAxisScale = this.getAxis('y').scale;
  39315. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  39316. return;
  39317. }
  39318. var xScaleExtent = xAxisScale.getExtent();
  39319. var yScaleExtent = yAxisScale.getExtent();
  39320. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  39321. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  39322. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  39323. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  39324. if (!xScaleSpan || !yScaleSpan) {
  39325. return;
  39326. } // Accelerate data to point calculation on the special large time series data.
  39327. var scaleX = (end[0] - start[0]) / xScaleSpan;
  39328. var scaleY = (end[1] - start[1]) / yScaleSpan;
  39329. var translateX = start[0] - xScaleExtent[0] * scaleX;
  39330. var translateY = start[1] - yScaleExtent[0] * scaleY;
  39331. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  39332. this._invTransform = invert([], m);
  39333. };
  39334. /**
  39335. * Base axis will be used on stacking.
  39336. */
  39337. Cartesian2D.prototype.getBaseAxis = function () {
  39338. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  39339. };
  39340. Cartesian2D.prototype.containPoint = function (point) {
  39341. var axisX = this.getAxis('x');
  39342. var axisY = this.getAxis('y');
  39343. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  39344. };
  39345. Cartesian2D.prototype.containData = function (data) {
  39346. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  39347. };
  39348. Cartesian2D.prototype.dataToPoint = function (data, reserved, out) {
  39349. out = out || [];
  39350. var xVal = data[0];
  39351. var yVal = data[1]; // Fast path
  39352. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  39353. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  39354. return applyTransform(out, data, this._transform);
  39355. }
  39356. var xAxis = this.getAxis('x');
  39357. var yAxis = this.getAxis('y');
  39358. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));
  39359. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));
  39360. return out;
  39361. };
  39362. Cartesian2D.prototype.clampData = function (data, out) {
  39363. var xScale = this.getAxis('x').scale;
  39364. var yScale = this.getAxis('y').scale;
  39365. var xAxisExtent = xScale.getExtent();
  39366. var yAxisExtent = yScale.getExtent();
  39367. var x = xScale.parse(data[0]);
  39368. var y = yScale.parse(data[1]);
  39369. out = out || [];
  39370. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  39371. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  39372. return out;
  39373. };
  39374. Cartesian2D.prototype.pointToData = function (point, out) {
  39375. out = out || [];
  39376. if (this._invTransform) {
  39377. return applyTransform(out, point, this._invTransform);
  39378. }
  39379. var xAxis = this.getAxis('x');
  39380. var yAxis = this.getAxis('y');
  39381. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  39382. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  39383. return out;
  39384. };
  39385. Cartesian2D.prototype.getOtherAxis = function (axis) {
  39386. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  39387. };
  39388. /**
  39389. * Get rect area of cartesian.
  39390. * Area will have a contain function to determine if a point is in the coordinate system.
  39391. */
  39392. Cartesian2D.prototype.getArea = function () {
  39393. var xExtent = this.getAxis('x').getGlobalExtent();
  39394. var yExtent = this.getAxis('y').getGlobalExtent();
  39395. var x = Math.min(xExtent[0], xExtent[1]);
  39396. var y = Math.min(yExtent[0], yExtent[1]);
  39397. var width = Math.max(xExtent[0], xExtent[1]) - x;
  39398. var height = Math.max(yExtent[0], yExtent[1]) - y;
  39399. return new BoundingRect(x, y, width, height);
  39400. };
  39401. return Cartesian2D;
  39402. }(Cartesian);
  39403. var Axis2D =
  39404. /** @class */
  39405. function (_super) {
  39406. __extends(Axis2D, _super);
  39407. function Axis2D(dim, scale, coordExtent, axisType, position) {
  39408. var _this = _super.call(this, dim, scale, coordExtent) || this;
  39409. /**
  39410. * Index of axis, can be used as key
  39411. * Injected outside.
  39412. */
  39413. _this.index = 0;
  39414. _this.type = axisType || 'value';
  39415. _this.position = position || 'bottom';
  39416. return _this;
  39417. }
  39418. Axis2D.prototype.isHorizontal = function () {
  39419. var position = this.position;
  39420. return position === 'top' || position === 'bottom';
  39421. };
  39422. /**
  39423. * Each item cooresponds to this.getExtent(), which
  39424. * means globalExtent[0] may greater than globalExtent[1],
  39425. * unless `asc` is input.
  39426. *
  39427. * @param {boolean} [asc]
  39428. * @return {Array.<number>}
  39429. */
  39430. Axis2D.prototype.getGlobalExtent = function (asc) {
  39431. var ret = this.getExtent();
  39432. ret[0] = this.toGlobalCoord(ret[0]);
  39433. ret[1] = this.toGlobalCoord(ret[1]);
  39434. asc && ret[0] > ret[1] && ret.reverse();
  39435. return ret;
  39436. };
  39437. Axis2D.prototype.pointToData = function (point, clamp) {
  39438. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  39439. };
  39440. /**
  39441. * Set ordinalSortInfo
  39442. * @param info new OrdinalSortInfo
  39443. */
  39444. Axis2D.prototype.setCategorySortInfo = function (info) {
  39445. if (this.type !== 'category') {
  39446. return false;
  39447. }
  39448. this.model.option.categorySortInfo = info;
  39449. this.scale.setSortInfo(info);
  39450. };
  39451. return Axis2D;
  39452. }(Axis);
  39453. /**
  39454. * Can only be called after coordinate system creation stage.
  39455. * (Can be called before coordinate system update stage).
  39456. */
  39457. function layout$1(gridModel, axisModel, opt) {
  39458. opt = opt || {};
  39459. var grid = gridModel.coordinateSystem;
  39460. var axis = axisModel.axis;
  39461. var layout = {};
  39462. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  39463. var rawAxisPosition = axis.position;
  39464. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  39465. var axisDim = axis.dim;
  39466. var rect = grid.getRect();
  39467. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  39468. var idx = {
  39469. left: 0,
  39470. right: 1,
  39471. top: 0,
  39472. bottom: 1,
  39473. onZero: 2
  39474. };
  39475. var axisOffset = axisModel.get('offset') || 0;
  39476. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  39477. if (otherAxisOnZeroOf) {
  39478. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  39479. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  39480. } // Axis position
  39481. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  39482. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  39483. var dirMap = {
  39484. top: -1,
  39485. bottom: 1,
  39486. left: -1,
  39487. right: 1
  39488. };
  39489. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  39490. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  39491. if (axisModel.get(['axisTick', 'inside'])) {
  39492. layout.tickDirection = -layout.tickDirection;
  39493. }
  39494. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  39495. layout.labelDirection = -layout.labelDirection;
  39496. } // Special label rotation
  39497. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  39498. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  39499. layout.z2 = 1;
  39500. return layout;
  39501. }
  39502. function isCartesian2DSeries(seriesModel) {
  39503. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  39504. }
  39505. function findAxisModels(seriesModel) {
  39506. var axisModelMap = {
  39507. xAxisModel: null,
  39508. yAxisModel: null
  39509. };
  39510. each(axisModelMap, function (v, key) {
  39511. var axisType = key.replace(/Model$/, '');
  39512. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  39513. if ("development" !== 'production') {
  39514. if (!axisModel) {
  39515. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  39516. }
  39517. }
  39518. axisModelMap[key] = axisModel;
  39519. });
  39520. return axisModelMap;
  39521. }
  39522. var Grid =
  39523. /** @class */
  39524. function () {
  39525. function Grid(gridModel, ecModel, api) {
  39526. // FIXME:TS where used (different from registered type 'cartesian2d')?
  39527. this.type = 'grid';
  39528. this._coordsMap = {};
  39529. this._coordsList = [];
  39530. this._axesMap = {};
  39531. this._axesList = [];
  39532. this.axisPointerEnabled = true;
  39533. this.dimensions = cartesian2DDimensions;
  39534. this._initCartesian(gridModel, ecModel, api);
  39535. this.model = gridModel;
  39536. }
  39537. Grid.prototype.getRect = function () {
  39538. return this._rect;
  39539. };
  39540. Grid.prototype.update = function (ecModel, api) {
  39541. var axesMap = this._axesMap;
  39542. this._updateScale(ecModel, this.model);
  39543. each(axesMap.x, function (xAxis) {
  39544. niceScaleExtent(xAxis.scale, xAxis.model);
  39545. });
  39546. each(axesMap.y, function (yAxis) {
  39547. niceScaleExtent(yAxis.scale, yAxis.model);
  39548. }); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  39549. var onZeroRecords = {};
  39550. each(axesMap.x, function (xAxis) {
  39551. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  39552. });
  39553. each(axesMap.y, function (yAxis) {
  39554. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  39555. }); // Resize again if containLabel is enabled
  39556. // FIXME It may cause getting wrong grid size in data processing stage
  39557. this.resize(this.model, api);
  39558. };
  39559. /**
  39560. * Resize the grid
  39561. */
  39562. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  39563. var boxLayoutParams = gridModel.getBoxLayoutParams();
  39564. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  39565. var gridRect = getLayoutRect(boxLayoutParams, {
  39566. width: api.getWidth(),
  39567. height: api.getHeight()
  39568. });
  39569. this._rect = gridRect;
  39570. var axesList = this._axesList;
  39571. adjustAxes(); // Minus label size
  39572. if (isContainLabel) {
  39573. each(axesList, function (axis) {
  39574. if (!axis.model.get(['axisLabel', 'inside'])) {
  39575. var labelUnionRect = estimateLabelUnionRect(axis);
  39576. if (labelUnionRect) {
  39577. var dim = axis.isHorizontal() ? 'height' : 'width';
  39578. var margin = axis.model.get(['axisLabel', 'margin']);
  39579. gridRect[dim] -= labelUnionRect[dim] + margin;
  39580. if (axis.position === 'top') {
  39581. gridRect.y += labelUnionRect.height + margin;
  39582. } else if (axis.position === 'left') {
  39583. gridRect.x += labelUnionRect.width + margin;
  39584. }
  39585. }
  39586. }
  39587. });
  39588. adjustAxes();
  39589. }
  39590. each(this._coordsList, function (coord) {
  39591. // Calculate affine matrix to accelerate the data to point transform.
  39592. // If all the axes scales are time or value.
  39593. coord.calcAffineTransform();
  39594. });
  39595. function adjustAxes() {
  39596. each(axesList, function (axis) {
  39597. var isHorizontal = axis.isHorizontal();
  39598. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  39599. var idx = axis.inverse ? 1 : 0;
  39600. axis.setExtent(extent[idx], extent[1 - idx]);
  39601. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  39602. });
  39603. }
  39604. };
  39605. Grid.prototype.getAxis = function (dim, axisIndex) {
  39606. var axesMapOnDim = this._axesMap[dim];
  39607. if (axesMapOnDim != null) {
  39608. return axesMapOnDim[axisIndex || 0]; // if (axisIndex == null) {
  39609. // Find first axis
  39610. // for (let name in axesMapOnDim) {
  39611. // if (axesMapOnDim.hasOwnProperty(name)) {
  39612. // return axesMapOnDim[name];
  39613. // }
  39614. // }
  39615. // }
  39616. // return axesMapOnDim[axisIndex];
  39617. }
  39618. };
  39619. Grid.prototype.getAxes = function () {
  39620. return this._axesList.slice();
  39621. };
  39622. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  39623. if (xAxisIndex != null && yAxisIndex != null) {
  39624. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  39625. return this._coordsMap[key];
  39626. }
  39627. if (isObject(xAxisIndex)) {
  39628. yAxisIndex = xAxisIndex.yAxisIndex;
  39629. xAxisIndex = xAxisIndex.xAxisIndex;
  39630. }
  39631. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  39632. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  39633. return coordList[i];
  39634. }
  39635. }
  39636. };
  39637. Grid.prototype.getCartesians = function () {
  39638. return this._coordsList.slice();
  39639. };
  39640. /**
  39641. * @implements
  39642. */
  39643. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  39644. var target = this._findConvertTarget(finder);
  39645. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  39646. };
  39647. /**
  39648. * @implements
  39649. */
  39650. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  39651. var target = this._findConvertTarget(finder);
  39652. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  39653. };
  39654. Grid.prototype._findConvertTarget = function (finder) {
  39655. var seriesModel = finder.seriesModel;
  39656. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  39657. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  39658. var gridModel = finder.gridModel;
  39659. var coordsList = this._coordsList;
  39660. var cartesian;
  39661. var axis;
  39662. if (seriesModel) {
  39663. cartesian = seriesModel.coordinateSystem;
  39664. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  39665. } else if (xAxisModel && yAxisModel) {
  39666. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  39667. } else if (xAxisModel) {
  39668. axis = this.getAxis('x', xAxisModel.componentIndex);
  39669. } else if (yAxisModel) {
  39670. axis = this.getAxis('y', yAxisModel.componentIndex);
  39671. } // Lowest priority.
  39672. else if (gridModel) {
  39673. var grid = gridModel.coordinateSystem;
  39674. if (grid === this) {
  39675. cartesian = this._coordsList[0];
  39676. }
  39677. }
  39678. return {
  39679. cartesian: cartesian,
  39680. axis: axis
  39681. };
  39682. };
  39683. /**
  39684. * @implements
  39685. */
  39686. Grid.prototype.containPoint = function (point) {
  39687. var coord = this._coordsList[0];
  39688. if (coord) {
  39689. return coord.containPoint(point);
  39690. }
  39691. };
  39692. /**
  39693. * Initialize cartesian coordinate systems
  39694. */
  39695. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  39696. var _this = this;
  39697. var grid = this;
  39698. var axisPositionUsed = {
  39699. left: false,
  39700. right: false,
  39701. top: false,
  39702. bottom: false
  39703. };
  39704. var axesMap = {
  39705. x: {},
  39706. y: {}
  39707. };
  39708. var axesCount = {
  39709. x: 0,
  39710. y: 0
  39711. }; /// Create axis
  39712. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  39713. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  39714. if (!axesCount.x || !axesCount.y) {
  39715. // Roll back when there no either x or y axis
  39716. this._axesMap = {};
  39717. this._axesList = [];
  39718. return;
  39719. }
  39720. this._axesMap = axesMap; /// Create cartesian2d
  39721. each(axesMap.x, function (xAxis, xAxisIndex) {
  39722. each(axesMap.y, function (yAxis, yAxisIndex) {
  39723. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  39724. var cartesian = new Cartesian2D(key);
  39725. cartesian.master = _this;
  39726. cartesian.model = gridModel;
  39727. _this._coordsMap[key] = cartesian;
  39728. _this._coordsList.push(cartesian);
  39729. cartesian.addAxis(xAxis);
  39730. cartesian.addAxis(yAxis);
  39731. });
  39732. });
  39733. function createAxisCreator(dimName) {
  39734. return function (axisModel, idx) {
  39735. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  39736. return;
  39737. }
  39738. var axisPosition = axisModel.get('position');
  39739. if (dimName === 'x') {
  39740. // Fix position
  39741. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  39742. // Default bottom of X
  39743. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  39744. }
  39745. } else {
  39746. // Fix position
  39747. if (axisPosition !== 'left' && axisPosition !== 'right') {
  39748. // Default left of Y
  39749. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  39750. }
  39751. }
  39752. axisPositionUsed[axisPosition] = true;
  39753. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  39754. var isCategory = axis.type === 'category';
  39755. axis.onBand = isCategory && axisModel.get('boundaryGap');
  39756. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  39757. axisModel.axis = axis; // Inject axisModel into axis
  39758. axis.model = axisModel; // Inject grid info axis
  39759. axis.grid = grid; // Index of axis, can be used as key
  39760. axis.index = idx;
  39761. grid._axesList.push(axis);
  39762. axesMap[dimName][idx] = axis;
  39763. axesCount[dimName]++;
  39764. };
  39765. }
  39766. };
  39767. /**
  39768. * Update cartesian properties from series.
  39769. */
  39770. Grid.prototype._updateScale = function (ecModel, gridModel) {
  39771. // Reset scale
  39772. each(this._axesList, function (axis) {
  39773. axis.scale.setExtent(Infinity, -Infinity);
  39774. if (axis.type === 'category') {
  39775. var categorySortInfo = axis.model.get('categorySortInfo');
  39776. axis.scale.setSortInfo(categorySortInfo);
  39777. }
  39778. });
  39779. ecModel.eachSeries(function (seriesModel) {
  39780. if (isCartesian2DSeries(seriesModel)) {
  39781. var axesModelMap = findAxisModels(seriesModel);
  39782. var xAxisModel = axesModelMap.xAxisModel;
  39783. var yAxisModel = axesModelMap.yAxisModel;
  39784. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  39785. return;
  39786. }
  39787. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  39788. var data = seriesModel.getData();
  39789. var xAxis = cartesian.getAxis('x');
  39790. var yAxis = cartesian.getAxis('y');
  39791. if (data.type === 'list') {
  39792. unionExtent(data, xAxis);
  39793. unionExtent(data, yAxis);
  39794. }
  39795. }
  39796. }, this);
  39797. function unionExtent(data, axis) {
  39798. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  39799. axis.scale.unionExtentFromData(data, dim);
  39800. });
  39801. }
  39802. };
  39803. /**
  39804. * @param dim 'x' or 'y' or 'auto' or null/undefined
  39805. */
  39806. Grid.prototype.getTooltipAxes = function (dim) {
  39807. var baseAxes = [];
  39808. var otherAxes = [];
  39809. each(this.getCartesians(), function (cartesian) {
  39810. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  39811. var otherAxis = cartesian.getOtherAxis(baseAxis);
  39812. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  39813. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  39814. });
  39815. return {
  39816. baseAxes: baseAxes,
  39817. otherAxes: otherAxes
  39818. };
  39819. };
  39820. Grid.create = function (ecModel, api) {
  39821. var grids = [];
  39822. ecModel.eachComponent('grid', function (gridModel, idx) {
  39823. var grid = new Grid(gridModel, ecModel, api);
  39824. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  39825. // should be performed in create stage.
  39826. grid.resize(gridModel, api, true);
  39827. gridModel.coordinateSystem = grid;
  39828. grids.push(grid);
  39829. }); // Inject the coordinateSystems into seriesModel
  39830. ecModel.eachSeries(function (seriesModel) {
  39831. if (!isCartesian2DSeries(seriesModel)) {
  39832. return;
  39833. }
  39834. var axesModelMap = findAxisModels(seriesModel);
  39835. var xAxisModel = axesModelMap.xAxisModel;
  39836. var yAxisModel = axesModelMap.yAxisModel;
  39837. var gridModel = xAxisModel.getCoordSysModel();
  39838. if ("development" !== 'production') {
  39839. if (!gridModel) {
  39840. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  39841. }
  39842. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  39843. throw new Error('xAxis and yAxis must use the same grid');
  39844. }
  39845. }
  39846. var grid = gridModel.coordinateSystem;
  39847. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  39848. });
  39849. return grids;
  39850. }; // For deciding which dimensions to use when creating list data
  39851. Grid.dimensions = cartesian2DDimensions;
  39852. return Grid;
  39853. }();
  39854. /**
  39855. * Check if the axis is used in the specified grid.
  39856. */
  39857. function isAxisUsedInTheGrid(axisModel, gridModel) {
  39858. return axisModel.getCoordSysModel() === gridModel;
  39859. }
  39860. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  39861. onZeroRecords) {
  39862. axis.getAxesOnZeroOf = function () {
  39863. // TODO: onZero of multiple axes.
  39864. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  39865. }; // onZero can not be enabled in these two situations:
  39866. // 1. When any other axis is a category axis.
  39867. // 2. When no axis is cross 0 point.
  39868. var otherAxes = axesMap[otherAxisDim];
  39869. var otherAxisOnZeroOf;
  39870. var axisModel = axis.model;
  39871. var onZero = axisModel.get(['axisLine', 'onZero']);
  39872. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  39873. if (!onZero) {
  39874. return;
  39875. } // If target axis is specified.
  39876. if (onZeroAxisIndex != null) {
  39877. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  39878. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  39879. }
  39880. } else {
  39881. // Find the first available other axis.
  39882. for (var idx in otherAxes) {
  39883. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  39884. // if both onZero, the two Y axes overlap.
  39885. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  39886. otherAxisOnZeroOf = otherAxes[idx];
  39887. break;
  39888. }
  39889. }
  39890. }
  39891. if (otherAxisOnZeroOf) {
  39892. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  39893. }
  39894. function getOnZeroRecordKey(axis) {
  39895. return axis.dim + '_' + axis.index;
  39896. }
  39897. }
  39898. function canOnZeroToAxis(axis) {
  39899. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  39900. }
  39901. function updateAxisTransform(axis, coordBase) {
  39902. var axisExtent = axis.getExtent();
  39903. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  39904. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  39905. return coord + coordBase;
  39906. } : function (coord) {
  39907. return axisExtentSum - coord + coordBase;
  39908. };
  39909. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  39910. return coord - coordBase;
  39911. } : function (coord) {
  39912. return axisExtentSum - coord + coordBase;
  39913. };
  39914. }
  39915. var PI$5 = Math.PI;
  39916. /**
  39917. * A final axis is translated and rotated from a "standard axis".
  39918. * So opt.position and opt.rotation is required.
  39919. *
  39920. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  39921. * for example: (0, 0) ------------> (0, 50)
  39922. *
  39923. * nameDirection or tickDirection or labelDirection is 1 means tick
  39924. * or label is below the standard axis, whereas is -1 means above
  39925. * the standard axis. labelOffset means offset between label and axis,
  39926. * which is useful when 'onZero', where axisLabel is in the grid and
  39927. * label in outside grid.
  39928. *
  39929. * Tips: like always,
  39930. * positive rotation represents anticlockwise, and negative rotation
  39931. * represents clockwise.
  39932. * The direction of position coordinate is the same as the direction
  39933. * of screen coordinate.
  39934. *
  39935. * Do not need to consider axis 'inverse', which is auto processed by
  39936. * axis extent.
  39937. */
  39938. var AxisBuilder =
  39939. /** @class */
  39940. function () {
  39941. function AxisBuilder(axisModel, opt) {
  39942. this.group = new Group();
  39943. this.opt = opt;
  39944. this.axisModel = axisModel; // Default value
  39945. defaults(opt, {
  39946. labelOffset: 0,
  39947. nameDirection: 1,
  39948. tickDirection: 1,
  39949. labelDirection: 1,
  39950. silent: true,
  39951. handleAutoShown: function () {
  39952. return true;
  39953. }
  39954. }); // FIXME Not use a seperate text group?
  39955. var transformGroup = new Group({
  39956. x: opt.position[0],
  39957. y: opt.position[1],
  39958. rotation: opt.rotation
  39959. }); // this.group.add(transformGroup);
  39960. // this._transformGroup = transformGroup;
  39961. transformGroup.updateTransform();
  39962. this._transformGroup = transformGroup;
  39963. }
  39964. AxisBuilder.prototype.hasBuilder = function (name) {
  39965. return !!builders[name];
  39966. };
  39967. AxisBuilder.prototype.add = function (name) {
  39968. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  39969. };
  39970. AxisBuilder.prototype.getGroup = function () {
  39971. return this.group;
  39972. };
  39973. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  39974. var rotationDiff = remRadian(textRotation - axisRotation);
  39975. var textAlign;
  39976. var textVerticalAlign;
  39977. if (isRadianAroundZero(rotationDiff)) {
  39978. // Label is parallel with axis line.
  39979. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  39980. textAlign = 'center';
  39981. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  39982. // Label is inverse parallel with axis line.
  39983. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  39984. textAlign = 'center';
  39985. } else {
  39986. textVerticalAlign = 'middle';
  39987. if (rotationDiff > 0 && rotationDiff < PI$5) {
  39988. textAlign = direction > 0 ? 'right' : 'left';
  39989. } else {
  39990. textAlign = direction > 0 ? 'left' : 'right';
  39991. }
  39992. }
  39993. return {
  39994. rotation: rotationDiff,
  39995. textAlign: textAlign,
  39996. textVerticalAlign: textVerticalAlign
  39997. };
  39998. };
  39999. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  40000. var eventData = {
  40001. componentType: axisModel.mainType,
  40002. componentIndex: axisModel.componentIndex
  40003. };
  40004. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  40005. return eventData;
  40006. };
  40007. AxisBuilder.isLabelSilent = function (axisModel) {
  40008. var tooltipOpt = axisModel.get('tooltip');
  40009. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  40010. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  40011. };
  40012. return AxisBuilder;
  40013. }();
  40014. var builders = {
  40015. axisLine: function (opt, axisModel, group, transformGroup) {
  40016. var shown = axisModel.get(['axisLine', 'show']);
  40017. if (shown === 'auto' && opt.handleAutoShown) {
  40018. shown = opt.handleAutoShown('axisLine');
  40019. }
  40020. if (!shown) {
  40021. return;
  40022. }
  40023. var extent = axisModel.axis.getExtent();
  40024. var matrix = transformGroup.transform;
  40025. var pt1 = [extent[0], 0];
  40026. var pt2 = [extent[1], 0];
  40027. if (matrix) {
  40028. applyTransform(pt1, pt1, matrix);
  40029. applyTransform(pt2, pt2, matrix);
  40030. }
  40031. var lineStyle = extend({
  40032. lineCap: 'round'
  40033. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  40034. var line = new Line({
  40035. // Id for animation
  40036. subPixelOptimize: true,
  40037. shape: {
  40038. x1: pt1[0],
  40039. y1: pt1[1],
  40040. x2: pt2[0],
  40041. y2: pt2[1]
  40042. },
  40043. style: lineStyle,
  40044. strokeContainThreshold: opt.strokeContainThreshold || 5,
  40045. silent: true,
  40046. z2: 1
  40047. });
  40048. line.anid = 'line';
  40049. group.add(line);
  40050. var arrows = axisModel.get(['axisLine', 'symbol']);
  40051. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  40052. var arrowOffset = axisModel.get(['axisLine', 'symbolOffset']) || 0;
  40053. if (typeof arrowOffset === 'number') {
  40054. arrowOffset = [arrowOffset, arrowOffset];
  40055. }
  40056. if (arrows != null) {
  40057. if (typeof arrows === 'string') {
  40058. // Use the same arrow for start and end point
  40059. arrows = [arrows, arrows];
  40060. }
  40061. if (typeof arrowSize === 'string' || typeof arrowSize === 'number') {
  40062. // Use the same size for width and height
  40063. arrowSize = [arrowSize, arrowSize];
  40064. }
  40065. var symbolWidth_1 = arrowSize[0];
  40066. var symbolHeight_1 = arrowSize[1];
  40067. each([{
  40068. rotate: opt.rotation + Math.PI / 2,
  40069. offset: arrowOffset[0],
  40070. r: 0
  40071. }, {
  40072. rotate: opt.rotation - Math.PI / 2,
  40073. offset: arrowOffset[1],
  40074. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  40075. }], function (point, index) {
  40076. if (arrows[index] !== 'none' && arrows[index] != null) {
  40077. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  40078. var r = point.r + point.offset;
  40079. symbol.attr({
  40080. rotation: point.rotate,
  40081. x: pt1[0] + r * Math.cos(opt.rotation),
  40082. y: pt1[1] - r * Math.sin(opt.rotation),
  40083. silent: true,
  40084. z2: 11
  40085. });
  40086. group.add(symbol);
  40087. }
  40088. });
  40089. }
  40090. },
  40091. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  40092. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  40093. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  40094. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  40095. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection);
  40096. },
  40097. axisName: function (opt, axisModel, group, transformGroup) {
  40098. var name = retrieve(opt.axisName, axisModel.get('name'));
  40099. if (!name) {
  40100. return;
  40101. }
  40102. var nameLocation = axisModel.get('nameLocation');
  40103. var nameDirection = opt.nameDirection;
  40104. var textStyleModel = axisModel.getModel('nameTextStyle');
  40105. var gap = axisModel.get('nameGap') || 0;
  40106. var extent = axisModel.axis.getExtent();
  40107. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  40108. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  40109. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  40110. var labelLayout;
  40111. var nameRotation = axisModel.get('nameRotate');
  40112. if (nameRotation != null) {
  40113. nameRotation = nameRotation * PI$5 / 180; // To radian.
  40114. }
  40115. var axisNameAvailableWidth;
  40116. if (isNameLocationCenter(nameLocation)) {
  40117. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  40118. nameDirection);
  40119. } else {
  40120. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  40121. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  40122. if (axisNameAvailableWidth != null) {
  40123. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  40124. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  40125. }
  40126. }
  40127. var textFont = textStyleModel.getFont();
  40128. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  40129. var ellipsis = truncateOpt.ellipsis;
  40130. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  40131. var tooltipOpt = axisModel.get('tooltip', true);
  40132. var mainType = axisModel.mainType;
  40133. var formatterParams = {
  40134. componentType: mainType,
  40135. name: name,
  40136. $vars: ['name']
  40137. };
  40138. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  40139. var textEl = new ZRText({
  40140. x: pos[0],
  40141. y: pos[1],
  40142. rotation: labelLayout.rotation,
  40143. silent: AxisBuilder.isLabelSilent(axisModel),
  40144. style: createTextStyle(textStyleModel, {
  40145. text: name,
  40146. font: textFont,
  40147. overflow: 'truncate',
  40148. width: maxWidth,
  40149. ellipsis: ellipsis,
  40150. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  40151. align: textStyleModel.get('align') || labelLayout.textAlign,
  40152. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  40153. }),
  40154. z2: 1
  40155. });
  40156. textEl.tooltip = tooltipOpt && tooltipOpt.show ? extend({
  40157. content: name,
  40158. formatter: function () {
  40159. return name;
  40160. },
  40161. formatterParams: formatterParams
  40162. }, tooltipOpt) : null;
  40163. textEl.__fullText = name; // Id for animation
  40164. textEl.anid = 'name';
  40165. if (axisModel.get('triggerEvent')) {
  40166. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  40167. eventData.targetType = 'axisName';
  40168. eventData.name = name;
  40169. getECData(textEl).eventData = eventData;
  40170. } // FIXME
  40171. transformGroup.add(textEl);
  40172. textEl.updateTransform();
  40173. group.add(textEl);
  40174. textEl.decomposeTransform();
  40175. }
  40176. };
  40177. function endTextLayout(rotation, textPosition, textRotate, extent) {
  40178. var rotationDiff = remRadian(textRotate - rotation);
  40179. var textAlign;
  40180. var textVerticalAlign;
  40181. var inverse = extent[0] > extent[1];
  40182. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  40183. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  40184. textVerticalAlign = onLeft ? 'bottom' : 'top';
  40185. textAlign = 'center';
  40186. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  40187. textVerticalAlign = onLeft ? 'top' : 'bottom';
  40188. textAlign = 'center';
  40189. } else {
  40190. textVerticalAlign = 'middle';
  40191. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  40192. textAlign = onLeft ? 'left' : 'right';
  40193. } else {
  40194. textAlign = onLeft ? 'right' : 'left';
  40195. }
  40196. }
  40197. return {
  40198. rotation: rotationDiff,
  40199. textAlign: textAlign,
  40200. textVerticalAlign: textVerticalAlign
  40201. };
  40202. }
  40203. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  40204. if (shouldShowAllLabels(axisModel.axis)) {
  40205. return;
  40206. } // If min or max are user set, we need to check
  40207. // If the tick on min(max) are overlap on their neighbour tick
  40208. // If they are overlapped, we need to hide the min(max) tick label
  40209. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  40210. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  40211. // Have not consider onBand yet, where tick els is more than label els.
  40212. labelEls = labelEls || [];
  40213. tickEls = tickEls || [];
  40214. var firstLabel = labelEls[0];
  40215. var nextLabel = labelEls[1];
  40216. var lastLabel = labelEls[labelEls.length - 1];
  40217. var prevLabel = labelEls[labelEls.length - 2];
  40218. var firstTick = tickEls[0];
  40219. var nextTick = tickEls[1];
  40220. var lastTick = tickEls[tickEls.length - 1];
  40221. var prevTick = tickEls[tickEls.length - 2];
  40222. if (showMinLabel === false) {
  40223. ignoreEl(firstLabel);
  40224. ignoreEl(firstTick);
  40225. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  40226. if (showMinLabel) {
  40227. ignoreEl(nextLabel);
  40228. ignoreEl(nextTick);
  40229. } else {
  40230. ignoreEl(firstLabel);
  40231. ignoreEl(firstTick);
  40232. }
  40233. }
  40234. if (showMaxLabel === false) {
  40235. ignoreEl(lastLabel);
  40236. ignoreEl(lastTick);
  40237. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  40238. if (showMaxLabel) {
  40239. ignoreEl(prevLabel);
  40240. ignoreEl(prevTick);
  40241. } else {
  40242. ignoreEl(lastLabel);
  40243. ignoreEl(lastTick);
  40244. }
  40245. }
  40246. }
  40247. function ignoreEl(el) {
  40248. el && (el.ignore = true);
  40249. }
  40250. function isTwoLabelOverlapped(current, next) {
  40251. // current and next has the same rotation.
  40252. var firstRect = current && current.getBoundingRect().clone();
  40253. var nextRect = next && next.getBoundingRect().clone();
  40254. if (!firstRect || !nextRect) {
  40255. return;
  40256. } // When checking intersect of two rotated labels, we use mRotationBack
  40257. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  40258. var mRotationBack = identity([]);
  40259. rotate(mRotationBack, mRotationBack, -current.rotation);
  40260. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  40261. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  40262. return firstRect.intersect(nextRect);
  40263. }
  40264. function isNameLocationCenter(nameLocation) {
  40265. return nameLocation === 'middle' || nameLocation === 'center';
  40266. }
  40267. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  40268. var tickEls = [];
  40269. var pt1 = [];
  40270. var pt2 = [];
  40271. for (var i = 0; i < ticksCoords.length; i++) {
  40272. var tickCoord = ticksCoords[i].coord;
  40273. pt1[0] = tickCoord;
  40274. pt1[1] = 0;
  40275. pt2[0] = tickCoord;
  40276. pt2[1] = tickEndCoord;
  40277. if (tickTransform) {
  40278. applyTransform(pt1, pt1, tickTransform);
  40279. applyTransform(pt2, pt2, tickTransform);
  40280. } // Tick line, Not use group transform to have better line draw
  40281. var tickEl = new Line({
  40282. subPixelOptimize: true,
  40283. shape: {
  40284. x1: pt1[0],
  40285. y1: pt1[1],
  40286. x2: pt2[0],
  40287. y2: pt2[1]
  40288. },
  40289. style: tickLineStyle,
  40290. z2: 2,
  40291. autoBatch: true,
  40292. silent: true
  40293. });
  40294. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  40295. tickEls.push(tickEl);
  40296. }
  40297. return tickEls;
  40298. }
  40299. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  40300. var axis = axisModel.axis;
  40301. var tickModel = axisModel.getModel('axisTick');
  40302. var shown = tickModel.get('show');
  40303. if (shown === 'auto' && opt.handleAutoShown) {
  40304. shown = opt.handleAutoShown('axisTick');
  40305. }
  40306. if (!shown || axis.scale.isBlank()) {
  40307. return;
  40308. }
  40309. var lineStyleModel = tickModel.getModel('lineStyle');
  40310. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  40311. var ticksCoords = axis.getTicksCoords();
  40312. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  40313. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  40314. }), 'ticks');
  40315. for (var i = 0; i < ticksEls.length; i++) {
  40316. group.add(ticksEls[i]);
  40317. }
  40318. return ticksEls;
  40319. }
  40320. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  40321. var axis = axisModel.axis;
  40322. var minorTickModel = axisModel.getModel('minorTick');
  40323. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  40324. return;
  40325. }
  40326. var minorTicksCoords = axis.getMinorTicksCoords();
  40327. if (!minorTicksCoords.length) {
  40328. return;
  40329. }
  40330. var lineStyleModel = minorTickModel.getModel('lineStyle');
  40331. var tickEndCoord = tickDirection * minorTickModel.get('length');
  40332. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  40333. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  40334. }));
  40335. for (var i = 0; i < minorTicksCoords.length; i++) {
  40336. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  40337. for (var k = 0; k < minorTicksEls.length; k++) {
  40338. group.add(minorTicksEls[k]);
  40339. }
  40340. }
  40341. }
  40342. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  40343. var axis = axisModel.axis;
  40344. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  40345. if (!show || axis.scale.isBlank()) {
  40346. return;
  40347. }
  40348. var labelModel = axisModel.getModel('axisLabel');
  40349. var labelMargin = labelModel.get('margin');
  40350. var labels = axis.getViewLabels(); // Special label rotate.
  40351. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  40352. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  40353. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  40354. var labelEls = [];
  40355. var silent = AxisBuilder.isLabelSilent(axisModel);
  40356. var triggerEvent = axisModel.get('triggerEvent');
  40357. each(labels, function (labelItem, index) {
  40358. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  40359. var formattedLabel = labelItem.formattedLabel;
  40360. var rawLabel = labelItem.rawLabel;
  40361. var itemLabelModel = labelModel;
  40362. if (rawCategoryData && rawCategoryData[tickValue]) {
  40363. var rawCategoryItem = rawCategoryData[tickValue];
  40364. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  40365. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  40366. }
  40367. }
  40368. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  40369. var tickCoord = axis.dataToCoord(tickValue);
  40370. var textEl = new ZRText({
  40371. x: tickCoord,
  40372. y: opt.labelOffset + opt.labelDirection * labelMargin,
  40373. rotation: labelLayout.rotation,
  40374. silent: silent,
  40375. z2: 10,
  40376. style: createTextStyle(itemLabelModel, {
  40377. text: formattedLabel,
  40378. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  40379. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  40380. fill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original
  40381. // index of axis.data. So tick should not be exposed to user
  40382. // in category axis.
  40383. // (2) Compatible with previous version, which always use formatted label as
  40384. // input. But in interval scale the formatted label is like '223,445', which
  40385. // maked user repalce ','. So we modify it to return original val but remain
  40386. // it as 'string' to avoid error in replacing.
  40387. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  40388. })
  40389. });
  40390. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  40391. if (triggerEvent) {
  40392. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  40393. eventData.targetType = 'axisLabel';
  40394. eventData.value = rawLabel;
  40395. getECData(textEl).eventData = eventData;
  40396. } // FIXME
  40397. transformGroup.add(textEl);
  40398. textEl.updateTransform();
  40399. labelEls.push(textEl);
  40400. group.add(textEl);
  40401. textEl.decomposeTransform();
  40402. });
  40403. return labelEls;
  40404. }
  40405. // allAxesInfo should be updated when setOption performed.
  40406. function collect(ecModel, api) {
  40407. var result = {
  40408. /**
  40409. * key: makeKey(axis.model)
  40410. * value: {
  40411. * axis,
  40412. * coordSys,
  40413. * axisPointerModel,
  40414. * triggerTooltip,
  40415. * involveSeries,
  40416. * snap,
  40417. * seriesModels,
  40418. * seriesDataCount
  40419. * }
  40420. */
  40421. axesInfo: {},
  40422. seriesInvolved: false,
  40423. /**
  40424. * key: makeKey(coordSys.model)
  40425. * value: Object: key makeKey(axis.model), value: axisInfo
  40426. */
  40427. coordSysAxesInfo: {},
  40428. coordSysMap: {}
  40429. };
  40430. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  40431. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  40432. return result;
  40433. }
  40434. function collectAxesInfo(result, ecModel, api) {
  40435. var globalTooltipModel = ecModel.getComponent('tooltip');
  40436. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  40437. var linksOption = globalAxisPointerModel.get('link', true) || [];
  40438. var linkGroups = []; // Collect axes info.
  40439. each(api.getCoordinateSystems(), function (coordSys) {
  40440. // Some coordinate system do not support axes, like geo.
  40441. if (!coordSys.axisPointerEnabled) {
  40442. return;
  40443. }
  40444. var coordSysKey = makeKey(coordSys.model);
  40445. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  40446. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convienent way to show axisPointer
  40447. // for user. So we enable seting tooltip on coordSys model.
  40448. var coordSysModel = coordSys.model;
  40449. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  40450. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  40451. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  40452. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  40453. // show but axisPointer will show as normal.
  40454. && baseTooltipModel.get('show')) {
  40455. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  40456. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  40457. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  40458. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  40459. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  40460. if (triggerAxis || cross) {
  40461. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  40462. }
  40463. if (cross) {
  40464. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  40465. }
  40466. } // fromTooltip: true | false | 'cross'
  40467. // triggerTooltip: true | false | null
  40468. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  40469. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  40470. var axisPointerShow = axisPointerModel.get('show');
  40471. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  40472. return;
  40473. }
  40474. if (triggerTooltip == null) {
  40475. triggerTooltip = axisPointerModel.get('triggerTooltip');
  40476. }
  40477. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  40478. var snap = axisPointerModel.get('snap');
  40479. var axisKey = makeKey(axis.model);
  40480. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  40481. var axisInfo = result.axesInfo[axisKey] = {
  40482. key: axisKey,
  40483. axis: axis,
  40484. coordSys: coordSys,
  40485. axisPointerModel: axisPointerModel,
  40486. triggerTooltip: triggerTooltip,
  40487. involveSeries: involveSeries,
  40488. snap: snap,
  40489. useHandle: isHandleTrigger(axisPointerModel),
  40490. seriesModels: [],
  40491. linkGroup: null
  40492. };
  40493. axesInfoInCoordSys[axisKey] = axisInfo;
  40494. result.seriesInvolved = result.seriesInvolved || involveSeries;
  40495. var groupIndex = getLinkGroupIndex(linksOption, axis);
  40496. if (groupIndex != null) {
  40497. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  40498. axesInfo: {}
  40499. });
  40500. linkGroup.axesInfo[axisKey] = axisInfo;
  40501. linkGroup.mapper = linksOption[groupIndex].mapper;
  40502. axisInfo.linkGroup = linkGroup;
  40503. }
  40504. }
  40505. });
  40506. }
  40507. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  40508. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  40509. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  40510. var volatileOption = {};
  40511. each(fields, function (field) {
  40512. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  40513. }); // category axis do not auto snap, otherwise some tick that do not
  40514. // has value can not be hovered. value/time/log axis default snap if
  40515. // triggered from tooltip and trigger tooltip.
  40516. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatibel with previous behavior, tooltip axis do not show label by default.
  40517. // Only these properties can be overrided from tooltip to axisPointer.
  40518. if (tooltipAxisPointerModel.get('type') === 'cross') {
  40519. volatileOption.type = 'line';
  40520. }
  40521. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  40522. labelOption.show == null && (labelOption.show = false);
  40523. if (fromTooltip === 'cross') {
  40524. // When 'cross', both axes show labels.
  40525. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  40526. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  40527. // (cross style is dashed by default)
  40528. if (!triggerTooltip) {
  40529. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  40530. crossStyle && defaults(labelOption, crossStyle.textStyle);
  40531. }
  40532. }
  40533. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  40534. }
  40535. function collectSeriesInfo(result, ecModel) {
  40536. // Prepare data for axis trigger
  40537. ecModel.eachSeries(function (seriesModel) {
  40538. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  40539. var coordSys = seriesModel.coordinateSystem;
  40540. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  40541. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  40542. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  40543. return;
  40544. }
  40545. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  40546. var axis = axisInfo.axis;
  40547. if (coordSys.getAxis(axis.dim) === axis) {
  40548. axisInfo.seriesModels.push(seriesModel);
  40549. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  40550. axisInfo.seriesDataCount += seriesModel.getData().count();
  40551. }
  40552. });
  40553. });
  40554. }
  40555. /**
  40556. * For example:
  40557. * {
  40558. * axisPointer: {
  40559. * links: [{
  40560. * xAxisIndex: [2, 4],
  40561. * yAxisIndex: 'all'
  40562. * }, {
  40563. * xAxisId: ['a5', 'a7'],
  40564. * xAxisName: 'xxx'
  40565. * }]
  40566. * }
  40567. * }
  40568. */
  40569. function getLinkGroupIndex(linksOption, axis) {
  40570. var axisModel = axis.model;
  40571. var dim = axis.dim;
  40572. for (var i = 0; i < linksOption.length; i++) {
  40573. var linkOption = linksOption[i] || {};
  40574. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  40575. return i;
  40576. }
  40577. }
  40578. }
  40579. function checkPropInLink(linkPropValue, axisPropValue) {
  40580. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  40581. }
  40582. function fixValue(axisModel) {
  40583. var axisInfo = getAxisInfo(axisModel);
  40584. if (!axisInfo) {
  40585. return;
  40586. }
  40587. var axisPointerModel = axisInfo.axisPointerModel;
  40588. var scale = axisInfo.axis.scale;
  40589. var option = axisPointerModel.option;
  40590. var status = axisPointerModel.get('status');
  40591. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  40592. if (value != null) {
  40593. value = scale.parse(value);
  40594. }
  40595. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  40596. // and status should be initialized.
  40597. if (status == null) {
  40598. option.status = useHandle ? 'show' : 'hide';
  40599. }
  40600. var extent = scale.getExtent().slice();
  40601. extent[0] > extent[1] && extent.reverse();
  40602. if ( // Pick a value on axis when initializing.
  40603. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  40604. // where we should re-pick a value to keep `handle` displaying normally.
  40605. || value > extent[1]) {
  40606. // Make handle displayed on the end of the axis when init, which looks better.
  40607. value = extent[1];
  40608. }
  40609. if (value < extent[0]) {
  40610. value = extent[0];
  40611. }
  40612. option.value = value;
  40613. if (useHandle) {
  40614. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  40615. }
  40616. }
  40617. function getAxisInfo(axisModel) {
  40618. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  40619. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  40620. }
  40621. function getAxisPointerModel(axisModel) {
  40622. var axisInfo = getAxisInfo(axisModel);
  40623. return axisInfo && axisInfo.axisPointerModel;
  40624. }
  40625. function isHandleTrigger(axisPointerModel) {
  40626. return !!axisPointerModel.get(['handle', 'show']);
  40627. }
  40628. /**
  40629. * @param {module:echarts/model/Model} model
  40630. * @return {string} unique key
  40631. */
  40632. function makeKey(model) {
  40633. return model.type + '||' + model.id;
  40634. }
  40635. var axisPointerClazz = {};
  40636. /**
  40637. * Base class of AxisView.
  40638. */
  40639. var AxisView =
  40640. /** @class */
  40641. function (_super) {
  40642. __extends(AxisView, _super);
  40643. function AxisView() {
  40644. var _this = _super !== null && _super.apply(this, arguments) || this;
  40645. _this.type = AxisView.type;
  40646. return _this;
  40647. }
  40648. /**
  40649. * @override
  40650. */
  40651. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  40652. // FIXME
  40653. // This process should proformed after coordinate systems updated
  40654. // (axis scale updated), and should be performed each time update.
  40655. // So put it here temporarily, although it is not appropriate to
  40656. // put a model-writing procedure in `view`.
  40657. this.axisPointerClass && fixValue(axisModel);
  40658. _super.prototype.render.apply(this, arguments);
  40659. this._doUpdateAxisPointerClass(axisModel, api, true);
  40660. };
  40661. /**
  40662. * Action handler.
  40663. */
  40664. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  40665. this._doUpdateAxisPointerClass(axisModel, api, false);
  40666. };
  40667. /**
  40668. * @override
  40669. */
  40670. AxisView.prototype.remove = function (ecModel, api) {
  40671. var axisPointer = this._axisPointer;
  40672. axisPointer && axisPointer.remove(api);
  40673. };
  40674. /**
  40675. * @override
  40676. */
  40677. AxisView.prototype.dispose = function (ecModel, api) {
  40678. this._disposeAxisPointer(api);
  40679. _super.prototype.dispose.apply(this, arguments);
  40680. };
  40681. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  40682. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  40683. if (!Clazz) {
  40684. return;
  40685. }
  40686. var axisPointerModel = getAxisPointerModel(axisModel);
  40687. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  40688. };
  40689. AxisView.prototype._disposeAxisPointer = function (api) {
  40690. this._axisPointer && this._axisPointer.dispose(api);
  40691. this._axisPointer = null;
  40692. };
  40693. AxisView.registerAxisPointerClass = function (type, clazz) {
  40694. if ("development" !== 'production') {
  40695. if (axisPointerClazz[type]) {
  40696. throw new Error('axisPointer ' + type + ' exists');
  40697. }
  40698. }
  40699. axisPointerClazz[type] = clazz;
  40700. };
  40701. AxisView.getAxisPointerClass = function (type) {
  40702. return type && axisPointerClazz[type];
  40703. };
  40704. AxisView.type = 'axis';
  40705. return AxisView;
  40706. }(ComponentView);
  40707. var inner$5 = makeInner();
  40708. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  40709. var axis = axisModel.axis;
  40710. if (axis.scale.isBlank()) {
  40711. return;
  40712. } // TODO: TYPE
  40713. var splitAreaModel = axisModel.getModel('splitArea');
  40714. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  40715. var areaColors = areaStyleModel.get('color');
  40716. var gridRect = gridModel.coordinateSystem.getRect();
  40717. var ticksCoords = axis.getTicksCoords({
  40718. tickModel: splitAreaModel,
  40719. clamp: true
  40720. });
  40721. if (!ticksCoords.length) {
  40722. return;
  40723. } // For Making appropriate splitArea animation, the color and anid
  40724. // should be corresponding to previous one if possible.
  40725. var areaColorsLen = areaColors.length;
  40726. var lastSplitAreaColors = inner$5(axisView).splitAreaColors;
  40727. var newSplitAreaColors = createHashMap();
  40728. var colorIndex = 0;
  40729. if (lastSplitAreaColors) {
  40730. for (var i = 0; i < ticksCoords.length; i++) {
  40731. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  40732. if (cIndex != null) {
  40733. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  40734. break;
  40735. }
  40736. }
  40737. }
  40738. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  40739. var areaStyle = areaStyleModel.getAreaStyle();
  40740. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  40741. for (var i = 1; i < ticksCoords.length; i++) {
  40742. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  40743. var x = void 0;
  40744. var y = void 0;
  40745. var width = void 0;
  40746. var height = void 0;
  40747. if (axis.isHorizontal()) {
  40748. x = prev;
  40749. y = gridRect.y;
  40750. width = tickCoord - x;
  40751. height = gridRect.height;
  40752. prev = x + width;
  40753. } else {
  40754. x = gridRect.x;
  40755. y = prev;
  40756. width = gridRect.width;
  40757. height = tickCoord - y;
  40758. prev = y + height;
  40759. }
  40760. var tickValue = ticksCoords[i - 1].tickValue;
  40761. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  40762. axisGroup.add(new Rect({
  40763. anid: tickValue != null ? 'area_' + tickValue : null,
  40764. shape: {
  40765. x: x,
  40766. y: y,
  40767. width: width,
  40768. height: height
  40769. },
  40770. style: defaults({
  40771. fill: areaColors[colorIndex]
  40772. }, areaStyle),
  40773. autoBatch: true,
  40774. silent: true
  40775. }));
  40776. colorIndex = (colorIndex + 1) % areaColorsLen;
  40777. }
  40778. inner$5(axisView).splitAreaColors = newSplitAreaColors;
  40779. }
  40780. function rectCoordAxisHandleRemove(axisView) {
  40781. inner$5(axisView).splitAreaColors = null;
  40782. }
  40783. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  40784. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  40785. var CartesianAxisView =
  40786. /** @class */
  40787. function (_super) {
  40788. __extends(CartesianAxisView, _super);
  40789. function CartesianAxisView() {
  40790. var _this = _super !== null && _super.apply(this, arguments) || this;
  40791. _this.type = CartesianAxisView.type;
  40792. _this.axisPointerClass = 'CartesianAxisPointer';
  40793. return _this;
  40794. }
  40795. /**
  40796. * @override
  40797. */
  40798. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  40799. this.group.removeAll();
  40800. var oldAxisGroup = this._axisGroup;
  40801. this._axisGroup = new Group();
  40802. this.group.add(this._axisGroup);
  40803. if (!axisModel.get('show')) {
  40804. return;
  40805. }
  40806. var gridModel = axisModel.getCoordSysModel();
  40807. var layout = layout$1(gridModel, axisModel);
  40808. var axisBuilder = new AxisBuilder(axisModel, extend({
  40809. handleAutoShown: function (elementType) {
  40810. var cartesians = gridModel.coordinateSystem.getCartesians();
  40811. for (var i = 0; i < cartesians.length; i++) {
  40812. var otherAxisType = cartesians[i].getOtherAxis(axisModel.axis).type;
  40813. if (otherAxisType === 'value' || otherAxisType === 'log') {
  40814. // Still show axis tick or axisLine if other axis is value / log
  40815. return true;
  40816. }
  40817. } // Not show axisTick or axisLine if other axis is category / time
  40818. return false;
  40819. }
  40820. }, layout));
  40821. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  40822. this._axisGroup.add(axisBuilder.getGroup());
  40823. each(selfBuilderAttrs, function (name) {
  40824. if (axisModel.get([name, 'show'])) {
  40825. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  40826. }
  40827. }, this);
  40828. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  40829. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  40830. };
  40831. CartesianAxisView.prototype.remove = function () {
  40832. rectCoordAxisHandleRemove(this);
  40833. };
  40834. CartesianAxisView.type = 'cartesianAxis';
  40835. return CartesianAxisView;
  40836. }(AxisView);
  40837. var axisElementBuilders = {
  40838. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  40839. var axis = axisModel.axis;
  40840. if (axis.scale.isBlank()) {
  40841. return;
  40842. }
  40843. var splitLineModel = axisModel.getModel('splitLine');
  40844. var lineStyleModel = splitLineModel.getModel('lineStyle');
  40845. var lineColors = lineStyleModel.get('color');
  40846. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  40847. var gridRect = gridModel.coordinateSystem.getRect();
  40848. var isHorizontal = axis.isHorizontal();
  40849. var lineCount = 0;
  40850. var ticksCoords = axis.getTicksCoords({
  40851. tickModel: splitLineModel
  40852. });
  40853. var p1 = [];
  40854. var p2 = [];
  40855. var lineStyle = lineStyleModel.getLineStyle();
  40856. for (var i = 0; i < ticksCoords.length; i++) {
  40857. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  40858. if (isHorizontal) {
  40859. p1[0] = tickCoord;
  40860. p1[1] = gridRect.y;
  40861. p2[0] = tickCoord;
  40862. p2[1] = gridRect.y + gridRect.height;
  40863. } else {
  40864. p1[0] = gridRect.x;
  40865. p1[1] = tickCoord;
  40866. p2[0] = gridRect.x + gridRect.width;
  40867. p2[1] = tickCoord;
  40868. }
  40869. var colorIndex = lineCount++ % lineColors.length;
  40870. var tickValue = ticksCoords[i].tickValue;
  40871. axisGroup.add(new Line({
  40872. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  40873. subPixelOptimize: true,
  40874. autoBatch: true,
  40875. shape: {
  40876. x1: p1[0],
  40877. y1: p1[1],
  40878. x2: p2[0],
  40879. y2: p2[1]
  40880. },
  40881. style: defaults({
  40882. stroke: lineColors[colorIndex]
  40883. }, lineStyle),
  40884. silent: true
  40885. }));
  40886. }
  40887. },
  40888. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  40889. var axis = axisModel.axis;
  40890. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  40891. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  40892. var gridRect = gridModel.coordinateSystem.getRect();
  40893. var isHorizontal = axis.isHorizontal();
  40894. var minorTicksCoords = axis.getMinorTicksCoords();
  40895. if (!minorTicksCoords.length) {
  40896. return;
  40897. }
  40898. var p1 = [];
  40899. var p2 = [];
  40900. var lineStyle = lineStyleModel.getLineStyle();
  40901. for (var i = 0; i < minorTicksCoords.length; i++) {
  40902. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  40903. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  40904. if (isHorizontal) {
  40905. p1[0] = tickCoord;
  40906. p1[1] = gridRect.y;
  40907. p2[0] = tickCoord;
  40908. p2[1] = gridRect.y + gridRect.height;
  40909. } else {
  40910. p1[0] = gridRect.x;
  40911. p1[1] = tickCoord;
  40912. p2[0] = gridRect.x + gridRect.width;
  40913. p2[1] = tickCoord;
  40914. }
  40915. axisGroup.add(new Line({
  40916. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  40917. subPixelOptimize: true,
  40918. autoBatch: true,
  40919. shape: {
  40920. x1: p1[0],
  40921. y1: p1[1],
  40922. x2: p2[0],
  40923. y2: p2[1]
  40924. },
  40925. style: lineStyle,
  40926. silent: true
  40927. }));
  40928. }
  40929. }
  40930. },
  40931. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  40932. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  40933. }
  40934. };
  40935. var CartesianXAxisView =
  40936. /** @class */
  40937. function (_super) {
  40938. __extends(CartesianXAxisView, _super);
  40939. function CartesianXAxisView() {
  40940. var _this = _super !== null && _super.apply(this, arguments) || this;
  40941. _this.type = CartesianXAxisView.type;
  40942. return _this;
  40943. }
  40944. CartesianXAxisView.type = 'xAxis';
  40945. return CartesianXAxisView;
  40946. }(CartesianAxisView);
  40947. var CartesianYAxisView =
  40948. /** @class */
  40949. function (_super) {
  40950. __extends(CartesianYAxisView, _super);
  40951. function CartesianYAxisView() {
  40952. var _this = _super !== null && _super.apply(this, arguments) || this;
  40953. _this.type = CartesianXAxisView.type;
  40954. return _this;
  40955. }
  40956. CartesianYAxisView.type = 'yAxis';
  40957. return CartesianYAxisView;
  40958. }(CartesianAxisView);
  40959. var GridView =
  40960. /** @class */
  40961. function (_super) {
  40962. __extends(GridView, _super);
  40963. function GridView() {
  40964. var _this = _super !== null && _super.apply(this, arguments) || this;
  40965. _this.type = 'grid';
  40966. return _this;
  40967. }
  40968. GridView.prototype.render = function (gridModel, ecModel) {
  40969. this.group.removeAll();
  40970. if (gridModel.get('show')) {
  40971. this.group.add(new Rect({
  40972. shape: gridModel.coordinateSystem.getRect(),
  40973. style: defaults({
  40974. fill: gridModel.get('backgroundColor')
  40975. }, gridModel.getItemStyle()),
  40976. silent: true,
  40977. z2: -1
  40978. }));
  40979. }
  40980. };
  40981. GridView.type = 'grid';
  40982. return GridView;
  40983. }(ComponentView);
  40984. var extraOption = {
  40985. // gridIndex: 0,
  40986. // gridId: '',
  40987. offset: 0
  40988. };
  40989. function install$5(registers) {
  40990. registers.registerComponentView(GridView);
  40991. registers.registerComponentModel(GridModel);
  40992. registers.registerCoordinateSystem('cartesian2d', Grid);
  40993. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  40994. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  40995. registers.registerComponentView(CartesianXAxisView);
  40996. registers.registerComponentView(CartesianYAxisView);
  40997. registers.registerPreprocessor(function (option) {
  40998. // Only create grid when need
  40999. if (option.xAxis && option.yAxis && !option.grid) {
  41000. option.grid = {};
  41001. }
  41002. });
  41003. }
  41004. function install$6(registers) {
  41005. // In case developer forget to include grid component
  41006. use(install$5);
  41007. registers.registerSeriesModel(ScatterSeriesModel);
  41008. registers.registerChartView(ScatterView);
  41009. registers.registerLayout(pointsLayout('scatter'));
  41010. }
  41011. var inner$6 = makeInner();
  41012. var clone$3 = clone;
  41013. var bind$1 = bind;
  41014. /**
  41015. * Base axis pointer class in 2D.
  41016. */
  41017. var BaseAxisPointer =
  41018. /** @class */
  41019. function () {
  41020. function BaseAxisPointer() {
  41021. this._dragging = false;
  41022. /**
  41023. * In px, arbitrary value. Do not set too small,
  41024. * no animation is ok for most cases.
  41025. */
  41026. this.animationThreshold = 15;
  41027. }
  41028. /**
  41029. * @implement
  41030. */
  41031. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  41032. var value = axisPointerModel.get('value');
  41033. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  41034. // be replaced when user calling setOption in not merge mode.
  41035. this._axisModel = axisModel;
  41036. this._axisPointerModel = axisPointerModel;
  41037. this._api = api; // Optimize: `render` will be called repeatly during mouse move.
  41038. // So it is power consuming if performing `render` each time,
  41039. // especially on mobile device.
  41040. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  41041. return;
  41042. }
  41043. this._lastValue = value;
  41044. this._lastStatus = status;
  41045. var group = this._group;
  41046. var handle = this._handle;
  41047. if (!status || status === 'hide') {
  41048. // Do not clear here, for animation better.
  41049. group && group.hide();
  41050. handle && handle.hide();
  41051. return;
  41052. }
  41053. group && group.show();
  41054. handle && handle.show(); // Otherwise status is 'show'
  41055. var elOption = {};
  41056. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  41057. var graphicKey = elOption.graphicKey;
  41058. if (graphicKey !== this._lastGraphicKey) {
  41059. this.clear(api);
  41060. }
  41061. this._lastGraphicKey = graphicKey;
  41062. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  41063. if (!group) {
  41064. group = this._group = new Group();
  41065. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  41066. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  41067. api.getZr().add(group);
  41068. } else {
  41069. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  41070. this.updatePointerEl(group, elOption, doUpdateProps);
  41071. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  41072. }
  41073. updateMandatoryProps(group, axisPointerModel, true);
  41074. this._renderHandle(value);
  41075. };
  41076. /**
  41077. * @implement
  41078. */
  41079. BaseAxisPointer.prototype.remove = function (api) {
  41080. this.clear(api);
  41081. };
  41082. /**
  41083. * @implement
  41084. */
  41085. BaseAxisPointer.prototype.dispose = function (api) {
  41086. this.clear(api);
  41087. };
  41088. /**
  41089. * @protected
  41090. */
  41091. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  41092. var animation = axisPointerModel.get('animation');
  41093. var axis = axisModel.axis;
  41094. var isCategoryAxis = axis.type === 'category';
  41095. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  41096. if (!useSnap && !isCategoryAxis) {
  41097. return false;
  41098. }
  41099. if (animation === 'auto' || animation == null) {
  41100. var animationThreshold = this.animationThreshold;
  41101. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  41102. return true;
  41103. } // It is important to auto animation when snap used. Consider if there is
  41104. // a dataZoom, animation will be disabled when too many points exist, while
  41105. // it will be enabled for better visual effect when little points exist.
  41106. if (useSnap) {
  41107. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  41108. var axisExtent = axis.getExtent(); // Approximate band width
  41109. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  41110. }
  41111. return false;
  41112. }
  41113. return animation === true;
  41114. };
  41115. /**
  41116. * add {pointer, label, graphicKey} to elOption
  41117. * @protected
  41118. */
  41119. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Shoule be implemenented by sub-class.
  41120. };
  41121. /**
  41122. * @protected
  41123. */
  41124. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  41125. var pointerOption = elOption.pointer;
  41126. if (pointerOption) {
  41127. var pointerEl = inner$6(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  41128. group.add(pointerEl);
  41129. }
  41130. };
  41131. /**
  41132. * @protected
  41133. */
  41134. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  41135. if (elOption.label) {
  41136. var labelEl = inner$6(group).labelEl = new ZRText(clone$3(elOption.label));
  41137. group.add(labelEl);
  41138. updateLabelShowHide(labelEl, axisPointerModel);
  41139. }
  41140. };
  41141. /**
  41142. * @protected
  41143. */
  41144. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  41145. var pointerEl = inner$6(group).pointerEl;
  41146. if (pointerEl && elOption.pointer) {
  41147. pointerEl.setStyle(elOption.pointer.style);
  41148. updateProps(pointerEl, {
  41149. shape: elOption.pointer.shape
  41150. });
  41151. }
  41152. };
  41153. /**
  41154. * @protected
  41155. */
  41156. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  41157. var labelEl = inner$6(group).labelEl;
  41158. if (labelEl) {
  41159. labelEl.setStyle(elOption.label.style);
  41160. updateProps(labelEl, {
  41161. // Consider text length change in vertical axis, animation should
  41162. // be used on shape, otherwise the effect will be weird.
  41163. // TODOTODO
  41164. // shape: elOption.label.shape,
  41165. x: elOption.label.x,
  41166. y: elOption.label.y
  41167. });
  41168. updateLabelShowHide(labelEl, axisPointerModel);
  41169. }
  41170. };
  41171. /**
  41172. * @private
  41173. */
  41174. BaseAxisPointer.prototype._renderHandle = function (value) {
  41175. if (this._dragging || !this.updateHandleTransform) {
  41176. return;
  41177. }
  41178. var axisPointerModel = this._axisPointerModel;
  41179. var zr = this._api.getZr();
  41180. var handle = this._handle;
  41181. var handleModel = axisPointerModel.getModel('handle');
  41182. var status = axisPointerModel.get('status');
  41183. if (!handleModel.get('show') || !status || status === 'hide') {
  41184. handle && zr.remove(handle);
  41185. this._handle = null;
  41186. return;
  41187. }
  41188. var isInit;
  41189. if (!this._handle) {
  41190. isInit = true;
  41191. handle = this._handle = createIcon(handleModel.get('icon'), {
  41192. cursor: 'move',
  41193. draggable: true,
  41194. onmousemove: function (e) {
  41195. // Fot mobile devicem, prevent screen slider on the button.
  41196. stop(e.event);
  41197. },
  41198. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  41199. drift: bind$1(this._onHandleDragMove, this),
  41200. ondragend: bind$1(this._onHandleDragEnd, this)
  41201. });
  41202. zr.add(handle);
  41203. }
  41204. updateMandatoryProps(handle, axisPointerModel, false); // update style
  41205. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  41206. var handleSize = handleModel.get('size');
  41207. if (!isArray(handleSize)) {
  41208. handleSize = [handleSize, handleSize];
  41209. }
  41210. handle.scaleX = handleSize[0] / 2;
  41211. handle.scaleY = handleSize[1] / 2;
  41212. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  41213. this._moveHandleToValue(value, isInit);
  41214. };
  41215. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  41216. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  41217. };
  41218. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  41219. var handle = this._handle;
  41220. if (!handle) {
  41221. return;
  41222. }
  41223. this._dragging = true; // Persistent for throttle.
  41224. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  41225. this._payloadInfo = trans;
  41226. handle.stopAnimation();
  41227. handle.attr(getHandleTransProps(trans));
  41228. inner$6(handle).lastProp = null;
  41229. this._doDispatchAxisPointer();
  41230. };
  41231. /**
  41232. * Throttled method.
  41233. */
  41234. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  41235. var handle = this._handle;
  41236. if (!handle) {
  41237. return;
  41238. }
  41239. var payloadInfo = this._payloadInfo;
  41240. var axisModel = this._axisModel;
  41241. this._api.dispatchAction({
  41242. type: 'updateAxisPointer',
  41243. x: payloadInfo.cursorPoint[0],
  41244. y: payloadInfo.cursorPoint[1],
  41245. tooltipOption: payloadInfo.tooltipOption,
  41246. axesInfo: [{
  41247. axisDim: axisModel.axis.dim,
  41248. axisIndex: axisModel.componentIndex
  41249. }]
  41250. });
  41251. };
  41252. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  41253. this._dragging = false;
  41254. var handle = this._handle;
  41255. if (!handle) {
  41256. return;
  41257. }
  41258. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  41259. // axisPointer. So move handle to align the exact value position when
  41260. // drag ended.
  41261. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  41262. // button, and will be hidden after finger left handle button.
  41263. this._api.dispatchAction({
  41264. type: 'hideTip'
  41265. });
  41266. };
  41267. /**
  41268. * @private
  41269. */
  41270. BaseAxisPointer.prototype.clear = function (api) {
  41271. this._lastValue = null;
  41272. this._lastStatus = null;
  41273. var zr = api.getZr();
  41274. var group = this._group;
  41275. var handle = this._handle;
  41276. if (zr && group) {
  41277. this._lastGraphicKey = null;
  41278. group && zr.remove(group);
  41279. handle && zr.remove(handle);
  41280. this._group = null;
  41281. this._handle = null;
  41282. this._payloadInfo = null;
  41283. }
  41284. };
  41285. /**
  41286. * @protected
  41287. */
  41288. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  41289. };
  41290. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  41291. xDimIndex = xDimIndex || 0;
  41292. return {
  41293. x: xy[xDimIndex],
  41294. y: xy[1 - xDimIndex],
  41295. width: wh[xDimIndex],
  41296. height: wh[1 - xDimIndex]
  41297. };
  41298. };
  41299. return BaseAxisPointer;
  41300. }();
  41301. function updateProps$1(animationModel, moveAnimation, el, props) {
  41302. // Animation optimize.
  41303. if (!propsEqual(inner$6(el).lastProp, props)) {
  41304. inner$6(el).lastProp = props;
  41305. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  41306. }
  41307. }
  41308. function propsEqual(lastProps, newProps) {
  41309. if (isObject(lastProps) && isObject(newProps)) {
  41310. var equals_1 = true;
  41311. each(newProps, function (item, key) {
  41312. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  41313. });
  41314. return !!equals_1;
  41315. } else {
  41316. return lastProps === newProps;
  41317. }
  41318. }
  41319. function updateLabelShowHide(labelEl, axisPointerModel) {
  41320. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  41321. }
  41322. function getHandleTransProps(trans) {
  41323. return {
  41324. x: trans.x || 0,
  41325. y: trans.y || 0,
  41326. rotation: trans.rotation || 0
  41327. };
  41328. }
  41329. function updateMandatoryProps(group, axisPointerModel, silent) {
  41330. var z = axisPointerModel.get('z');
  41331. var zlevel = axisPointerModel.get('zlevel');
  41332. group && group.traverse(function (el) {
  41333. if (el.type !== 'group') {
  41334. z != null && (el.z = z);
  41335. zlevel != null && (el.zlevel = zlevel);
  41336. el.silent = silent;
  41337. }
  41338. });
  41339. }
  41340. function buildElStyle(axisPointerModel) {
  41341. var axisPointerType = axisPointerModel.get('type');
  41342. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  41343. var style;
  41344. if (axisPointerType === 'line') {
  41345. style = styleModel.getLineStyle();
  41346. style.fill = null;
  41347. } else if (axisPointerType === 'shadow') {
  41348. style = styleModel.getAreaStyle();
  41349. style.stroke = null;
  41350. }
  41351. return style;
  41352. }
  41353. /**
  41354. * @param {Function} labelPos {align, verticalAlign, position}
  41355. */
  41356. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  41357. var value = axisPointerModel.get('value');
  41358. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  41359. precision: axisPointerModel.get(['label', 'precision']),
  41360. formatter: axisPointerModel.get(['label', 'formatter'])
  41361. });
  41362. var labelModel = axisPointerModel.getModel('label');
  41363. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  41364. var font = labelModel.getFont();
  41365. var textRect = getBoundingRect(text, font);
  41366. var position = labelPos.position;
  41367. var width = textRect.width + paddings[1] + paddings[3];
  41368. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  41369. var align = labelPos.align;
  41370. align === 'right' && (position[0] -= width);
  41371. align === 'center' && (position[0] -= width / 2);
  41372. var verticalAlign = labelPos.verticalAlign;
  41373. verticalAlign === 'bottom' && (position[1] -= height);
  41374. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  41375. confineInContainer(position, width, height, api);
  41376. var bgColor = labelModel.get('backgroundColor');
  41377. if (!bgColor || bgColor === 'auto') {
  41378. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  41379. }
  41380. elOption.label = {
  41381. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  41382. x: position[0],
  41383. y: position[1],
  41384. style: createTextStyle(labelModel, {
  41385. text: text,
  41386. font: font,
  41387. fill: labelModel.getTextColor(),
  41388. padding: paddings,
  41389. backgroundColor: bgColor
  41390. }),
  41391. // Lable should be over axisPointer.
  41392. z2: 10
  41393. };
  41394. } // Do not overflow ec container
  41395. function confineInContainer(position, width, height, api) {
  41396. var viewWidth = api.getWidth();
  41397. var viewHeight = api.getHeight();
  41398. position[0] = Math.min(position[0] + width, viewWidth) - width;
  41399. position[1] = Math.min(position[1] + height, viewHeight) - height;
  41400. position[0] = Math.max(position[0], 0);
  41401. position[1] = Math.max(position[1], 0);
  41402. }
  41403. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  41404. value = axis.scale.parse(value);
  41405. var text = axis.scale.getLabel({
  41406. value: value
  41407. }, {
  41408. // If `precision` is set, width can be fixed (like '12.00500'), which
  41409. // helps to debounce when when moving label.
  41410. precision: opt.precision
  41411. });
  41412. var formatter = opt.formatter;
  41413. if (formatter) {
  41414. var params_1 = {
  41415. value: getAxisRawValue(axis, {
  41416. value: value
  41417. }),
  41418. axisDimension: axis.dim,
  41419. axisIndex: axis.index,
  41420. seriesData: []
  41421. };
  41422. each(seriesDataIndices, function (idxItem) {
  41423. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  41424. var dataIndex = idxItem.dataIndexInside;
  41425. var dataParams = series && series.getDataParams(dataIndex);
  41426. dataParams && params_1.seriesData.push(dataParams);
  41427. });
  41428. if (isString(formatter)) {
  41429. text = formatter.replace('{value}', text);
  41430. } else if (isFunction(formatter)) {
  41431. text = formatter(params_1);
  41432. }
  41433. }
  41434. return text;
  41435. }
  41436. function getTransformedPosition(axis, value, layoutInfo) {
  41437. var transform = create$1();
  41438. rotate(transform, transform, layoutInfo.rotation);
  41439. translate(transform, transform, layoutInfo.position);
  41440. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  41441. }
  41442. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  41443. // @ts-ignore
  41444. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  41445. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  41446. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  41447. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  41448. align: textLayout.textAlign,
  41449. verticalAlign: textLayout.textVerticalAlign
  41450. });
  41451. }
  41452. function makeLineShape(p1, p2, xDimIndex) {
  41453. xDimIndex = xDimIndex || 0;
  41454. return {
  41455. x1: p1[xDimIndex],
  41456. y1: p1[1 - xDimIndex],
  41457. x2: p2[xDimIndex],
  41458. y2: p2[1 - xDimIndex]
  41459. };
  41460. }
  41461. function makeRectShape(xy, wh, xDimIndex) {
  41462. xDimIndex = xDimIndex || 0;
  41463. return {
  41464. x: xy[xDimIndex],
  41465. y: xy[1 - xDimIndex],
  41466. width: wh[xDimIndex],
  41467. height: wh[1 - xDimIndex]
  41468. };
  41469. }
  41470. var CartesianAxisPointer =
  41471. /** @class */
  41472. function (_super) {
  41473. __extends(CartesianAxisPointer, _super);
  41474. function CartesianAxisPointer() {
  41475. return _super !== null && _super.apply(this, arguments) || this;
  41476. }
  41477. /**
  41478. * @override
  41479. */
  41480. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  41481. var axis = axisModel.axis;
  41482. var grid = axis.grid;
  41483. var axisPointerType = axisPointerModel.get('type');
  41484. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  41485. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  41486. if (axisPointerType && axisPointerType !== 'none') {
  41487. var elStyle = buildElStyle(axisPointerModel);
  41488. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  41489. pointerOption.style = elStyle;
  41490. elOption.graphicKey = pointerOption.type;
  41491. elOption.pointer = pointerOption;
  41492. }
  41493. var layoutInfo = layout$1(grid.model, axisModel);
  41494. buildCartesianSingleLabelElOption( // @ts-ignore
  41495. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  41496. };
  41497. /**
  41498. * @override
  41499. */
  41500. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  41501. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  41502. labelInside: false
  41503. }); // @ts-ignore
  41504. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  41505. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  41506. return {
  41507. x: pos[0],
  41508. y: pos[1],
  41509. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  41510. };
  41511. };
  41512. /**
  41513. * @override
  41514. */
  41515. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  41516. var axis = axisModel.axis;
  41517. var grid = axis.grid;
  41518. var axisExtent = axis.getGlobalExtent(true);
  41519. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  41520. var dimIndex = axis.dim === 'x' ? 0 : 1;
  41521. var currPosition = [transform.x, transform.y];
  41522. currPosition[dimIndex] += delta[dimIndex];
  41523. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  41524. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  41525. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  41526. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  41527. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  41528. var tooltipOptions = [{
  41529. verticalAlign: 'middle'
  41530. }, {
  41531. align: 'center'
  41532. }];
  41533. return {
  41534. x: currPosition[0],
  41535. y: currPosition[1],
  41536. rotation: transform.rotation,
  41537. cursorPoint: cursorPoint,
  41538. tooltipOption: tooltipOptions[dimIndex]
  41539. };
  41540. };
  41541. return CartesianAxisPointer;
  41542. }(BaseAxisPointer);
  41543. function getCartesian(grid, axis) {
  41544. var opt = {};
  41545. opt[axis.dim + 'AxisIndex'] = axis.index;
  41546. return grid.getCartesian(opt);
  41547. }
  41548. var pointerShapeBuilder = {
  41549. line: function (axis, pixelValue, otherExtent) {
  41550. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  41551. return {
  41552. type: 'Line',
  41553. subPixelOptimize: true,
  41554. shape: targetShape
  41555. };
  41556. },
  41557. shadow: function (axis, pixelValue, otherExtent) {
  41558. var bandWidth = Math.max(1, axis.getBandWidth());
  41559. var span = otherExtent[1] - otherExtent[0];
  41560. return {
  41561. type: 'Rect',
  41562. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  41563. };
  41564. }
  41565. };
  41566. function getAxisDimIndex(axis) {
  41567. return axis.dim === 'x' ? 0 : 1;
  41568. }
  41569. var AxisPointerModel =
  41570. /** @class */
  41571. function (_super) {
  41572. __extends(AxisPointerModel, _super);
  41573. function AxisPointerModel() {
  41574. var _this = _super !== null && _super.apply(this, arguments) || this;
  41575. _this.type = AxisPointerModel.type;
  41576. return _this;
  41577. }
  41578. AxisPointerModel.type = 'axisPointer';
  41579. AxisPointerModel.defaultOption = {
  41580. // 'auto' means that show when triggered by tooltip or handle.
  41581. show: 'auto',
  41582. zlevel: 0,
  41583. z: 50,
  41584. type: 'line',
  41585. // axispointer triggered by tootip determine snap automatically,
  41586. // see `modelHelper`.
  41587. snap: false,
  41588. triggerTooltip: true,
  41589. value: null,
  41590. status: null,
  41591. link: [],
  41592. // Do not set 'auto' here, otherwise global animation: false
  41593. // will not effect at this axispointer.
  41594. animation: null,
  41595. animationDurationUpdate: 200,
  41596. lineStyle: {
  41597. color: '#B9BEC9',
  41598. width: 1,
  41599. type: 'dashed'
  41600. },
  41601. shadowStyle: {
  41602. color: 'rgba(210,219,238,0.2)'
  41603. },
  41604. label: {
  41605. show: true,
  41606. formatter: null,
  41607. precision: 'auto',
  41608. margin: 3,
  41609. color: '#fff',
  41610. padding: [5, 7, 5, 7],
  41611. backgroundColor: 'auto',
  41612. borderColor: null,
  41613. borderWidth: 0,
  41614. borderRadius: 3
  41615. },
  41616. handle: {
  41617. show: false,
  41618. // eslint-disable-next-line
  41619. 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',
  41620. size: 45,
  41621. // handle margin is from symbol center to axis, which is stable when circular move.
  41622. margin: 50,
  41623. // color: '#1b8bbd'
  41624. // color: '#2f4554'
  41625. color: '#333',
  41626. shadowBlur: 3,
  41627. shadowColor: '#aaa',
  41628. shadowOffsetX: 0,
  41629. shadowOffsetY: 2,
  41630. // For mobile performance
  41631. throttle: 40
  41632. }
  41633. };
  41634. return AxisPointerModel;
  41635. }(ComponentModel);
  41636. var inner$7 = makeInner();
  41637. var each$4 = each;
  41638. /**
  41639. * @param {string} key
  41640. * @param {module:echarts/ExtensionAPI} api
  41641. * @param {Function} handler
  41642. * param: {string} currTrigger
  41643. * param: {Array.<number>} point
  41644. */
  41645. function register(key, api, handler) {
  41646. if (env.node) {
  41647. return;
  41648. }
  41649. var zr = api.getZr();
  41650. inner$7(zr).records || (inner$7(zr).records = {});
  41651. initGlobalListeners(zr, api);
  41652. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  41653. record.handler = handler;
  41654. }
  41655. function initGlobalListeners(zr, api) {
  41656. if (inner$7(zr).initialized) {
  41657. return;
  41658. }
  41659. inner$7(zr).initialized = true;
  41660. useHandler('click', curry(doEnter, 'click'));
  41661. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  41662. useHandler('globalout', onLeave);
  41663. function useHandler(eventType, cb) {
  41664. zr.on(eventType, function (e) {
  41665. var dis = makeDispatchAction(api);
  41666. each$4(inner$7(zr).records, function (record) {
  41667. record && cb(record, e, dis.dispatchAction);
  41668. });
  41669. dispatchTooltipFinally(dis.pendings, api);
  41670. });
  41671. }
  41672. }
  41673. function dispatchTooltipFinally(pendings, api) {
  41674. var showLen = pendings.showTip.length;
  41675. var hideLen = pendings.hideTip.length;
  41676. var actuallyPayload;
  41677. if (showLen) {
  41678. actuallyPayload = pendings.showTip[showLen - 1];
  41679. } else if (hideLen) {
  41680. actuallyPayload = pendings.hideTip[hideLen - 1];
  41681. }
  41682. if (actuallyPayload) {
  41683. actuallyPayload.dispatchAction = null;
  41684. api.dispatchAction(actuallyPayload);
  41685. }
  41686. }
  41687. function onLeave(record, e, dispatchAction) {
  41688. record.handler('leave', null, dispatchAction);
  41689. }
  41690. function doEnter(currTrigger, record, e, dispatchAction) {
  41691. record.handler(currTrigger, e, dispatchAction);
  41692. }
  41693. function makeDispatchAction(api) {
  41694. var pendings = {
  41695. showTip: [],
  41696. hideTip: []
  41697. }; // FIXME
  41698. // better approach?
  41699. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  41700. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  41701. // So we have to add "final stage" to merge those dispatched actions.
  41702. var dispatchAction = function (payload) {
  41703. var pendingList = pendings[payload.type];
  41704. if (pendingList) {
  41705. pendingList.push(payload);
  41706. } else {
  41707. payload.dispatchAction = dispatchAction;
  41708. api.dispatchAction(payload);
  41709. }
  41710. };
  41711. return {
  41712. dispatchAction: dispatchAction,
  41713. pendings: pendings
  41714. };
  41715. }
  41716. function unregister(key, api) {
  41717. if (env.node) {
  41718. return;
  41719. }
  41720. var zr = api.getZr();
  41721. var record = (inner$7(zr).records || {})[key];
  41722. if (record) {
  41723. inner$7(zr).records[key] = null;
  41724. }
  41725. }
  41726. var AxisPointerView =
  41727. /** @class */
  41728. function (_super) {
  41729. __extends(AxisPointerView, _super);
  41730. function AxisPointerView() {
  41731. var _this = _super !== null && _super.apply(this, arguments) || this;
  41732. _this.type = AxisPointerView.type;
  41733. return _this;
  41734. }
  41735. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  41736. var globalTooltipModel = ecModel.getComponent('tooltip');
  41737. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  41738. // AxisPointerView to be independent to Tooltip.
  41739. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  41740. // If 'none', it is not controlled by mouse totally.
  41741. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  41742. dispatchAction({
  41743. type: 'updateAxisPointer',
  41744. currTrigger: currTrigger,
  41745. x: e && e.offsetX,
  41746. y: e && e.offsetY
  41747. });
  41748. }
  41749. });
  41750. };
  41751. AxisPointerView.prototype.remove = function (ecModel, api) {
  41752. unregister('axisPointer', api);
  41753. };
  41754. AxisPointerView.prototype.dispose = function (ecModel, api) {
  41755. unregister('axisPointer', api);
  41756. };
  41757. AxisPointerView.type = 'axisPointer';
  41758. return AxisPointerView;
  41759. }(ComponentView);
  41760. /**
  41761. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  41762. * @param ecModel
  41763. * @return {point: [x, y], el: ...} point Will not be null.
  41764. */
  41765. function findPointFromSeries(finder, ecModel) {
  41766. var point = [];
  41767. var seriesIndex = finder.seriesIndex;
  41768. var seriesModel;
  41769. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  41770. return {
  41771. point: []
  41772. };
  41773. }
  41774. var data = seriesModel.getData();
  41775. var dataIndex = queryDataIndex(data, finder);
  41776. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  41777. return {
  41778. point: []
  41779. };
  41780. }
  41781. var el = data.getItemGraphicEl(dataIndex);
  41782. var coordSys = seriesModel.coordinateSystem;
  41783. if (seriesModel.getTooltipPosition) {
  41784. point = seriesModel.getTooltipPosition(dataIndex) || [];
  41785. } else if (coordSys && coordSys.dataToPoint) {
  41786. if (finder.isStacked) {
  41787. var baseAxis = coordSys.getBaseAxis();
  41788. var valueAxis = coordSys.getOtherAxis(baseAxis);
  41789. var valueAxisDim = valueAxis.dim;
  41790. var baseAxisDim = baseAxis.dim;
  41791. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  41792. var baseDim = data.mapDimension(baseAxisDim);
  41793. var stackedData = [];
  41794. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  41795. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  41796. point = coordSys.dataToPoint(stackedData) || [];
  41797. } else {
  41798. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  41799. return data.mapDimension(dim);
  41800. }), dataIndex)) || [];
  41801. }
  41802. } else if (el) {
  41803. // Use graphic bounding rect
  41804. var rect = el.getBoundingRect().clone();
  41805. rect.applyTransform(el.transform);
  41806. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  41807. }
  41808. return {
  41809. point: point,
  41810. el: el
  41811. };
  41812. }
  41813. var inner$8 = makeInner();
  41814. /**
  41815. * Basic logic: check all axis, if they do not demand show/highlight,
  41816. * then hide/downplay them.
  41817. *
  41818. * @return content of event obj for echarts.connect.
  41819. */
  41820. function axisTrigger(payload, ecModel, api) {
  41821. var currTrigger = payload.currTrigger;
  41822. var point = [payload.x, payload.y];
  41823. var finder = payload;
  41824. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  41825. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  41826. // See #6121. But we are not able to reproduce it yet.
  41827. if (!coordSysAxesInfo) {
  41828. return;
  41829. }
  41830. if (illegalPoint(point)) {
  41831. // Used in the default behavior of `connection`: use the sample seriesIndex
  41832. // and dataIndex. And also used in the tooltipView trigger.
  41833. point = findPointFromSeries({
  41834. seriesIndex: finder.seriesIndex,
  41835. // Do not use dataIndexInside from other ec instance.
  41836. // FIXME: auto detect it?
  41837. dataIndex: finder.dataIndex
  41838. }, ecModel).point;
  41839. }
  41840. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  41841. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  41842. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  41843. // and dataIndex.
  41844. var inputAxesInfo = finder.axesInfo;
  41845. var axesInfo = coordSysAxesInfo.axesInfo;
  41846. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  41847. var outputPayload = {};
  41848. var showValueMap = {};
  41849. var dataByCoordSys = {
  41850. list: [],
  41851. map: {}
  41852. };
  41853. var updaters = {
  41854. showPointer: curry(showPointer, showValueMap),
  41855. showTooltip: curry(showTooltip, dataByCoordSys)
  41856. }; // Process for triggered axes.
  41857. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  41858. // If a point given, it must be contained by the coordinate system.
  41859. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  41860. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  41861. var axis = axisInfo.axis;
  41862. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  41863. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  41864. var val = inputAxisInfo && inputAxisInfo.value;
  41865. if (val == null && !isIllegalPoint) {
  41866. val = axis.pointToData(point);
  41867. }
  41868. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  41869. }
  41870. });
  41871. }); // Process for linked axes.
  41872. var linkTriggers = {};
  41873. each(axesInfo, function (tarAxisInfo, tarKey) {
  41874. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  41875. if (linkGroup && !showValueMap[tarKey]) {
  41876. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  41877. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  41878. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  41879. var val = srcValItem.value;
  41880. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  41881. linkTriggers[tarAxisInfo.key] = val;
  41882. }
  41883. });
  41884. }
  41885. });
  41886. each(linkTriggers, function (val, tarKey) {
  41887. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  41888. });
  41889. updateModelActually(showValueMap, axesInfo, outputPayload);
  41890. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  41891. dispatchHighDownActually(axesInfo, dispatchAction, api);
  41892. return outputPayload;
  41893. }
  41894. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  41895. var axis = axisInfo.axis;
  41896. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  41897. return;
  41898. }
  41899. if (!axisInfo.involveSeries) {
  41900. updaters.showPointer(axisInfo, newValue);
  41901. return;
  41902. } // Heavy calculation. So put it after axis.containData checking.
  41903. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  41904. var payloadBatch = payloadInfo.payloadBatch;
  41905. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  41906. // By default use the first involved series data as a sample to connect.
  41907. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  41908. extend(outputFinder, payloadBatch[0]);
  41909. } // If no linkSource input, this process is for collecting link
  41910. // target, where snap should not be accepted.
  41911. if (!noSnap && axisInfo.snap) {
  41912. if (axis.containData(snapToValue) && snapToValue != null) {
  41913. newValue = snapToValue;
  41914. }
  41915. }
  41916. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  41917. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  41918. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  41919. }
  41920. function buildPayloadsBySeries(value, axisInfo) {
  41921. var axis = axisInfo.axis;
  41922. var dim = axis.dim;
  41923. var snapToValue = value;
  41924. var payloadBatch = [];
  41925. var minDist = Number.MAX_VALUE;
  41926. var minDiff = -1;
  41927. each(axisInfo.seriesModels, function (series, idx) {
  41928. var dataDim = series.getData().mapDimensionsAll(dim);
  41929. var seriesNestestValue;
  41930. var dataIndices;
  41931. if (series.getAxisTooltipData) {
  41932. var result = series.getAxisTooltipData(dataDim, value, axis);
  41933. dataIndices = result.dataIndices;
  41934. seriesNestestValue = result.nestestValue;
  41935. } else {
  41936. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  41937. // when data length is not same.
  41938. // false,
  41939. axis.type === 'category' ? 0.5 : null);
  41940. if (!dataIndices.length) {
  41941. return;
  41942. }
  41943. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  41944. }
  41945. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  41946. return;
  41947. }
  41948. var diff = value - seriesNestestValue;
  41949. var dist = Math.abs(diff); // Consider category case
  41950. if (dist <= minDist) {
  41951. if (dist < minDist || diff >= 0 && minDiff < 0) {
  41952. minDist = dist;
  41953. minDiff = diff;
  41954. snapToValue = seriesNestestValue;
  41955. payloadBatch.length = 0;
  41956. }
  41957. each(dataIndices, function (dataIndex) {
  41958. payloadBatch.push({
  41959. seriesIndex: series.seriesIndex,
  41960. dataIndexInside: dataIndex,
  41961. dataIndex: series.getData().getRawIndex(dataIndex)
  41962. });
  41963. });
  41964. }
  41965. });
  41966. return {
  41967. payloadBatch: payloadBatch,
  41968. snapToValue: snapToValue
  41969. };
  41970. }
  41971. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  41972. showValueMap[axisInfo.key] = {
  41973. value: value,
  41974. payloadBatch: payloadBatch
  41975. };
  41976. }
  41977. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  41978. var payloadBatch = payloadInfo.payloadBatch;
  41979. var axis = axisInfo.axis;
  41980. var axisModel = axis.model;
  41981. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  41982. // whose length will be used to judge whether dispatch action.
  41983. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  41984. return;
  41985. }
  41986. var coordSysModel = axisInfo.coordSys.model;
  41987. var coordSysKey = makeKey(coordSysModel);
  41988. var coordSysItem = dataByCoordSys.map[coordSysKey];
  41989. if (!coordSysItem) {
  41990. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  41991. coordSysId: coordSysModel.id,
  41992. coordSysIndex: coordSysModel.componentIndex,
  41993. coordSysType: coordSysModel.type,
  41994. coordSysMainType: coordSysModel.mainType,
  41995. dataByAxis: []
  41996. };
  41997. dataByCoordSys.list.push(coordSysItem);
  41998. }
  41999. coordSysItem.dataByAxis.push({
  42000. axisDim: axis.dim,
  42001. axisIndex: axisModel.componentIndex,
  42002. axisType: axisModel.type,
  42003. axisId: axisModel.id,
  42004. value: value,
  42005. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  42006. // depends that all models have been updated. So it should not be performed
  42007. // here. Considering axisPointerModel used here is volatile, which is hard
  42008. // to be retrieve in TooltipView, we prepare parameters here.
  42009. valueLabelOpt: {
  42010. precision: axisPointerModel.get(['label', 'precision']),
  42011. formatter: axisPointerModel.get(['label', 'formatter'])
  42012. },
  42013. seriesDataIndices: payloadBatch.slice()
  42014. });
  42015. }
  42016. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  42017. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  42018. each(axesInfo, function (axisInfo, key) {
  42019. var option = axisInfo.axisPointerModel.option;
  42020. var valItem = showValueMap[key];
  42021. if (valItem) {
  42022. !axisInfo.useHandle && (option.status = 'show');
  42023. option.value = valItem.value; // For label formatter param and highlight.
  42024. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  42025. } // When always show (e.g., handle used), remain
  42026. // original value and status.
  42027. else {
  42028. // If hide, value still need to be set, consider
  42029. // click legend to toggle axis blank.
  42030. !axisInfo.useHandle && (option.status = 'hide');
  42031. } // If status is 'hide', should be no info in payload.
  42032. option.status === 'show' && outputAxesInfo.push({
  42033. axisDim: axisInfo.axis.dim,
  42034. axisIndex: axisInfo.axis.model.componentIndex,
  42035. value: option.value
  42036. });
  42037. });
  42038. }
  42039. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  42040. // Basic logic: If no showTip required, hideTip will be dispatched.
  42041. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  42042. dispatchAction({
  42043. type: 'hideTip'
  42044. });
  42045. return;
  42046. } // In most case only one axis (or event one series is used). It is
  42047. // convinient to fetch payload.seriesIndex and payload.dataIndex
  42048. // dirtectly. So put the first seriesIndex and dataIndex of the first
  42049. // axis on the payload.
  42050. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  42051. dispatchAction({
  42052. type: 'showTip',
  42053. escapeConnect: true,
  42054. x: point[0],
  42055. y: point[1],
  42056. tooltipOption: payload.tooltipOption,
  42057. position: payload.position,
  42058. dataIndexInside: sampleItem.dataIndexInside,
  42059. dataIndex: sampleItem.dataIndex,
  42060. seriesIndex: sampleItem.seriesIndex,
  42061. dataByCoordSys: dataByCoordSys.list
  42062. });
  42063. }
  42064. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  42065. // FIXME
  42066. // highlight status modification shoule be a stage of main process?
  42067. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  42068. var zr = api.getZr();
  42069. var highDownKey = 'axisPointerLastHighlights';
  42070. var lastHighlights = inner$8(zr)[highDownKey] || {};
  42071. var newHighlights = inner$8(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  42072. // Build hash map and remove duplicate incidentally.
  42073. each(axesInfo, function (axisInfo, key) {
  42074. var option = axisInfo.axisPointerModel.option;
  42075. option.status === 'show' && each(option.seriesDataIndices, function (batchItem) {
  42076. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  42077. newHighlights[key] = batchItem;
  42078. });
  42079. }); // Diff.
  42080. var toHighlight = [];
  42081. var toDownplay = [];
  42082. each(lastHighlights, function (batchItem, key) {
  42083. !newHighlights[key] && toDownplay.push(batchItem);
  42084. });
  42085. each(newHighlights, function (batchItem, key) {
  42086. !lastHighlights[key] && toHighlight.push(batchItem);
  42087. });
  42088. toDownplay.length && api.dispatchAction({
  42089. type: 'downplay',
  42090. escapeConnect: true,
  42091. // Not blur others when highlight in axisPointer.
  42092. notBlur: true,
  42093. batch: toDownplay
  42094. });
  42095. toHighlight.length && api.dispatchAction({
  42096. type: 'highlight',
  42097. escapeConnect: true,
  42098. // Not blur others when highlight in axisPointer.
  42099. notBlur: true,
  42100. batch: toHighlight
  42101. });
  42102. }
  42103. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  42104. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  42105. var inputAxisInfo = inputAxesInfo[i];
  42106. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  42107. return inputAxisInfo;
  42108. }
  42109. }
  42110. }
  42111. function makeMapperParam(axisInfo) {
  42112. var axisModel = axisInfo.axis.model;
  42113. var item = {};
  42114. var dim = item.axisDim = axisInfo.axis.dim;
  42115. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  42116. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  42117. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  42118. return item;
  42119. }
  42120. function illegalPoint(point) {
  42121. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  42122. }
  42123. function install$7(registers) {
  42124. // CartesianAxisPointer is not supposed to be required here. But consider
  42125. // echarts.simple.js and online build tooltip, which only require gridSimple,
  42126. // CartesianAxisPointer should be able to required somewhere.
  42127. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  42128. registers.registerComponentModel(AxisPointerModel);
  42129. registers.registerComponentView(AxisPointerView);
  42130. registers.registerPreprocessor(function (option) {
  42131. // Always has a global axisPointerModel for default setting.
  42132. if (option) {
  42133. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  42134. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  42135. // is not set, remain null/undefined, otherwise it will
  42136. // override existent link setting.
  42137. if (link && !isArray(link)) {
  42138. option.axisPointer.link = [link];
  42139. }
  42140. }
  42141. }); // This process should proformed after coordinate systems created
  42142. // and series data processed. So put it on statistic processing stage.
  42143. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  42144. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  42145. // allAxesInfo should be updated when setOption performed.
  42146. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  42147. }); // Broadcast to all views.
  42148. registers.registerAction({
  42149. type: 'updateAxisPointer',
  42150. event: 'updateAxisPointer',
  42151. update: ':updateAxisPointer'
  42152. }, axisTrigger);
  42153. }
  42154. function install$8(registers) {
  42155. use(install$5);
  42156. use(install$7);
  42157. }
  42158. /**
  42159. * Whether need to call `convertEC4CompatibleStyle`.
  42160. */
  42161. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  42162. // Since echarts5, `RectText` is separated from its host element and style.text
  42163. // does not exist any more. The compat work brings some extra burden on performance.
  42164. // So we provide:
  42165. // `legacy: true` force make compat.
  42166. // `legacy: false`, force do not compat.
  42167. // `legacy` not set: auto detect wheter legacy.
  42168. // But in this case we do not compat (difficult to detect and rare case):
  42169. // Becuse custom series and graphic component support "merge", users may firstly
  42170. // only set `textStrokeWidth` style or secondly only set `text`.
  42171. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  42172. && (elType === 'text' || hasOwn(style, 'text')));
  42173. }
  42174. /**
  42175. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  42176. * @param hostStyle The properties might be modified.
  42177. * @return If be text el, `textContentStyle` and `textConfig` will not be retured.
  42178. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  42179. * retried from the `hostStyle`.
  42180. */
  42181. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  42182. var srcStyle = hostStyle;
  42183. var textConfig;
  42184. var textContent;
  42185. var textContentStyle;
  42186. if (elType === 'text') {
  42187. textContentStyle = srcStyle;
  42188. } else {
  42189. textContentStyle = {};
  42190. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  42191. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  42192. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  42193. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  42194. textContent = {
  42195. type: 'text',
  42196. style: textContentStyle,
  42197. // ec4 do not support rectText trigger.
  42198. // And when text postion is different in normal and emphasis
  42199. // => hover text trigger emphasis;
  42200. // => text position changed, leave mouse pointer immediately;
  42201. // That might cause state incorrect.
  42202. silent: true
  42203. };
  42204. textConfig = {};
  42205. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  42206. if (isNormal) {
  42207. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  42208. } else {
  42209. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  42210. }
  42211. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  42212. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  42213. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  42214. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  42215. }
  42216. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  42217. each(textContentStyle.rich, function (richItem) {
  42218. convertEC4CompatibleRichItem(richItem, richItem);
  42219. });
  42220. return {
  42221. textConfig: textConfig,
  42222. textContent: textContent
  42223. };
  42224. }
  42225. /**
  42226. * The result will be set to `out`.
  42227. */
  42228. function convertEC4CompatibleRichItem(out, richItem) {
  42229. if (!richItem) {
  42230. return;
  42231. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  42232. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  42233. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  42234. // richText in ec5.
  42235. // (2) `out === richItem` if and only if `out` is text el or rich item.
  42236. // So we can overwite existing props in `out` since textXXX has higher priority.
  42237. richItem.font = richItem.textFont || richItem.font;
  42238. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  42239. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  42240. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  42241. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  42242. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  42243. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  42244. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  42245. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  42246. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  42247. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  42248. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  42249. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  42250. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  42251. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  42252. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  42253. }
  42254. var inner$9 = makeInner();
  42255. var _nonShapeGraphicElements = {
  42256. // Reserved but not supported in graphic component.
  42257. path: null,
  42258. compoundPath: null,
  42259. // Supported in graphic component.
  42260. group: Group,
  42261. image: ZRImage,
  42262. text: ZRText
  42263. }; // ------------------------
  42264. // Preprocessor
  42265. // ------------------------
  42266. var preprocessor = function (option) {
  42267. var graphicOption = option.graphic; // Convert
  42268. // {graphic: [{left: 10, type: 'circle'}, ...]}
  42269. // or
  42270. // {graphic: {left: 10, type: 'circle'}}
  42271. // to
  42272. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  42273. if (isArray(graphicOption)) {
  42274. if (!graphicOption[0] || !graphicOption[0].elements) {
  42275. option.graphic = [{
  42276. elements: graphicOption
  42277. }];
  42278. } else {
  42279. // Only one graphic instance can be instantiated. (We dont
  42280. // want that too many views are created in echarts._viewMap)
  42281. option.graphic = [option.graphic[0]];
  42282. }
  42283. } else if (graphicOption && !graphicOption.elements) {
  42284. option.graphic = [{
  42285. elements: [graphicOption]
  42286. }];
  42287. }
  42288. };
  42289. var GraphicComponentModel =
  42290. /** @class */
  42291. function (_super) {
  42292. __extends(GraphicComponentModel, _super);
  42293. function GraphicComponentModel() {
  42294. var _this = _super !== null && _super.apply(this, arguments) || this;
  42295. _this.type = GraphicComponentModel.type;
  42296. return _this;
  42297. }
  42298. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  42299. // Prevent default merge to elements
  42300. var elements = this.option.elements;
  42301. this.option.elements = null;
  42302. _super.prototype.mergeOption.call(this, option, ecModel);
  42303. this.option.elements = elements;
  42304. };
  42305. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  42306. var thisOption = this.option;
  42307. var newList = (isInit ? thisOption : newOption).elements;
  42308. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  42309. var flattenedList = [];
  42310. this._flatten(newList, flattenedList, null);
  42311. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  42312. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  42313. each(mappingResult, function (resultItem, index) {
  42314. var newElOption = resultItem.newOption;
  42315. if ("development" !== 'production') {
  42316. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  42317. }
  42318. if (!newElOption) {
  42319. return;
  42320. }
  42321. elOptionsToUpdate.push(newElOption);
  42322. setKeyInfoToNewElOption(resultItem, newElOption);
  42323. mergeNewElOptionToExist(existList, index, newElOption);
  42324. setLayoutInfoToExist(existList[index], newElOption);
  42325. }, this); // Clean
  42326. for (var i = existList.length - 1; i >= 0; i--) {
  42327. if (existList[i] == null) {
  42328. existList.splice(i, 1);
  42329. } else {
  42330. // $action should be volatile, otherwise option gotten from
  42331. // `getOption` will contain unexpected $action.
  42332. delete existList[i].$action;
  42333. }
  42334. }
  42335. };
  42336. /**
  42337. * Convert
  42338. * [{
  42339. * type: 'group',
  42340. * id: 'xx',
  42341. * children: [{type: 'circle'}, {type: 'polygon'}]
  42342. * }]
  42343. * to
  42344. * [
  42345. * {type: 'group', id: 'xx'},
  42346. * {type: 'circle', parentId: 'xx'},
  42347. * {type: 'polygon', parentId: 'xx'}
  42348. * ]
  42349. */
  42350. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  42351. each(optionList, function (option) {
  42352. if (!option) {
  42353. return;
  42354. }
  42355. if (parentOption) {
  42356. option.parentOption = parentOption;
  42357. }
  42358. result.push(option);
  42359. var children = option.children;
  42360. if (option.type === 'group' && children) {
  42361. this._flatten(children, result, option);
  42362. } // Deleting for JSON output, and for not affecting group creation.
  42363. delete option.children;
  42364. }, this);
  42365. }; // FIXME
  42366. // Pass to view using payload? setOption has a payload?
  42367. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  42368. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  42369. this._elOptionsToUpdate = null;
  42370. return els;
  42371. };
  42372. GraphicComponentModel.type = 'graphic';
  42373. GraphicComponentModel.defaultOption = {
  42374. elements: [] // parentId: null
  42375. };
  42376. return GraphicComponentModel;
  42377. }(ComponentModel); // ------------------------
  42378. // View
  42379. // ------------------------
  42380. var GraphicComponentView =
  42381. /** @class */
  42382. function (_super) {
  42383. __extends(GraphicComponentView, _super);
  42384. function GraphicComponentView() {
  42385. var _this = _super !== null && _super.apply(this, arguments) || this;
  42386. _this.type = GraphicComponentView.type;
  42387. return _this;
  42388. }
  42389. GraphicComponentView.prototype.init = function () {
  42390. this._elMap = createHashMap();
  42391. };
  42392. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  42393. // Having leveraged between use cases and algorithm complexity, a very
  42394. // simple layout mechanism is used:
  42395. // The size(width/height) can be determined by itself or its parent (not
  42396. // implemented yet), but can not by its children. (Top-down travel)
  42397. // The location(x/y) can be determined by the bounding rect of itself
  42398. // (can including its descendants or not) and the size of its parent.
  42399. // (Bottom-up travel)
  42400. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  42401. // view will be reused.
  42402. if (graphicModel !== this._lastGraphicModel) {
  42403. this._clear();
  42404. }
  42405. this._lastGraphicModel = graphicModel;
  42406. this._updateElements(graphicModel);
  42407. this._relocate(graphicModel, api);
  42408. };
  42409. /**
  42410. * Update graphic elements.
  42411. */
  42412. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  42413. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  42414. if (!elOptionsToUpdate) {
  42415. return;
  42416. }
  42417. var elMap = this._elMap;
  42418. var rootGroup = this.group; // Top-down tranverse to assign graphic settings to each elements.
  42419. each(elOptionsToUpdate, function (elOption) {
  42420. var id = convertOptionIdName(elOption.id, null);
  42421. var elExisting = id != null ? elMap.get(id) : null;
  42422. var parentId = convertOptionIdName(elOption.parentId, null);
  42423. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  42424. var elType = elOption.type;
  42425. var elOptionStyle = elOption.style;
  42426. if (elType === 'text' && elOptionStyle) {
  42427. // In top/bottom mode, textVerticalAlign should not be used, which cause
  42428. // inaccurately locating.
  42429. if (elOption.hv && elOption.hv[1]) {
  42430. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  42431. }
  42432. }
  42433. var textContentOption = elOption.textContent;
  42434. var textConfig = elOption.textConfig;
  42435. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  42436. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  42437. if (!textConfig && convertResult.textConfig) {
  42438. textConfig = elOption.textConfig = convertResult.textConfig;
  42439. }
  42440. if (!textContentOption && convertResult.textContent) {
  42441. textContentOption = convertResult.textContent;
  42442. }
  42443. } // Remove unnecessary props to avoid potential problems.
  42444. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  42445. if ("development" !== 'production') {
  42446. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  42447. }
  42448. var $action = elOption.$action || 'merge';
  42449. if ($action === 'merge') {
  42450. elExisting ? elExisting.attr(elOptionCleaned) : createEl(id, targetElParent, elOptionCleaned, elMap);
  42451. } else if ($action === 'replace') {
  42452. removeEl(elExisting, elMap);
  42453. createEl(id, targetElParent, elOptionCleaned, elMap);
  42454. } else if ($action === 'remove') {
  42455. removeEl(elExisting, elMap);
  42456. }
  42457. var el = elMap.get(id);
  42458. if (el && textContentOption) {
  42459. if ($action === 'merge') {
  42460. var textContentExisting = el.getTextContent();
  42461. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  42462. } else if ($action === 'replace') {
  42463. el.setTextContent(new ZRText(textContentOption));
  42464. }
  42465. }
  42466. if (el) {
  42467. var elInner = inner$9(el);
  42468. elInner.__ecGraphicWidthOption = elOption.width;
  42469. elInner.__ecGraphicHeightOption = elOption.height;
  42470. setEventData(el, graphicModel, elOption);
  42471. }
  42472. });
  42473. };
  42474. /**
  42475. * Locate graphic elements.
  42476. */
  42477. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  42478. var elOptions = graphicModel.option.elements;
  42479. var rootGroup = this.group;
  42480. var elMap = this._elMap;
  42481. var apiWidth = api.getWidth();
  42482. var apiHeight = api.getHeight(); // Top-down to calculate percentage width/height of group
  42483. for (var i = 0; i < elOptions.length; i++) {
  42484. var elOption = elOptions[i];
  42485. var id = convertOptionIdName(elOption.id, null);
  42486. var el = id != null ? elMap.get(id) : null;
  42487. if (!el || !el.isGroup) {
  42488. continue;
  42489. }
  42490. var parentEl = el.parent;
  42491. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  42492. var elInner = inner$9(el);
  42493. var parentElInner = inner$9(parentEl);
  42494. elInner.__ecGraphicWidth = parsePercent$1(elInner.__ecGraphicWidthOption, isParentRoot ? apiWidth : parentElInner.__ecGraphicWidth) || 0;
  42495. elInner.__ecGraphicHeight = parsePercent$1(elInner.__ecGraphicHeightOption, isParentRoot ? apiHeight : parentElInner.__ecGraphicHeight) || 0;
  42496. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  42497. for (var i = elOptions.length - 1; i >= 0; i--) {
  42498. var elOption = elOptions[i];
  42499. var id = convertOptionIdName(elOption.id, null);
  42500. var el = id != null ? elMap.get(id) : null;
  42501. if (!el) {
  42502. continue;
  42503. }
  42504. var parentEl = el.parent;
  42505. var parentElInner = inner$9(parentEl);
  42506. var containerInfo = parentEl === rootGroup ? {
  42507. width: apiWidth,
  42508. height: apiHeight
  42509. } : {
  42510. width: parentElInner.__ecGraphicWidth,
  42511. height: parentElInner.__ecGraphicHeight
  42512. }; // PENDING
  42513. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  42514. // does not include the rect of [0, 0, group.width, group.height], which
  42515. // is probably weird for users. Should we make a break change for it?
  42516. positionElement(el, elOption, containerInfo, null, {
  42517. hv: elOption.hv,
  42518. boundingMode: elOption.bounding
  42519. });
  42520. }
  42521. };
  42522. /**
  42523. * Clear all elements.
  42524. */
  42525. GraphicComponentView.prototype._clear = function () {
  42526. var elMap = this._elMap;
  42527. elMap.each(function (el) {
  42528. removeEl(el, elMap);
  42529. });
  42530. this._elMap = createHashMap();
  42531. };
  42532. GraphicComponentView.prototype.dispose = function () {
  42533. this._clear();
  42534. };
  42535. GraphicComponentView.type = 'graphic';
  42536. return GraphicComponentView;
  42537. }(ComponentView);
  42538. function createEl(id, targetElParent, elOption, elMap) {
  42539. var graphicType = elOption.type;
  42540. if ("development" !== 'production') {
  42541. assert(graphicType, 'graphic type MUST be set');
  42542. }
  42543. var Clz = hasOwn(_nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  42544. // overwritten by users, so do them first.
  42545. ? _nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  42546. if ("development" !== 'production') {
  42547. assert(Clz, 'graphic type can not be found');
  42548. }
  42549. var el = new Clz(elOption);
  42550. targetElParent.add(el);
  42551. elMap.set(id, el);
  42552. inner$9(el).__ecGraphicId = id;
  42553. }
  42554. function removeEl(elExisting, elMap) {
  42555. var existElParent = elExisting && elExisting.parent;
  42556. if (existElParent) {
  42557. elExisting.type === 'group' && elExisting.traverse(function (el) {
  42558. removeEl(el, elMap);
  42559. });
  42560. elMap.removeKey(inner$9(elExisting).__ecGraphicId);
  42561. existElParent.remove(elExisting);
  42562. }
  42563. } // Remove unnecessary props to avoid potential problems.
  42564. function getCleanedElOption(elOption) {
  42565. elOption = extend({}, elOption);
  42566. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent'].concat(LOCATION_PARAMS), function (name) {
  42567. delete elOption[name];
  42568. });
  42569. return elOption;
  42570. }
  42571. function isSetLoc(obj, props) {
  42572. var isSet;
  42573. each(props, function (prop) {
  42574. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  42575. });
  42576. return isSet;
  42577. }
  42578. function setKeyInfoToNewElOption(resultItem, newElOption) {
  42579. var existElOption = resultItem.existing; // Set id and type after id assigned.
  42580. newElOption.id = resultItem.keyInfo.id;
  42581. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  42582. if (newElOption.parentId == null) {
  42583. var newElParentOption = newElOption.parentOption;
  42584. if (newElParentOption) {
  42585. newElOption.parentId = newElParentOption.id;
  42586. } else if (existElOption) {
  42587. newElOption.parentId = existElOption.parentId;
  42588. }
  42589. } // Clear
  42590. newElOption.parentOption = null;
  42591. }
  42592. function mergeNewElOptionToExist(existList, index, newElOption) {
  42593. // Update existing options, for `getOption` feature.
  42594. var newElOptCopy = extend({}, newElOption);
  42595. var existElOption = existList[index];
  42596. var $action = newElOption.$action || 'merge';
  42597. if ($action === 'merge') {
  42598. if (existElOption) {
  42599. if ("development" !== 'production') {
  42600. var newType = newElOption.type;
  42601. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  42602. } // We can ensure that newElOptCopy and existElOption are not
  42603. // the same object, so `merge` will not change newElOptCopy.
  42604. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  42605. mergeLayoutParam(existElOption, newElOptCopy, {
  42606. ignoreSize: true
  42607. }); // Will be used in render.
  42608. copyLayoutParams(newElOption, existElOption);
  42609. } else {
  42610. existList[index] = newElOptCopy;
  42611. }
  42612. } else if ($action === 'replace') {
  42613. existList[index] = newElOptCopy;
  42614. } else if ($action === 'remove') {
  42615. // null will be cleaned later.
  42616. existElOption && (existList[index] = null);
  42617. }
  42618. }
  42619. function setLayoutInfoToExist(existItem, newElOption) {
  42620. if (!existItem) {
  42621. return;
  42622. }
  42623. existItem.hv = newElOption.hv = [// Rigid body, dont care `width`.
  42624. isSetLoc(newElOption, ['left', 'right']), // Rigid body, dont care `height`.
  42625. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  42626. if (existItem.type === 'group') {
  42627. var existingGroupOpt = existItem;
  42628. var newGroupOpt = newElOption;
  42629. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  42630. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  42631. }
  42632. }
  42633. function setEventData(el, graphicModel, elOption) {
  42634. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  42635. if (!el.silent && !el.ignore && !eventData) {
  42636. eventData = getECData(el).eventData = {
  42637. componentType: 'graphic',
  42638. componentIndex: graphicModel.componentIndex,
  42639. name: el.name
  42640. };
  42641. } // `elOption.info` enables user to mount some info on
  42642. // elements and use them in event handlers.
  42643. if (eventData) {
  42644. eventData.info = elOption.info;
  42645. }
  42646. }
  42647. function install$9(registers) {
  42648. registers.registerComponentModel(GraphicComponentModel);
  42649. registers.registerComponentView(GraphicComponentView);
  42650. registers.registerPreprocessor(preprocessor);
  42651. }
  42652. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  42653. // FIXME: polar has been broken (but rarely used).
  42654. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  42655. function isCoordSupported(seriesModel) {
  42656. var coordType = seriesModel.get('coordinateSystem');
  42657. return indexOf(SERIES_COORDS, coordType) >= 0;
  42658. }
  42659. function getAxisMainType(axisDim) {
  42660. if ("development" !== 'production') {
  42661. assert(axisDim);
  42662. }
  42663. return axisDim + 'Axis';
  42664. }
  42665. /**
  42666. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  42667. * This function finds all linked dataZoomModels start from the given payload.
  42668. */
  42669. function findEffectedDataZooms(ecModel, payload) {
  42670. // Key: `DataZoomAxisDimension`
  42671. var axisRecords = createHashMap();
  42672. var effectedModels = []; // Key: uid of dataZoomModel
  42673. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  42674. ecModel.eachComponent({
  42675. mainType: 'dataZoom',
  42676. query: payload
  42677. }, function (dataZoomModel) {
  42678. if (!effectedModelMap.get(dataZoomModel.uid)) {
  42679. addToEffected(dataZoomModel);
  42680. }
  42681. }); // Start from the given dataZoomModels, travel the graph to find
  42682. // all of the linked dataZoom models.
  42683. var foundNewLink;
  42684. do {
  42685. foundNewLink = false;
  42686. ecModel.eachComponent('dataZoom', processSingle);
  42687. } while (foundNewLink);
  42688. function processSingle(dataZoomModel) {
  42689. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  42690. addToEffected(dataZoomModel);
  42691. foundNewLink = true;
  42692. }
  42693. }
  42694. function addToEffected(dataZoom) {
  42695. effectedModelMap.set(dataZoom.uid, true);
  42696. effectedModels.push(dataZoom);
  42697. markAxisControlled(dataZoom);
  42698. }
  42699. function isLinked(dataZoomModel) {
  42700. var isLink = false;
  42701. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  42702. var axisIdxArr = axisRecords.get(axisDim);
  42703. if (axisIdxArr && axisIdxArr[axisIndex]) {
  42704. isLink = true;
  42705. }
  42706. });
  42707. return isLink;
  42708. }
  42709. function markAxisControlled(dataZoomModel) {
  42710. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  42711. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  42712. });
  42713. }
  42714. return effectedModels;
  42715. }
  42716. /**
  42717. * Find the first target coordinate system.
  42718. * Available after model built.
  42719. *
  42720. * @return Like {
  42721. * grid: [
  42722. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  42723. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  42724. * ...
  42725. * ], // cartesians must not be null/undefined.
  42726. * polar: [
  42727. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  42728. * ...
  42729. * ], // polars must not be null/undefined.
  42730. * singleAxis: [
  42731. * {model: coord0, axisModels: [], coordIndex: 0}
  42732. * ]
  42733. * }
  42734. */
  42735. function collectReferCoordSysModelInfo(dataZoomModel) {
  42736. var ecModel = dataZoomModel.ecModel;
  42737. var coordSysInfoWrap = {
  42738. infoList: [],
  42739. infoMap: createHashMap()
  42740. };
  42741. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  42742. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  42743. if (!axisModel) {
  42744. return;
  42745. }
  42746. var coordSysModel = axisModel.getCoordSysModel();
  42747. if (!coordSysModel) {
  42748. return;
  42749. }
  42750. var coordSysUid = coordSysModel.uid;
  42751. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  42752. if (!coordSysInfo) {
  42753. coordSysInfo = {
  42754. model: coordSysModel,
  42755. axisModels: []
  42756. };
  42757. coordSysInfoWrap.infoList.push(coordSysInfo);
  42758. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  42759. }
  42760. coordSysInfo.axisModels.push(axisModel);
  42761. });
  42762. return coordSysInfoWrap;
  42763. }
  42764. var DataZoomAxisInfo =
  42765. /** @class */
  42766. function () {
  42767. function DataZoomAxisInfo() {
  42768. this.indexList = [];
  42769. this.indexMap = [];
  42770. }
  42771. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  42772. // Remove duplication.
  42773. if (!this.indexMap[axisCmptIdx]) {
  42774. this.indexList.push(axisCmptIdx);
  42775. this.indexMap[axisCmptIdx] = true;
  42776. }
  42777. };
  42778. return DataZoomAxisInfo;
  42779. }();
  42780. var DataZoomModel =
  42781. /** @class */
  42782. function (_super) {
  42783. __extends(DataZoomModel, _super);
  42784. function DataZoomModel() {
  42785. var _this = _super !== null && _super.apply(this, arguments) || this;
  42786. _this.type = DataZoomModel.type;
  42787. _this._autoThrottle = true;
  42788. _this._noTarget = true;
  42789. /**
  42790. * It is `[rangeModeForMin, rangeModeForMax]`.
  42791. * The optional values for `rangeMode`:
  42792. * + `'value'` mode: the axis extent will always be determined by
  42793. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  42794. * how data like and how `axis.min` and `axis.max` are.
  42795. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  42796. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  42797. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  42798. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  42799. *
  42800. * For example, when users are using dynamic data (update data periodically via `setOption`),
  42801. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  42802. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  42803. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  42804. */
  42805. _this._rangePropMode = ['percent', 'percent'];
  42806. return _this;
  42807. }
  42808. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  42809. var inputRawOption = retrieveRawOption(option);
  42810. /**
  42811. * Suppose a "main process" start at the point that model prepared (that is,
  42812. * model initialized or merged or method called in `action`).
  42813. * We should keep the `main process` idempotent, that is, given a set of values
  42814. * on `option`, we get the same result.
  42815. *
  42816. * But sometimes, values on `option` will be updated for providing users
  42817. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  42818. * should not be the base/input of the `main process`.
  42819. *
  42820. * So in that case we should save and keep the input of the `main process`
  42821. * separately, called `settledOption`.
  42822. *
  42823. * For example, consider the case:
  42824. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  42825. * where the original input `option.startValue`, `option.endValue` are earsed by
  42826. * calculated value.
  42827. * (Step)2) click the legend to hide and show a series,
  42828. * where the new range is calculated by the earsed `startValue` and `endValue`,
  42829. * which brings incorrect result.
  42830. */
  42831. this.settledOption = inputRawOption;
  42832. this.mergeDefaultAndTheme(option, ecModel);
  42833. this._doInit(inputRawOption);
  42834. };
  42835. DataZoomModel.prototype.mergeOption = function (newOption) {
  42836. var inputRawOption = retrieveRawOption(newOption); //FIX #2591
  42837. merge(this.option, newOption, true);
  42838. merge(this.settledOption, inputRawOption, true);
  42839. this._doInit(inputRawOption);
  42840. };
  42841. DataZoomModel.prototype._doInit = function (inputRawOption) {
  42842. var thisOption = this.option; // if (!env.canvasSupported) {
  42843. // thisOption.realtime = false;
  42844. // }
  42845. this._setDefaultThrottle(inputRawOption);
  42846. this._updateRangeUse(inputRawOption);
  42847. var settledOption = this.settledOption;
  42848. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  42849. // start/end has higher priority over startValue/endValue if they
  42850. // both set, but we should make chart.setOption({endValue: 1000})
  42851. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  42852. if (this._rangePropMode[index] === 'value') {
  42853. thisOption[names[0]] = settledOption[names[0]] = null;
  42854. } // Otherwise do nothing and use the merge result.
  42855. }, this);
  42856. this._resetTarget();
  42857. };
  42858. DataZoomModel.prototype._resetTarget = function () {
  42859. var optionOrient = this.get('orient', true);
  42860. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  42861. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  42862. if (hasAxisSpecified) {
  42863. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  42864. } else {
  42865. this._orient = optionOrient || 'horizontal';
  42866. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  42867. }
  42868. this._noTarget = true;
  42869. targetAxisIndexMap.each(function (axisInfo) {
  42870. if (axisInfo.indexList.length) {
  42871. this._noTarget = false;
  42872. }
  42873. }, this);
  42874. };
  42875. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  42876. var hasAxisSpecified = false;
  42877. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  42878. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  42879. // but do not want use auto mode. Because empty array may be encountered when
  42880. // some error occured.
  42881. if (!refering.specified) {
  42882. return;
  42883. }
  42884. hasAxisSpecified = true;
  42885. var axisInfo = new DataZoomAxisInfo();
  42886. each(refering.models, function (axisModel) {
  42887. axisInfo.add(axisModel.componentIndex);
  42888. });
  42889. targetAxisIndexMap.set(axisDim, axisInfo);
  42890. }, this);
  42891. return hasAxisSpecified;
  42892. };
  42893. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  42894. var ecModel = this.ecModel;
  42895. var needAuto = true; // Find axis that parallel to dataZoom as default.
  42896. if (needAuto) {
  42897. var axisDim = orient === 'vertical' ? 'y' : 'x';
  42898. var axisModels = ecModel.findComponents({
  42899. mainType: axisDim + 'Axis'
  42900. });
  42901. setParallelAxis(axisModels, axisDim);
  42902. } // Find axis that parallel to dataZoom as default.
  42903. if (needAuto) {
  42904. var axisModels = ecModel.findComponents({
  42905. mainType: 'singleAxis',
  42906. filter: function (axisModel) {
  42907. return axisModel.get('orient', true) === orient;
  42908. }
  42909. });
  42910. setParallelAxis(axisModels, 'single');
  42911. }
  42912. function setParallelAxis(axisModels, axisDim) {
  42913. // At least use the first parallel axis as the target axis.
  42914. var axisModel = axisModels[0];
  42915. if (!axisModel) {
  42916. return;
  42917. }
  42918. var axisInfo = new DataZoomAxisInfo();
  42919. axisInfo.add(axisModel.componentIndex);
  42920. targetAxisIndexMap.set(axisDim, axisInfo);
  42921. needAuto = false; // Find parallel axes in the same grid.
  42922. if (axisDim === 'x' || axisDim === 'y') {
  42923. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  42924. gridModel_1 && each(axisModels, function (axModel) {
  42925. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  42926. axisInfo.add(axModel.componentIndex);
  42927. }
  42928. });
  42929. }
  42930. }
  42931. if (needAuto) {
  42932. // If no parallel axis, find the first category axis as default. (Also consider polar).
  42933. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  42934. if (!needAuto) {
  42935. return;
  42936. }
  42937. var axisModels = ecModel.findComponents({
  42938. mainType: getAxisMainType(axisDim),
  42939. filter: function (axisModel) {
  42940. return axisModel.get('type', true) === 'category';
  42941. }
  42942. });
  42943. if (axisModels[0]) {
  42944. var axisInfo = new DataZoomAxisInfo();
  42945. axisInfo.add(axisModels[0].componentIndex);
  42946. targetAxisIndexMap.set(axisDim, axisInfo);
  42947. needAuto = false;
  42948. }
  42949. }, this);
  42950. }
  42951. };
  42952. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  42953. var dim; // Find the first axis
  42954. this.eachTargetAxis(function (axisDim) {
  42955. !dim && (dim = axisDim);
  42956. }, this);
  42957. return dim === 'y' ? 'vertical' : 'horizontal';
  42958. };
  42959. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  42960. // When first time user set throttle, auto throttle ends.
  42961. if (inputRawOption.hasOwnProperty('throttle')) {
  42962. this._autoThrottle = false;
  42963. }
  42964. if (this._autoThrottle) {
  42965. var globalOption = this.ecModel.option;
  42966. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  42967. }
  42968. };
  42969. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  42970. var rangePropMode = this._rangePropMode;
  42971. var rangeModeInOption = this.get('rangeMode');
  42972. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  42973. var percentSpecified = inputRawOption[names[0]] != null;
  42974. var valueSpecified = inputRawOption[names[1]] != null;
  42975. if (percentSpecified && !valueSpecified) {
  42976. rangePropMode[index] = 'percent';
  42977. } else if (!percentSpecified && valueSpecified) {
  42978. rangePropMode[index] = 'value';
  42979. } else if (rangeModeInOption) {
  42980. rangePropMode[index] = rangeModeInOption[index];
  42981. } else if (percentSpecified) {
  42982. // percentSpecified && valueSpecified
  42983. rangePropMode[index] = 'percent';
  42984. } // else remain its original setting.
  42985. });
  42986. };
  42987. DataZoomModel.prototype.noTarget = function () {
  42988. return this._noTarget;
  42989. };
  42990. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  42991. var firstAxisModel;
  42992. this.eachTargetAxis(function (axisDim, axisIndex) {
  42993. if (firstAxisModel == null) {
  42994. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  42995. }
  42996. }, this);
  42997. return firstAxisModel;
  42998. };
  42999. /**
  43000. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  43001. */
  43002. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  43003. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  43004. each(axisInfo.indexList, function (axisIndex) {
  43005. callback.call(context, axisDim, axisIndex);
  43006. });
  43007. });
  43008. };
  43009. /**
  43010. * @return If not found, return null/undefined.
  43011. */
  43012. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  43013. var axisModel = this.getAxisModel(axisDim, axisIndex);
  43014. if (axisModel) {
  43015. return axisModel.__dzAxisProxy;
  43016. }
  43017. };
  43018. /**
  43019. * @return If not found, return null/undefined.
  43020. */
  43021. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  43022. if ("development" !== 'production') {
  43023. assert(axisDim && axisIndex != null);
  43024. }
  43025. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  43026. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  43027. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  43028. }
  43029. };
  43030. /**
  43031. * If not specified, set to undefined.
  43032. */
  43033. DataZoomModel.prototype.setRawRange = function (opt) {
  43034. var thisOption = this.option;
  43035. var settledOption = this.settledOption;
  43036. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  43037. // Consider the pair <start, startValue>:
  43038. // If one has value and the other one is `null/undefined`, we both set them
  43039. // to `settledOption`. This strategy enables the feature to clear the original
  43040. // value in `settledOption` to `null/undefined`.
  43041. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  43042. // and keep `settledOption` with the original value. This strategy enables users to
  43043. // only set <end or endValue> but not set <start or startValue> when calling
  43044. // `dispatchAction`.
  43045. // The pair <end, endValue> is treated in the same way.
  43046. if (opt[names[0]] != null || opt[names[1]] != null) {
  43047. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  43048. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  43049. }
  43050. }, this);
  43051. this._updateRangeUse(opt);
  43052. };
  43053. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  43054. var option = this.option;
  43055. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  43056. option[name] = opt[name];
  43057. });
  43058. };
  43059. DataZoomModel.prototype.getPercentRange = function () {
  43060. var axisProxy = this.findRepresentativeAxisProxy();
  43061. if (axisProxy) {
  43062. return axisProxy.getDataPercentWindow();
  43063. }
  43064. };
  43065. /**
  43066. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  43067. *
  43068. * @return [startValue, endValue] value can only be '-' or finite number.
  43069. */
  43070. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  43071. if (axisDim == null && axisIndex == null) {
  43072. var axisProxy = this.findRepresentativeAxisProxy();
  43073. if (axisProxy) {
  43074. return axisProxy.getDataValueWindow();
  43075. }
  43076. } else {
  43077. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  43078. }
  43079. };
  43080. /**
  43081. * @param axisModel If axisModel given, find axisProxy
  43082. * corresponding to the axisModel
  43083. */
  43084. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  43085. if (axisModel) {
  43086. return axisModel.__dzAxisProxy;
  43087. } // Find the first hosted axisProxy
  43088. var firstProxy;
  43089. var axisDimList = this._targetAxisInfoMap.keys();
  43090. for (var i = 0; i < axisDimList.length; i++) {
  43091. var axisDim = axisDimList[i];
  43092. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  43093. for (var j = 0; j < axisInfo.indexList.length; j++) {
  43094. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  43095. if (proxy.hostedBy(this)) {
  43096. return proxy;
  43097. }
  43098. if (!firstProxy) {
  43099. firstProxy = proxy;
  43100. }
  43101. }
  43102. } // If no hosted proxy found, still need to return a proxy.
  43103. // This case always happens in toolbox dataZoom, where axes are all hosted by
  43104. // other dataZooms.
  43105. return firstProxy;
  43106. };
  43107. DataZoomModel.prototype.getRangePropMode = function () {
  43108. return this._rangePropMode.slice();
  43109. };
  43110. DataZoomModel.prototype.getOrient = function () {
  43111. if ("development" !== 'production') {
  43112. // Should not be called before initialized.
  43113. assert(this._orient);
  43114. }
  43115. return this._orient;
  43116. };
  43117. DataZoomModel.type = 'dataZoom';
  43118. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  43119. DataZoomModel.defaultOption = {
  43120. zlevel: 0,
  43121. z: 4,
  43122. filterMode: 'filter',
  43123. start: 0,
  43124. end: 100
  43125. };
  43126. return DataZoomModel;
  43127. }(ComponentModel);
  43128. /**
  43129. * Retrieve the those raw params from option, which will be cached separately.
  43130. * becasue they will be overwritten by normalized/calculated values in the main
  43131. * process.
  43132. */
  43133. function retrieveRawOption(option) {
  43134. var ret = {};
  43135. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  43136. option.hasOwnProperty(name) && (ret[name] = option[name]);
  43137. });
  43138. return ret;
  43139. }
  43140. var SelectDataZoomModel =
  43141. /** @class */
  43142. function (_super) {
  43143. __extends(SelectDataZoomModel, _super);
  43144. function SelectDataZoomModel() {
  43145. var _this = _super !== null && _super.apply(this, arguments) || this;
  43146. _this.type = SelectDataZoomModel.type;
  43147. return _this;
  43148. }
  43149. SelectDataZoomModel.type = 'dataZoom.select';
  43150. return SelectDataZoomModel;
  43151. }(DataZoomModel);
  43152. var DataZoomView =
  43153. /** @class */
  43154. function (_super) {
  43155. __extends(DataZoomView, _super);
  43156. function DataZoomView() {
  43157. var _this = _super !== null && _super.apply(this, arguments) || this;
  43158. _this.type = DataZoomView.type;
  43159. return _this;
  43160. }
  43161. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  43162. this.dataZoomModel = dataZoomModel;
  43163. this.ecModel = ecModel;
  43164. this.api = api;
  43165. };
  43166. DataZoomView.type = 'dataZoom';
  43167. return DataZoomView;
  43168. }(ComponentView);
  43169. var SelectDataZoomView =
  43170. /** @class */
  43171. function (_super) {
  43172. __extends(SelectDataZoomView, _super);
  43173. function SelectDataZoomView() {
  43174. var _this = _super !== null && _super.apply(this, arguments) || this;
  43175. _this.type = SelectDataZoomView.type;
  43176. return _this;
  43177. }
  43178. SelectDataZoomView.type = 'dataZoom.select';
  43179. return SelectDataZoomView;
  43180. }(DataZoomView);
  43181. /*
  43182. * Licensed to the Apache Software Foundation (ASF) under one
  43183. * or more contributor license agreements. See the NOTICE file
  43184. * distributed with this work for additional information
  43185. * regarding copyright ownership. The ASF licenses this file
  43186. * to you under the Apache License, Version 2.0 (the
  43187. * "License"); you may not use this file except in compliance
  43188. * with the License. You may obtain a copy of the License at
  43189. *
  43190. * http://www.apache.org/licenses/LICENSE-2.0
  43191. *
  43192. * Unless required by applicable law or agreed to in writing,
  43193. * software distributed under the License is distributed on an
  43194. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43195. * KIND, either express or implied. See the License for the
  43196. * specific language governing permissions and limitations
  43197. * under the License.
  43198. */
  43199. /**
  43200. * AUTO-GENERATED FILE. DO NOT MODIFY.
  43201. */
  43202. /*
  43203. * Licensed to the Apache Software Foundation (ASF) under one
  43204. * or more contributor license agreements. See the NOTICE file
  43205. * distributed with this work for additional information
  43206. * regarding copyright ownership. The ASF licenses this file
  43207. * to you under the Apache License, Version 2.0 (the
  43208. * "License"); you may not use this file except in compliance
  43209. * with the License. You may obtain a copy of the License at
  43210. *
  43211. * http://www.apache.org/licenses/LICENSE-2.0
  43212. *
  43213. * Unless required by applicable law or agreed to in writing,
  43214. * software distributed under the License is distributed on an
  43215. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43216. * KIND, either express or implied. See the License for the
  43217. * specific language governing permissions and limitations
  43218. * under the License.
  43219. */
  43220. /**
  43221. * Calculate slider move result.
  43222. * Usage:
  43223. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  43224. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  43225. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  43226. *
  43227. * @param delta Move length.
  43228. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  43229. * handleEnds will be modified in this method.
  43230. * @param extent handleEnds is restricted by extent.
  43231. * extent[0] should less or equals than extent[1].
  43232. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  43233. * @param minSpan The range of dataZoom can not be smaller than that.
  43234. * If not set, handle0 and cross handle1. If set as a non-negative
  43235. * number (including `0`), handles will push each other when reaching
  43236. * the minSpan.
  43237. * @param maxSpan The range of dataZoom can not be larger than that.
  43238. * @return The input handleEnds.
  43239. */
  43240. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  43241. delta = delta || 0;
  43242. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  43243. if (minSpan != null) {
  43244. minSpan = restrict(minSpan, [0, extentSpan]);
  43245. }
  43246. if (maxSpan != null) {
  43247. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  43248. }
  43249. if (handleIndex === 'all') {
  43250. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  43251. handleSpan = restrict(handleSpan, [0, extentSpan]);
  43252. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  43253. handleIndex = 0;
  43254. }
  43255. handleEnds[0] = restrict(handleEnds[0], extent);
  43256. handleEnds[1] = restrict(handleEnds[1], extent);
  43257. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  43258. handleEnds[handleIndex] += delta; // Restrict in extent.
  43259. var extentMinSpan = minSpan || 0;
  43260. var realExtent = extent.slice();
  43261. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  43262. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  43263. var currDistSign;
  43264. currDistSign = getSpanSign(handleEnds, handleIndex);
  43265. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  43266. // If minSpan exists, 'cross' is forbidden.
  43267. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  43268. } // Shrink span.
  43269. currDistSign = getSpanSign(handleEnds, handleIndex);
  43270. if (maxSpan != null && currDistSign.span > maxSpan) {
  43271. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  43272. }
  43273. return handleEnds;
  43274. }
  43275. function getSpanSign(handleEnds, handleIndex) {
  43276. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  43277. // is at left of handleEnds[1] for non-cross case.
  43278. return {
  43279. span: Math.abs(dist),
  43280. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  43281. };
  43282. }
  43283. function restrict(value, extend) {
  43284. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  43285. }
  43286. var each$5 = each;
  43287. var asc$1 = asc;
  43288. /**
  43289. * Operate single axis.
  43290. * One axis can only operated by one axis operator.
  43291. * Different dataZoomModels may be defined to operate the same axis.
  43292. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  43293. * So dataZoomModels share one axisProxy in that case.
  43294. */
  43295. var AxisProxy =
  43296. /** @class */
  43297. function () {
  43298. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  43299. this._dimName = dimName;
  43300. this._axisIndex = axisIndex;
  43301. this.ecModel = ecModel;
  43302. this._dataZoomModel = dataZoomModel; // /**
  43303. // * @readOnly
  43304. // * @private
  43305. // */
  43306. // this.hasSeriesStacked;
  43307. }
  43308. /**
  43309. * Whether the axisProxy is hosted by dataZoomModel.
  43310. */
  43311. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  43312. return this._dataZoomModel === dataZoomModel;
  43313. };
  43314. /**
  43315. * @return Value can only be NaN or finite value.
  43316. */
  43317. AxisProxy.prototype.getDataValueWindow = function () {
  43318. return this._valueWindow.slice();
  43319. };
  43320. /**
  43321. * @return {Array.<number>}
  43322. */
  43323. AxisProxy.prototype.getDataPercentWindow = function () {
  43324. return this._percentWindow.slice();
  43325. };
  43326. AxisProxy.prototype.getTargetSeriesModels = function () {
  43327. var seriesModels = [];
  43328. this.ecModel.eachSeries(function (seriesModel) {
  43329. if (isCoordSupported(seriesModel)) {
  43330. var axisMainType = getAxisMainType(this._dimName);
  43331. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  43332. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  43333. seriesModels.push(seriesModel);
  43334. }
  43335. }
  43336. }, this);
  43337. return seriesModels;
  43338. };
  43339. AxisProxy.prototype.getAxisModel = function () {
  43340. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  43341. };
  43342. AxisProxy.prototype.getMinMaxSpan = function () {
  43343. return clone(this._minMaxSpan);
  43344. };
  43345. /**
  43346. * Only calculate by given range and this._dataExtent, do not change anything.
  43347. */
  43348. AxisProxy.prototype.calculateDataWindow = function (opt) {
  43349. var dataExtent = this._dataExtent;
  43350. var axisModel = this.getAxisModel();
  43351. var scale = axisModel.axis.scale;
  43352. var rangePropMode = this._dataZoomModel.getRangePropMode();
  43353. var percentExtent = [0, 100];
  43354. var percentWindow = [];
  43355. var valueWindow = [];
  43356. var hasPropModeValue;
  43357. each$5(['start', 'end'], function (prop, idx) {
  43358. var boundPercent = opt[prop];
  43359. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  43360. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  43361. // but not min/max of axis, which will be calculated by data window then).
  43362. // The former one is suitable for cases that a dataZoom component controls multiple
  43363. // axes with different unit or extent, and the latter one is suitable for accurate
  43364. // zoom by pixel (e.g., in dataZoomSelect).
  43365. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  43366. // only when setOption or dispatchAction, otherwise it remains its original value.
  43367. // (Why not only record `percentProp` and always map to `valueProp`? Because
  43368. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  43369. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  43370. // data extent. All of values that are overflow the `dataExtent` will be calculated
  43371. // to percent '100%').
  43372. if (rangePropMode[idx] === 'percent') {
  43373. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  43374. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  43375. } else {
  43376. hasPropModeValue = true;
  43377. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  43378. // This calculation can not be inversed, because all of values that
  43379. // are overflow the `dataExtent` will be calculated to percent '100%'
  43380. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  43381. } // valueWindow[idx] = round(boundValue);
  43382. // percentWindow[idx] = round(boundPercent);
  43383. valueWindow[idx] = boundValue;
  43384. percentWindow[idx] = boundPercent;
  43385. });
  43386. asc$1(valueWindow);
  43387. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  43388. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  43389. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  43390. // where API is able to initialize/modify the window size even though `zoomLock`
  43391. // specified.
  43392. var spans = this._minMaxSpan;
  43393. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  43394. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  43395. var suffix = toValue ? 'Span' : 'ValueSpan';
  43396. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  43397. for (var i = 0; i < 2; i++) {
  43398. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  43399. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  43400. }
  43401. }
  43402. return {
  43403. valueWindow: valueWindow,
  43404. percentWindow: percentWindow
  43405. };
  43406. };
  43407. /**
  43408. * Notice: reset should not be called before series.restoreData() called,
  43409. * so it is recommanded to be called in "process stage" but not "model init
  43410. * stage".
  43411. */
  43412. AxisProxy.prototype.reset = function (dataZoomModel) {
  43413. if (dataZoomModel !== this._dataZoomModel) {
  43414. return;
  43415. }
  43416. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  43417. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // this.hasSeriesStacked = false;
  43418. // each(targetSeries, function (series) {
  43419. // let data = series.getData();
  43420. // let dataDim = data.mapDimension(this._dimName);
  43421. // let stackedDimension = data.getCalculationInfo('stackedDimension');
  43422. // if (stackedDimension && stackedDimension === dataDim) {
  43423. // this.hasSeriesStacked = true;
  43424. // }
  43425. // }, this);
  43426. // `calculateDataWindow` uses min/maxSpan.
  43427. this._updateMinMaxSpan();
  43428. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  43429. this._valueWindow = dataWindow.valueWindow;
  43430. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  43431. this._setAxisModel();
  43432. };
  43433. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  43434. if (dataZoomModel !== this._dataZoomModel) {
  43435. return;
  43436. }
  43437. var axisDim = this._dimName;
  43438. var seriesModels = this.getTargetSeriesModels();
  43439. var filterMode = dataZoomModel.get('filterMode');
  43440. var valueWindow = this._valueWindow;
  43441. if (filterMode === 'none') {
  43442. return;
  43443. } // FIXME
  43444. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  43445. // with NaN data, NaN will be filtered and stack will be wrong.
  43446. // So we need to force the mode to be set empty.
  43447. // In fect, it is not a big deal that do not support filterMode-'filter'
  43448. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  43449. // selection" some day, which might need "adapt to data extent on the
  43450. // otherAxis", which is disabled by filterMode-'empty'.
  43451. // But currently, stack has been fixed to based on value but not index,
  43452. // so this is not an issue any more.
  43453. // let otherAxisModel = this.getOtherAxisModel();
  43454. // if (dataZoomModel.get('$fromToolbox')
  43455. // && otherAxisModel
  43456. // && otherAxisModel.hasSeriesStacked
  43457. // ) {
  43458. // filterMode = 'empty';
  43459. // }
  43460. // TODO
  43461. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  43462. each$5(seriesModels, function (seriesModel) {
  43463. var seriesData = seriesModel.getData();
  43464. var dataDims = seriesData.mapDimensionsAll(axisDim);
  43465. if (!dataDims.length) {
  43466. return;
  43467. }
  43468. if (filterMode === 'weakFilter') {
  43469. seriesData.filterSelf(function (dataIndex) {
  43470. var leftOut;
  43471. var rightOut;
  43472. var hasValue;
  43473. for (var i = 0; i < dataDims.length; i++) {
  43474. var value = seriesData.get(dataDims[i], dataIndex);
  43475. var thisHasValue = !isNaN(value);
  43476. var thisLeftOut = value < valueWindow[0];
  43477. var thisRightOut = value > valueWindow[1];
  43478. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  43479. return true;
  43480. }
  43481. thisHasValue && (hasValue = true);
  43482. thisLeftOut && (leftOut = true);
  43483. thisRightOut && (rightOut = true);
  43484. } // If both left out and right out, do not filter.
  43485. return hasValue && leftOut && rightOut;
  43486. });
  43487. } else {
  43488. each$5(dataDims, function (dim) {
  43489. if (filterMode === 'empty') {
  43490. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  43491. return !isInWindow(value) ? NaN : value;
  43492. }));
  43493. } else {
  43494. var range = {};
  43495. range[dim] = valueWindow; // console.time('select');
  43496. seriesData.selectRange(range); // console.timeEnd('select');
  43497. }
  43498. });
  43499. }
  43500. each$5(dataDims, function (dim) {
  43501. seriesData.setApproximateExtent(valueWindow, dim);
  43502. });
  43503. });
  43504. function isInWindow(value) {
  43505. return value >= valueWindow[0] && value <= valueWindow[1];
  43506. }
  43507. };
  43508. AxisProxy.prototype._updateMinMaxSpan = function () {
  43509. var minMaxSpan = this._minMaxSpan = {};
  43510. var dataZoomModel = this._dataZoomModel;
  43511. var dataExtent = this._dataExtent;
  43512. each$5(['min', 'max'], function (minMax) {
  43513. var percentSpan = dataZoomModel.get(minMax + 'Span');
  43514. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  43515. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  43516. if (valueSpan != null) {
  43517. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  43518. } else if (percentSpan != null) {
  43519. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  43520. }
  43521. minMaxSpan[minMax + 'Span'] = percentSpan;
  43522. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  43523. }, this);
  43524. };
  43525. AxisProxy.prototype._setAxisModel = function () {
  43526. var axisModel = this.getAxisModel();
  43527. var percentWindow = this._percentWindow;
  43528. var valueWindow = this._valueWindow;
  43529. if (!percentWindow) {
  43530. return;
  43531. } // [0, 500]: arbitrary value, guess axis extent.
  43532. var precision = getPixelPrecision(valueWindow, [0, 500]);
  43533. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  43534. // by series data, which may be a little different from the extent calculated by
  43535. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  43536. // little when zooming. So it will not be fixed until some users require it strongly.
  43537. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  43538. if (percentWindow[0] !== 0) {
  43539. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  43540. }
  43541. if (percentWindow[1] !== 100) {
  43542. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  43543. }
  43544. rawExtentInfo.freeze();
  43545. };
  43546. return AxisProxy;
  43547. }();
  43548. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  43549. var dataExtent = [Infinity, -Infinity];
  43550. each$5(seriesModels, function (seriesModel) {
  43551. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  43552. }); // It is important to get "consistent" extent when more then one axes is
  43553. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  43554. // when zooming. But it is difficult to know what is "consistent", considering
  43555. // axes have different type or even different meanings (For example, two
  43556. // time axes are used to compare data of the same date in different years).
  43557. // So basically dataZoom just obtains extent by series.data (in category axis
  43558. // extent can be obtained from axis.data).
  43559. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  43560. // consistent.
  43561. var axisModel = axisProxy.getAxisModel();
  43562. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  43563. return [rawExtentResult.min, rawExtentResult.max];
  43564. }
  43565. var dataZoomProcessor = {
  43566. // `dataZoomProcessor` will only be performed in needed series. Consider if
  43567. // there is a line series and a pie series, it is better not to update the
  43568. // line series if only pie series is needed to be updated.
  43569. getTargetSeries: function (ecModel) {
  43570. function eachAxisModel(cb) {
  43571. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  43572. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  43573. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  43574. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  43575. });
  43576. });
  43577. } // FIXME: it brings side-effect to `getTargetSeries`.
  43578. // Prepare axis proxies.
  43579. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  43580. // dispose all last axis proxy, in case that some axis are deleted.
  43581. axisModel.__dzAxisProxy = null;
  43582. });
  43583. var proxyList = [];
  43584. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  43585. // Different dataZooms may constrol the same axis. In that case,
  43586. // an axisProxy serves both of them.
  43587. if (!axisModel.__dzAxisProxy) {
  43588. // Use the first dataZoomModel as the main model of axisProxy.
  43589. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  43590. proxyList.push(axisModel.__dzAxisProxy);
  43591. }
  43592. });
  43593. var seriesModelMap = createHashMap();
  43594. each(proxyList, function (axisProxy) {
  43595. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  43596. seriesModelMap.set(seriesModel.uid, seriesModel);
  43597. });
  43598. });
  43599. return seriesModelMap;
  43600. },
  43601. // Consider appendData, where filter should be performed. Because data process is
  43602. // in block mode currently, it is not need to worry about that the overallProgress
  43603. // execute every frame.
  43604. overallReset: function (ecModel, api) {
  43605. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  43606. // We calculate window and reset axis here but not in model
  43607. // init stage and not after action dispatch handler, because
  43608. // reset should be called after seriesData.restoreData.
  43609. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  43610. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  43611. }); // Caution: data zoom filtering is order sensitive when using
  43612. // percent range and no min/max/scale set on axis.
  43613. // For example, we have dataZoom definition:
  43614. // [
  43615. // {xAxisIndex: 0, start: 30, end: 70},
  43616. // {yAxisIndex: 0, start: 20, end: 80}
  43617. // ]
  43618. // In this case, [20, 80] of y-dataZoom should be based on data
  43619. // that have filtered by x-dataZoom using range of [30, 70],
  43620. // but should not be based on full raw data. Thus sliding
  43621. // x-dataZoom will change both ranges of xAxis and yAxis,
  43622. // while sliding y-dataZoom will only change the range of yAxis.
  43623. // So we should filter x-axis after reset x-axis immediately,
  43624. // and then reset y-axis and filter y-axis.
  43625. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  43626. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  43627. });
  43628. });
  43629. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  43630. // Fullfill all of the range props so that user
  43631. // is able to get them from chart.getOption().
  43632. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  43633. if (axisProxy) {
  43634. var percentRange = axisProxy.getDataPercentWindow();
  43635. var valueRange = axisProxy.getDataValueWindow();
  43636. dataZoomModel.setCalculatedRange({
  43637. start: percentRange[0],
  43638. end: percentRange[1],
  43639. startValue: valueRange[0],
  43640. endValue: valueRange[1]
  43641. });
  43642. }
  43643. });
  43644. }
  43645. };
  43646. function installDataZoomAction(registers) {
  43647. registers.registerAction('dataZoom', function (payload, ecModel) {
  43648. var effectedModels = findEffectedDataZooms(ecModel, payload);
  43649. each(effectedModels, function (dataZoomModel) {
  43650. dataZoomModel.setRawRange({
  43651. start: payload.start,
  43652. end: payload.end,
  43653. startValue: payload.startValue,
  43654. endValue: payload.endValue
  43655. });
  43656. });
  43657. });
  43658. }
  43659. var installed = false;
  43660. function installCommon(registers) {
  43661. if (installed) {
  43662. return;
  43663. }
  43664. installed = true;
  43665. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  43666. installDataZoomAction(registers);
  43667. registers.registerSubTypeDefaulter('dataZoom', function () {
  43668. // Default 'slider' when no type specified.
  43669. return 'slider';
  43670. });
  43671. }
  43672. function install$a(registers) {
  43673. registers.registerComponentModel(SelectDataZoomModel);
  43674. registers.registerComponentView(SelectDataZoomView);
  43675. installCommon(registers);
  43676. }
  43677. /*
  43678. * Licensed to the Apache Software Foundation (ASF) under one
  43679. * or more contributor license agreements. See the NOTICE file
  43680. * distributed with this work for additional information
  43681. * regarding copyright ownership. The ASF licenses this file
  43682. * to you under the Apache License, Version 2.0 (the
  43683. * "License"); you may not use this file except in compliance
  43684. * with the License. You may obtain a copy of the License at
  43685. *
  43686. * http://www.apache.org/licenses/LICENSE-2.0
  43687. *
  43688. * Unless required by applicable law or agreed to in writing,
  43689. * software distributed under the License is distributed on an
  43690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43691. * KIND, either express or implied. See the License for the
  43692. * specific language governing permissions and limitations
  43693. * under the License.
  43694. */
  43695. /**
  43696. * AUTO-GENERATED FILE. DO NOT MODIFY.
  43697. */
  43698. var ToolboxFeature =
  43699. /** @class */
  43700. function () {
  43701. function ToolboxFeature() {}
  43702. return ToolboxFeature;
  43703. }();
  43704. var features = {};
  43705. function registerFeature(name, ctor) {
  43706. features[name] = ctor;
  43707. }
  43708. function getFeature(name) {
  43709. return features[name];
  43710. }
  43711. var ToolboxModel =
  43712. /** @class */
  43713. function (_super) {
  43714. __extends(ToolboxModel, _super);
  43715. function ToolboxModel() {
  43716. var _this = _super !== null && _super.apply(this, arguments) || this;
  43717. _this.type = ToolboxModel.type;
  43718. return _this;
  43719. }
  43720. ToolboxModel.prototype.optionUpdated = function () {
  43721. _super.prototype.optionUpdated.apply(this, arguments);
  43722. var ecModel = this.ecModel;
  43723. each(this.option.feature, function (featureOpt, featureName) {
  43724. var Feature = getFeature(featureName);
  43725. if (Feature) {
  43726. if (Feature.getDefaultOption) {
  43727. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  43728. }
  43729. merge(featureOpt, Feature.defaultOption);
  43730. }
  43731. });
  43732. };
  43733. ToolboxModel.type = 'toolbox';
  43734. ToolboxModel.layoutMode = {
  43735. type: 'box',
  43736. ignoreSize: true
  43737. };
  43738. ToolboxModel.defaultOption = {
  43739. show: true,
  43740. z: 6,
  43741. zlevel: 0,
  43742. orient: 'horizontal',
  43743. left: 'right',
  43744. top: 'top',
  43745. // right
  43746. // bottom
  43747. backgroundColor: 'transparent',
  43748. borderColor: '#ccc',
  43749. borderRadius: 0,
  43750. borderWidth: 0,
  43751. padding: 5,
  43752. itemSize: 15,
  43753. itemGap: 8,
  43754. showTitle: true,
  43755. iconStyle: {
  43756. borderColor: '#666',
  43757. color: 'none'
  43758. },
  43759. emphasis: {
  43760. iconStyle: {
  43761. borderColor: '#3E98C5'
  43762. }
  43763. },
  43764. // textStyle: {},
  43765. // feature
  43766. tooltip: {
  43767. show: false
  43768. }
  43769. };
  43770. return ToolboxModel;
  43771. }(ComponentModel);
  43772. /**
  43773. * Layout list like component.
  43774. * It will box layout each items in group of component and then position the whole group in the viewport
  43775. * @param {module:zrender/group/Group} group
  43776. * @param {module:echarts/model/Component} componentModel
  43777. * @param {module:echarts/ExtensionAPI}
  43778. */
  43779. function layout$2(group, componentModel, api) {
  43780. var boxLayoutParams = componentModel.getBoxLayoutParams();
  43781. var padding = componentModel.get('padding');
  43782. var viewportSize = {
  43783. width: api.getWidth(),
  43784. height: api.getHeight()
  43785. };
  43786. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  43787. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  43788. positionElement(group, boxLayoutParams, viewportSize, padding);
  43789. }
  43790. function makeBackground(rect, componentModel) {
  43791. var padding = normalizeCssArray$1(componentModel.get('padding'));
  43792. var style = componentModel.getItemStyle(['color', 'opacity']);
  43793. style.fill = componentModel.get('backgroundColor');
  43794. rect = new Rect({
  43795. shape: {
  43796. x: rect.x - padding[3],
  43797. y: rect.y - padding[0],
  43798. width: rect.width + padding[1] + padding[3],
  43799. height: rect.height + padding[0] + padding[2],
  43800. r: componentModel.get('borderRadius')
  43801. },
  43802. style: style,
  43803. silent: true,
  43804. z2: -1
  43805. }); // FIXME
  43806. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  43807. // and background rect when setting like `left: 0`, `top: 0`.
  43808. // graphic.subPixelOptimizeRect(rect);
  43809. return rect;
  43810. }
  43811. var ToolboxView =
  43812. /** @class */
  43813. function (_super) {
  43814. __extends(ToolboxView, _super);
  43815. function ToolboxView() {
  43816. return _super !== null && _super.apply(this, arguments) || this;
  43817. }
  43818. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  43819. var group = this.group;
  43820. group.removeAll();
  43821. if (!toolboxModel.get('show')) {
  43822. return;
  43823. }
  43824. var itemSize = +toolboxModel.get('itemSize');
  43825. var featureOpts = toolboxModel.get('feature') || {};
  43826. var features = this._features || (this._features = {});
  43827. var featureNames = [];
  43828. each(featureOpts, function (opt, name) {
  43829. featureNames.push(name);
  43830. });
  43831. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  43832. this._featureNames = featureNames;
  43833. function processFeature(newIndex, oldIndex) {
  43834. var featureName = featureNames[newIndex];
  43835. var oldName = featureNames[oldIndex];
  43836. var featureOpt = featureOpts[featureName];
  43837. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  43838. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  43839. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  43840. featureOpt.title = payload.newTitle;
  43841. }
  43842. if (featureName && !oldName) {
  43843. // Create
  43844. if (isUserFeatureName(featureName)) {
  43845. feature = {
  43846. onclick: featureModel.option.onclick,
  43847. featureName: featureName
  43848. };
  43849. } else {
  43850. var Feature = getFeature(featureName);
  43851. if (!Feature) {
  43852. return;
  43853. }
  43854. feature = new Feature();
  43855. }
  43856. features[featureName] = feature;
  43857. } else {
  43858. feature = features[oldName]; // If feature does not exsit.
  43859. if (!feature) {
  43860. return;
  43861. }
  43862. }
  43863. feature.uid = getUID('toolbox-feature');
  43864. feature.model = featureModel;
  43865. feature.ecModel = ecModel;
  43866. feature.api = api;
  43867. if (feature instanceof ToolboxFeature) {
  43868. if (!featureName && oldName) {
  43869. feature.dispose && feature.dispose(ecModel, api);
  43870. return;
  43871. }
  43872. if (!featureModel.get('show') || feature.unusable) {
  43873. feature.remove && feature.remove(ecModel, api);
  43874. return;
  43875. }
  43876. }
  43877. createIconPaths(featureModel, feature, featureName);
  43878. featureModel.setIconStatus = function (iconName, status) {
  43879. var option = this.option;
  43880. var iconPaths = this.iconPaths;
  43881. option.iconStatus = option.iconStatus || {};
  43882. option.iconStatus[iconName] = status;
  43883. if (iconPaths[iconName]) {
  43884. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  43885. }
  43886. };
  43887. if (feature instanceof ToolboxFeature) {
  43888. if (feature.render) {
  43889. feature.render(featureModel, ecModel, api, payload);
  43890. }
  43891. }
  43892. }
  43893. function createIconPaths(featureModel, feature, featureName) {
  43894. var iconStyleModel = featureModel.getModel('iconStyle');
  43895. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has mutiple icon. they are orginaized as
  43896. // {
  43897. // icon: {
  43898. // foo: '',
  43899. // bar: ''
  43900. // },
  43901. // title: {
  43902. // foo: '',
  43903. // bar: ''
  43904. // }
  43905. // }
  43906. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  43907. var titles = featureModel.get('title') || {};
  43908. var iconsMap;
  43909. var titlesMap;
  43910. if (typeof icons === 'string') {
  43911. iconsMap = {};
  43912. iconsMap[featureName] = icons;
  43913. } else {
  43914. iconsMap = icons;
  43915. }
  43916. if (typeof titles === 'string') {
  43917. titlesMap = {};
  43918. titlesMap[featureName] = titles;
  43919. } else {
  43920. titlesMap = titles;
  43921. }
  43922. var iconPaths = featureModel.iconPaths = {};
  43923. each(iconsMap, function (iconStr, iconName) {
  43924. var path = createIcon(iconStr, {}, {
  43925. x: -itemSize / 2,
  43926. y: -itemSize / 2,
  43927. width: itemSize,
  43928. height: itemSize
  43929. }); // TODO handling image
  43930. path.setStyle(iconStyleModel.getItemStyle());
  43931. var pathEmphasisState = path.ensureState('emphasis');
  43932. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  43933. var textContent = new ZRText({
  43934. style: {
  43935. text: titlesMap[iconName],
  43936. align: iconStyleEmphasisModel.get('textAlign'),
  43937. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  43938. padding: iconStyleEmphasisModel.get('textPadding'),
  43939. fill: null
  43940. },
  43941. ignore: true
  43942. });
  43943. path.setTextContent(textContent);
  43944. var tooltipModel = toolboxModel.getModel('tooltip');
  43945. if (tooltipModel && tooltipModel.get('show')) {
  43946. path.tooltip = extend({
  43947. content: titlesMap[iconName],
  43948. formatter: tooltipModel.get('formatter', true) || function () {
  43949. return titlesMap[iconName];
  43950. },
  43951. formatterParams: {
  43952. componentType: 'toolbox',
  43953. name: iconName,
  43954. title: titlesMap[iconName],
  43955. $vars: ['name', 'title']
  43956. },
  43957. position: tooltipModel.get('position', true) || 'bottom'
  43958. }, tooltipModel.option);
  43959. } // graphic.enableHoverEmphasis(path);
  43960. path.__title = titlesMap[iconName];
  43961. path.on('mouseover', function () {
  43962. // Should not reuse above hoverStyle, which might be modified.
  43963. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  43964. var defaultTextPosition = toolboxModel.get('orient') === 'vertical' ? toolboxModel.get('right') == null ? 'right' : 'left' : toolboxModel.get('bottom') == null ? 'bottom' : 'top';
  43965. textContent.setStyle({
  43966. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  43967. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  43968. });
  43969. path.setTextConfig({
  43970. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  43971. });
  43972. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  43973. // There are flags managed by the echarts.
  43974. enterEmphasis(this);
  43975. }).on('mouseout', function () {
  43976. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  43977. leaveEmphasis(this);
  43978. }
  43979. textContent.hide();
  43980. });
  43981. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  43982. group.add(path);
  43983. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  43984. iconPaths[iconName] = path;
  43985. });
  43986. }
  43987. layout$2(group, toolboxModel, api); // Render background after group is layout
  43988. // FIXME
  43989. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  43990. group.eachChild(function (icon) {
  43991. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  43992. // TODO simplify code?
  43993. var emphasisState = icon.ensureState('emphasis');
  43994. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  43995. var textContent = icon.getTextContent();
  43996. var emphasisTextState = textContent && textContent.states.emphasis; // May be background element
  43997. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  43998. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  43999. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  44000. var offsetX = icon.x + group.x;
  44001. var offsetY = icon.y + group.y + itemSize;
  44002. var needPutOnTop = false;
  44003. if (offsetY + rect.height > api.getHeight()) {
  44004. emphasisTextConfig.position = 'top';
  44005. needPutOnTop = true;
  44006. }
  44007. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 8;
  44008. if (offsetX + rect.width / 2 > api.getWidth()) {
  44009. emphasisTextConfig.position = ['100%', topOffset];
  44010. emphasisTextStyle.align = 'right';
  44011. } else if (offsetX - rect.width / 2 < 0) {
  44012. emphasisTextConfig.position = [0, topOffset];
  44013. emphasisTextStyle.align = 'left';
  44014. }
  44015. }
  44016. });
  44017. };
  44018. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  44019. each(this._features, function (feature) {
  44020. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  44021. });
  44022. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  44023. // zrUtil.each(this._features, function (feature) {
  44024. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  44025. // });
  44026. // },
  44027. ToolboxView.prototype.remove = function (ecModel, api) {
  44028. each(this._features, function (feature) {
  44029. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  44030. });
  44031. this.group.removeAll();
  44032. };
  44033. ToolboxView.prototype.dispose = function (ecModel, api) {
  44034. each(this._features, function (feature) {
  44035. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  44036. });
  44037. };
  44038. ToolboxView.type = 'toolbox';
  44039. return ToolboxView;
  44040. }(ComponentView);
  44041. function isUserFeatureName(featureName) {
  44042. return featureName.indexOf('my') === 0;
  44043. }
  44044. var SaveAsImage =
  44045. /** @class */
  44046. function (_super) {
  44047. __extends(SaveAsImage, _super);
  44048. function SaveAsImage() {
  44049. return _super !== null && _super.apply(this, arguments) || this;
  44050. }
  44051. SaveAsImage.prototype.onclick = function (ecModel, api) {
  44052. var model = this.model;
  44053. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  44054. var isSvg = api.getZr().painter.getType() === 'svg';
  44055. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  44056. var url = api.getConnectedDataURL({
  44057. type: type,
  44058. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  44059. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  44060. excludeComponents: model.get('excludeComponents'),
  44061. pixelRatio: model.get('pixelRatio')
  44062. }); // Chrome, Firefox, New Edge
  44063. if (typeof MouseEvent === 'function' && (env.browser.newEdge || !env.browser.ie && !env.browser.edge)) {
  44064. var $a = document.createElement('a');
  44065. $a.download = title + '.' + type;
  44066. $a.target = '_blank';
  44067. $a.href = url;
  44068. var evt = new MouseEvent('click', {
  44069. // some micro front-end framework, window maybe is a Proxy
  44070. view: document.defaultView,
  44071. bubbles: true,
  44072. cancelable: false
  44073. });
  44074. $a.dispatchEvent(evt);
  44075. } // IE or old Edge
  44076. else {
  44077. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  44078. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  44079. var base64Encoded = parts[0].indexOf('base64') > -1;
  44080. var bstr = isSvg // should decode the svg data uri first
  44081. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  44082. // otherwise, like `svg` data uri exported by zrender,
  44083. // there will be an error, for it's not encoded with base64.
  44084. // (just a url-encoded string through `encodeURIComponent`)
  44085. base64Encoded && (bstr = atob(bstr));
  44086. var filename = title + '.' + type;
  44087. if (window.navigator.msSaveOrOpenBlob) {
  44088. var n = bstr.length;
  44089. var u8arr = new Uint8Array(n);
  44090. while (n--) {
  44091. u8arr[n] = bstr.charCodeAt(n);
  44092. }
  44093. var blob = new Blob([u8arr]);
  44094. window.navigator.msSaveOrOpenBlob(blob, filename);
  44095. } else {
  44096. var frame = document.createElement('iframe');
  44097. document.body.appendChild(frame);
  44098. var cw = frame.contentWindow;
  44099. var doc = cw.document;
  44100. doc.open('image/svg+xml', 'replace');
  44101. doc.write(bstr);
  44102. doc.close();
  44103. cw.focus();
  44104. doc.execCommand('SaveAs', true, filename);
  44105. document.body.removeChild(frame);
  44106. }
  44107. } else {
  44108. var lang = model.get('lang');
  44109. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  44110. var tab = window.open();
  44111. tab.document.write(html);
  44112. tab.document.title = title;
  44113. }
  44114. }
  44115. };
  44116. SaveAsImage.getDefaultOption = function (ecModel) {
  44117. var defaultOption = {
  44118. show: true,
  44119. 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',
  44120. title: ecModel.getLocale(['toolbox', 'saveAsImage', 'title']),
  44121. type: 'png',
  44122. // Default use option.backgroundColor
  44123. // backgroundColor: '#fff',
  44124. connectedBackgroundColor: '#fff',
  44125. name: '',
  44126. excludeComponents: ['toolbox'],
  44127. // use current pixel ratio of device by default
  44128. // pixelRatio: 1,
  44129. lang: ecModel.getLocale(['toolbox', 'saveAsImage', 'lang'])
  44130. };
  44131. return defaultOption;
  44132. };
  44133. return SaveAsImage;
  44134. }(ToolboxFeature);
  44135. SaveAsImage.prototype.unusable = !env.canvasSupported;
  44136. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  44137. var radioTypes = [['line', 'bar'], ['stack']];
  44138. var MagicType =
  44139. /** @class */
  44140. function (_super) {
  44141. __extends(MagicType, _super);
  44142. function MagicType() {
  44143. return _super !== null && _super.apply(this, arguments) || this;
  44144. }
  44145. MagicType.prototype.getIcons = function () {
  44146. var model = this.model;
  44147. var availableIcons = model.get('icon');
  44148. var icons = {};
  44149. each(model.get('type'), function (type) {
  44150. if (availableIcons[type]) {
  44151. icons[type] = availableIcons[type];
  44152. }
  44153. });
  44154. return icons;
  44155. };
  44156. MagicType.getDefaultOption = function (ecModel) {
  44157. var defaultOption = {
  44158. show: true,
  44159. type: [],
  44160. // Icon group
  44161. icon: {
  44162. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  44163. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  44164. // eslint-disable-next-line
  44165. 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
  44166. },
  44167. // `line`, `bar`, `stack`, `tiled`
  44168. title: ecModel.getLocale(['toolbox', 'magicType', 'title']),
  44169. option: {},
  44170. seriesIndex: {}
  44171. };
  44172. return defaultOption;
  44173. };
  44174. MagicType.prototype.onclick = function (ecModel, api, type) {
  44175. var model = this.model;
  44176. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  44177. if (!seriesOptGenreator[type]) {
  44178. return;
  44179. }
  44180. var newOption = {
  44181. series: []
  44182. };
  44183. var generateNewSeriesTypes = function (seriesModel) {
  44184. var seriesType = seriesModel.subType;
  44185. var seriesId = seriesModel.id;
  44186. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  44187. if (newSeriesOpt) {
  44188. // PENDING If merge original option?
  44189. defaults(newSeriesOpt, seriesModel.option);
  44190. newOption.series.push(newSeriesOpt);
  44191. } // Modify boundaryGap
  44192. var coordSys = seriesModel.coordinateSystem;
  44193. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  44194. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  44195. if (categoryAxis) {
  44196. var axisDim = categoryAxis.dim;
  44197. var axisType = axisDim + 'Axis';
  44198. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  44199. var axisIndex = axisModel.componentIndex;
  44200. newOption[axisType] = newOption[axisType] || [];
  44201. for (var i = 0; i <= axisIndex; i++) {
  44202. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  44203. }
  44204. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  44205. }
  44206. }
  44207. };
  44208. each(radioTypes, function (radio) {
  44209. if (indexOf(radio, type) >= 0) {
  44210. each(radio, function (item) {
  44211. model.setIconStatus(item, 'normal');
  44212. });
  44213. }
  44214. });
  44215. model.setIconStatus(type, 'emphasis');
  44216. ecModel.eachComponent({
  44217. mainType: 'series',
  44218. query: seriesIndex == null ? null : {
  44219. seriesIndex: seriesIndex
  44220. }
  44221. }, generateNewSeriesTypes);
  44222. var newTitle; // Change title of stack
  44223. if (type === 'stack') {
  44224. // use titles in model instead of ecModel
  44225. // as stack and tiled appears in pair, just flip them
  44226. // no need of checking stack state
  44227. newTitle = merge({
  44228. stack: model.option.title.tiled,
  44229. tiled: model.option.title.stack
  44230. }, model.option.title);
  44231. }
  44232. api.dispatchAction({
  44233. type: 'changeMagicType',
  44234. currentType: type,
  44235. newOption: newOption,
  44236. newTitle: newTitle,
  44237. featureName: 'magicType'
  44238. });
  44239. };
  44240. return MagicType;
  44241. }(ToolboxFeature);
  44242. var seriesOptGenreator = {
  44243. 'line': function (seriesType, seriesId, seriesModel, model) {
  44244. if (seriesType === 'bar') {
  44245. return merge({
  44246. id: seriesId,
  44247. type: 'line',
  44248. // Preserve data related option
  44249. data: seriesModel.get('data'),
  44250. stack: seriesModel.get('stack'),
  44251. markPoint: seriesModel.get('markPoint'),
  44252. markLine: seriesModel.get('markLine')
  44253. }, model.get(['option', 'line']) || {}, true);
  44254. }
  44255. },
  44256. 'bar': function (seriesType, seriesId, seriesModel, model) {
  44257. if (seriesType === 'line') {
  44258. return merge({
  44259. id: seriesId,
  44260. type: 'bar',
  44261. // Preserve data related option
  44262. data: seriesModel.get('data'),
  44263. stack: seriesModel.get('stack'),
  44264. markPoint: seriesModel.get('markPoint'),
  44265. markLine: seriesModel.get('markLine')
  44266. }, model.get(['option', 'bar']) || {}, true);
  44267. }
  44268. },
  44269. 'stack': function (seriesType, seriesId, seriesModel, model) {
  44270. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  44271. if (seriesType === 'line' || seriesType === 'bar') {
  44272. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  44273. return merge({
  44274. id: seriesId,
  44275. stack: isStack ? '' : INNER_STACK_KEYWORD
  44276. }, model.get(['option', 'stack']) || {}, true);
  44277. }
  44278. }
  44279. }; // TODO: SELF REGISTERED.
  44280. registerAction({
  44281. type: 'changeMagicType',
  44282. event: 'magicTypeChanged',
  44283. update: 'prepareAndUpdate'
  44284. }, function (payload, ecModel) {
  44285. ecModel.mergeOption(payload.newOption);
  44286. });
  44287. var BLOCK_SPLITER = new Array(60).join('-');
  44288. var ITEM_SPLITER = '\t';
  44289. /**
  44290. * Group series into two types
  44291. * 1. on category axis, like line, bar
  44292. * 2. others, like scatter, pie
  44293. */
  44294. function groupSeries(ecModel) {
  44295. var seriesGroupByCategoryAxis = {};
  44296. var otherSeries = [];
  44297. var meta = [];
  44298. ecModel.eachRawSeries(function (seriesModel) {
  44299. var coordSys = seriesModel.coordinateSystem;
  44300. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  44301. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  44302. var baseAxis = coordSys.getBaseAxis();
  44303. if (baseAxis.type === 'category') {
  44304. var key = baseAxis.dim + '_' + baseAxis.index;
  44305. if (!seriesGroupByCategoryAxis[key]) {
  44306. seriesGroupByCategoryAxis[key] = {
  44307. categoryAxis: baseAxis,
  44308. valueAxis: coordSys.getOtherAxis(baseAxis),
  44309. series: []
  44310. };
  44311. meta.push({
  44312. axisDim: baseAxis.dim,
  44313. axisIndex: baseAxis.index
  44314. });
  44315. }
  44316. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  44317. } else {
  44318. otherSeries.push(seriesModel);
  44319. }
  44320. } else {
  44321. otherSeries.push(seriesModel);
  44322. }
  44323. });
  44324. return {
  44325. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  44326. other: otherSeries,
  44327. meta: meta
  44328. };
  44329. }
  44330. /**
  44331. * Assemble content of series on cateogory axis
  44332. * @inner
  44333. */
  44334. function assembleSeriesWithCategoryAxis(groups) {
  44335. var tables = [];
  44336. each(groups, function (group, key) {
  44337. var categoryAxis = group.categoryAxis;
  44338. var valueAxis = group.valueAxis;
  44339. var valueAxisDim = valueAxis.dim;
  44340. var headers = [' '].concat(map(group.series, function (series) {
  44341. return series.name;
  44342. })); // @ts-ignore TODO Polar
  44343. var columns = [categoryAxis.model.getCategories()];
  44344. each(group.series, function (series) {
  44345. var rawData = series.getRawData();
  44346. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  44347. return val;
  44348. }));
  44349. }); // Assemble table content
  44350. var lines = [headers.join(ITEM_SPLITER)];
  44351. for (var i = 0; i < columns[0].length; i++) {
  44352. var items = [];
  44353. for (var j = 0; j < columns.length; j++) {
  44354. items.push(columns[j][i]);
  44355. }
  44356. lines.push(items.join(ITEM_SPLITER));
  44357. }
  44358. tables.push(lines.join('\n'));
  44359. });
  44360. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  44361. }
  44362. /**
  44363. * Assemble content of other series
  44364. */
  44365. function assembleOtherSeries(series) {
  44366. return map(series, function (series) {
  44367. var data = series.getRawData();
  44368. var lines = [series.name];
  44369. var vals = [];
  44370. data.each(data.dimensions, function () {
  44371. var argLen = arguments.length;
  44372. var dataIndex = arguments[argLen - 1];
  44373. var name = data.getName(dataIndex);
  44374. for (var i = 0; i < argLen - 1; i++) {
  44375. vals[i] = arguments[i];
  44376. }
  44377. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  44378. });
  44379. return lines.join('\n');
  44380. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  44381. }
  44382. function getContentFromModel(ecModel) {
  44383. var result = groupSeries(ecModel);
  44384. return {
  44385. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  44386. return !!str.replace(/[\n\t\s]/g, '');
  44387. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  44388. meta: result.meta
  44389. };
  44390. }
  44391. function trim$1(str) {
  44392. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  44393. }
  44394. /**
  44395. * If a block is tsv format
  44396. */
  44397. function isTSVFormat(block) {
  44398. // Simple method to find out if a block is tsv format
  44399. var firstLine = block.slice(0, block.indexOf('\n'));
  44400. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  44401. return true;
  44402. }
  44403. }
  44404. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  44405. /**
  44406. * @param {string} tsv
  44407. * @return {Object}
  44408. */
  44409. function parseTSVContents(tsv) {
  44410. var tsvLines = tsv.split(/\n+/g);
  44411. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  44412. var categories = [];
  44413. var series = map(headers, function (header) {
  44414. return {
  44415. name: header,
  44416. data: []
  44417. };
  44418. });
  44419. for (var i = 0; i < tsvLines.length; i++) {
  44420. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  44421. categories.push(items.shift());
  44422. for (var j = 0; j < items.length; j++) {
  44423. series[j] && (series[j].data[i] = items[j]);
  44424. }
  44425. }
  44426. return {
  44427. series: series,
  44428. categories: categories
  44429. };
  44430. }
  44431. function parseListContents(str) {
  44432. var lines = str.split(/\n+/g);
  44433. var seriesName = trim$1(lines.shift());
  44434. var data = [];
  44435. for (var i = 0; i < lines.length; i++) {
  44436. // if line is empty, ignore it.
  44437. // there is a case that a user forgot to delete `\n`.
  44438. var line = trim$1(lines[i]);
  44439. if (!line) {
  44440. continue;
  44441. }
  44442. var items = line.split(itemSplitRegex);
  44443. var name_1 = '';
  44444. var value = void 0;
  44445. var hasName = false;
  44446. if (isNaN(items[0])) {
  44447. // First item is name
  44448. hasName = true;
  44449. name_1 = items[0];
  44450. items = items.slice(1);
  44451. data[i] = {
  44452. name: name_1,
  44453. value: []
  44454. };
  44455. value = data[i].value;
  44456. } else {
  44457. value = data[i] = [];
  44458. }
  44459. for (var j = 0; j < items.length; j++) {
  44460. value.push(+items[j]);
  44461. }
  44462. if (value.length === 1) {
  44463. hasName ? data[i].value = value[0] : data[i] = value[0];
  44464. }
  44465. }
  44466. return {
  44467. name: seriesName,
  44468. data: data
  44469. };
  44470. }
  44471. function parseContents(str, blockMetaList) {
  44472. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  44473. var newOption = {
  44474. series: []
  44475. };
  44476. each(blocks, function (block, idx) {
  44477. if (isTSVFormat(block)) {
  44478. var result = parseTSVContents(block);
  44479. var blockMeta = blockMetaList[idx];
  44480. var axisKey = blockMeta.axisDim + 'Axis';
  44481. if (blockMeta) {
  44482. newOption[axisKey] = newOption[axisKey] || [];
  44483. newOption[axisKey][blockMeta.axisIndex] = {
  44484. data: result.categories
  44485. };
  44486. newOption.series = newOption.series.concat(result.series);
  44487. }
  44488. } else {
  44489. var result = parseListContents(block);
  44490. newOption.series.push(result);
  44491. }
  44492. });
  44493. return newOption;
  44494. }
  44495. var DataView =
  44496. /** @class */
  44497. function (_super) {
  44498. __extends(DataView, _super);
  44499. function DataView() {
  44500. return _super !== null && _super.apply(this, arguments) || this;
  44501. }
  44502. DataView.prototype.onclick = function (ecModel, api) {
  44503. var container = api.getDom();
  44504. var model = this.model;
  44505. if (this._dom) {
  44506. container.removeChild(this._dom);
  44507. }
  44508. var root = document.createElement('div');
  44509. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  44510. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  44511. var header = document.createElement('h4');
  44512. var lang = model.get('lang') || [];
  44513. header.innerHTML = lang[0] || model.get('title');
  44514. header.style.cssText = 'margin: 10px 20px;';
  44515. header.style.color = model.get('textColor');
  44516. var viewMain = document.createElement('div');
  44517. var textarea = document.createElement('textarea');
  44518. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  44519. var optionToContent = model.get('optionToContent');
  44520. var contentToOption = model.get('contentToOption');
  44521. var result = getContentFromModel(ecModel);
  44522. if (typeof optionToContent === 'function') {
  44523. var htmlOrDom = optionToContent(api.getOption());
  44524. if (typeof htmlOrDom === 'string') {
  44525. viewMain.innerHTML = htmlOrDom;
  44526. } else if (isDom(htmlOrDom)) {
  44527. viewMain.appendChild(htmlOrDom);
  44528. }
  44529. } else {
  44530. // Use default textarea
  44531. viewMain.appendChild(textarea);
  44532. textarea.readOnly = model.get('readOnly');
  44533. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  44534. textarea.style.color = model.get('textColor');
  44535. textarea.style.borderColor = model.get('textareaBorderColor');
  44536. textarea.style.backgroundColor = model.get('textareaColor');
  44537. textarea.value = result.value;
  44538. }
  44539. var blockMetaList = result.meta;
  44540. var buttonContainer = document.createElement('div');
  44541. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  44542. var buttonStyle = 'float:right;margin-right:20px;border:none;' + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  44543. var closeButton = document.createElement('div');
  44544. var refreshButton = document.createElement('div');
  44545. buttonStyle += ';background-color:' + model.get('buttonColor');
  44546. buttonStyle += ';color:' + model.get('buttonTextColor');
  44547. var self = this;
  44548. function close() {
  44549. container.removeChild(root);
  44550. self._dom = null;
  44551. }
  44552. addEventListener(closeButton, 'click', close);
  44553. addEventListener(refreshButton, 'click', function () {
  44554. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  44555. if ("development" !== 'production') {
  44556. // eslint-disable-next-line
  44557. console.warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  44558. }
  44559. close();
  44560. return;
  44561. }
  44562. var newOption;
  44563. try {
  44564. if (typeof contentToOption === 'function') {
  44565. newOption = contentToOption(viewMain, api.getOption());
  44566. } else {
  44567. newOption = parseContents(textarea.value, blockMetaList);
  44568. }
  44569. } catch (e) {
  44570. close();
  44571. throw new Error('Data view format error ' + e);
  44572. }
  44573. if (newOption) {
  44574. api.dispatchAction({
  44575. type: 'changeDataView',
  44576. newOption: newOption
  44577. });
  44578. }
  44579. close();
  44580. });
  44581. closeButton.innerHTML = lang[1];
  44582. refreshButton.innerHTML = lang[2];
  44583. refreshButton.style.cssText = buttonStyle;
  44584. closeButton.style.cssText = buttonStyle;
  44585. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  44586. buttonContainer.appendChild(closeButton);
  44587. root.appendChild(header);
  44588. root.appendChild(viewMain);
  44589. root.appendChild(buttonContainer);
  44590. viewMain.style.height = container.clientHeight - 80 + 'px';
  44591. container.appendChild(root);
  44592. this._dom = root;
  44593. };
  44594. DataView.prototype.remove = function (ecModel, api) {
  44595. this._dom && api.getDom().removeChild(this._dom);
  44596. };
  44597. DataView.prototype.dispose = function (ecModel, api) {
  44598. this.remove(ecModel, api);
  44599. };
  44600. DataView.getDefaultOption = function (ecModel) {
  44601. var defaultOption = {
  44602. show: true,
  44603. readOnly: false,
  44604. optionToContent: null,
  44605. contentToOption: null,
  44606. // eslint-disable-next-line
  44607. 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',
  44608. title: ecModel.getLocale(['toolbox', 'dataView', 'title']),
  44609. lang: ecModel.getLocale(['toolbox', 'dataView', 'lang']),
  44610. backgroundColor: '#fff',
  44611. textColor: '#000',
  44612. textareaColor: '#fff',
  44613. textareaBorderColor: '#333',
  44614. buttonColor: '#c23531',
  44615. buttonTextColor: '#fff'
  44616. };
  44617. return defaultOption;
  44618. };
  44619. return DataView;
  44620. }(ToolboxFeature);
  44621. /**
  44622. * @inner
  44623. */
  44624. function tryMergeDataOption(newData, originalData) {
  44625. return map(newData, function (newVal, idx) {
  44626. var original = originalData && originalData[idx];
  44627. if (isObject(original) && !isArray(original)) {
  44628. var newValIsObject = isObject(newVal) && !isArray(newVal);
  44629. if (!newValIsObject) {
  44630. newVal = {
  44631. value: newVal
  44632. };
  44633. } // original data has name but new data has no name
  44634. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  44635. newVal = defaults(newVal, original);
  44636. shouldDeleteName && delete newVal.name;
  44637. return newVal;
  44638. } else {
  44639. return newVal;
  44640. }
  44641. });
  44642. } // TODO: SELF REGISTERED.
  44643. registerAction({
  44644. type: 'changeDataView',
  44645. event: 'dataViewChanged',
  44646. update: 'prepareAndUpdate'
  44647. }, function (payload, ecModel) {
  44648. var newSeriesOptList = [];
  44649. each(payload.newOption.series, function (seriesOpt) {
  44650. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  44651. if (!seriesModel) {
  44652. // New created series
  44653. // Geuss the series type
  44654. newSeriesOptList.push(extend({
  44655. // Default is scatter
  44656. type: 'scatter'
  44657. }, seriesOpt));
  44658. } else {
  44659. var originalData = seriesModel.get('data');
  44660. newSeriesOptList.push({
  44661. name: seriesOpt.name,
  44662. data: tryMergeDataOption(seriesOpt.data, originalData)
  44663. });
  44664. }
  44665. });
  44666. ecModel.mergeOption(defaults({
  44667. series: newSeriesOptList
  44668. }, payload.newOption));
  44669. });
  44670. var each$6 = each;
  44671. var inner$a = makeInner();
  44672. /**
  44673. * @param ecModel
  44674. * @param newSnapshot key is dataZoomId
  44675. */
  44676. function push(ecModel, newSnapshot) {
  44677. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  44678. // complete an range with current range.
  44679. each$6(newSnapshot, function (batchItem, dataZoomId) {
  44680. var i = storedSnapshots.length - 1;
  44681. for (; i >= 0; i--) {
  44682. var snapshot = storedSnapshots[i];
  44683. if (snapshot[dataZoomId]) {
  44684. break;
  44685. }
  44686. }
  44687. if (i < 0) {
  44688. // No origin range set, create one by current range.
  44689. var dataZoomModel = ecModel.queryComponents({
  44690. mainType: 'dataZoom',
  44691. subType: 'select',
  44692. id: dataZoomId
  44693. })[0];
  44694. if (dataZoomModel) {
  44695. var percentRange = dataZoomModel.getPercentRange();
  44696. storedSnapshots[0][dataZoomId] = {
  44697. dataZoomId: dataZoomId,
  44698. start: percentRange[0],
  44699. end: percentRange[1]
  44700. };
  44701. }
  44702. }
  44703. });
  44704. storedSnapshots.push(newSnapshot);
  44705. }
  44706. function pop(ecModel) {
  44707. var storedSnapshots = getStoreSnapshots(ecModel);
  44708. var head = storedSnapshots[storedSnapshots.length - 1];
  44709. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  44710. var snapshot = {};
  44711. each$6(head, function (batchItem, dataZoomId) {
  44712. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  44713. batchItem = storedSnapshots[i][dataZoomId];
  44714. if (batchItem) {
  44715. snapshot[dataZoomId] = batchItem;
  44716. break;
  44717. }
  44718. }
  44719. });
  44720. return snapshot;
  44721. }
  44722. function clear$1(ecModel) {
  44723. inner$a(ecModel).snapshots = null;
  44724. }
  44725. function count(ecModel) {
  44726. return getStoreSnapshots(ecModel).length;
  44727. }
  44728. /**
  44729. * History length of each dataZoom may be different.
  44730. * this._history[0] is used to store origin range.
  44731. */
  44732. function getStoreSnapshots(ecModel) {
  44733. var store = inner$a(ecModel);
  44734. if (!store.snapshots) {
  44735. store.snapshots = [{}];
  44736. }
  44737. return store.snapshots;
  44738. }
  44739. var RestoreOption =
  44740. /** @class */
  44741. function (_super) {
  44742. __extends(RestoreOption, _super);
  44743. function RestoreOption() {
  44744. return _super !== null && _super.apply(this, arguments) || this;
  44745. }
  44746. RestoreOption.prototype.onclick = function (ecModel, api) {
  44747. clear$1(ecModel);
  44748. api.dispatchAction({
  44749. type: 'restore',
  44750. from: this.uid
  44751. });
  44752. };
  44753. RestoreOption.getDefaultOption = function (ecModel) {
  44754. var defaultOption = {
  44755. show: true,
  44756. // eslint-disable-next-line
  44757. 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',
  44758. title: ecModel.getLocale(['toolbox', 'restore', 'title'])
  44759. };
  44760. return defaultOption;
  44761. };
  44762. return RestoreOption;
  44763. }(ToolboxFeature); // TODO: SELF REGISTERED.
  44764. registerAction({
  44765. type: 'restore',
  44766. event: 'restore',
  44767. update: 'prepareAndUpdate'
  44768. }, function (payload, ecModel) {
  44769. ecModel.resetOption('recreate');
  44770. });
  44771. var ATTR = '\0_ec_interaction_mutex';
  44772. function take(zr, resourceKey, userKey) {
  44773. var store = getStore(zr);
  44774. store[resourceKey] = userKey;
  44775. }
  44776. function release(zr, resourceKey, userKey) {
  44777. var store = getStore(zr);
  44778. var uKey = store[resourceKey];
  44779. if (uKey === userKey) {
  44780. store[resourceKey] = null;
  44781. }
  44782. }
  44783. function isTaken(zr, resourceKey) {
  44784. return !!getStore(zr)[resourceKey];
  44785. }
  44786. function getStore(zr) {
  44787. return zr[ATTR] || (zr[ATTR] = {});
  44788. }
  44789. /**
  44790. * payload: {
  44791. * type: 'takeGlobalCursor',
  44792. * key: 'dataZoomSelect', or 'brush', or ...,
  44793. * If no userKey, release global cursor.
  44794. * }
  44795. */
  44796. // TODO: SELF REGISTERED.
  44797. registerAction({
  44798. type: 'takeGlobalCursor',
  44799. event: 'globalCursorTaken',
  44800. update: 'update'
  44801. }, function () {});
  44802. var BRUSH_PANEL_GLOBAL = true;
  44803. var mathMin$7 = Math.min;
  44804. var mathMax$7 = Math.max;
  44805. var mathPow$2 = Math.pow;
  44806. var COVER_Z = 10000;
  44807. var UNSELECT_THRESHOLD = 6;
  44808. var MIN_RESIZE_LINE_WIDTH = 6;
  44809. var MUTEX_RESOURCE_KEY = 'globalPan';
  44810. var DIRECTION_MAP = {
  44811. w: [0, 0],
  44812. e: [0, 1],
  44813. n: [1, 0],
  44814. s: [1, 1]
  44815. };
  44816. var CURSOR_MAP = {
  44817. w: 'ew',
  44818. e: 'ew',
  44819. n: 'ns',
  44820. s: 'ns',
  44821. ne: 'nesw',
  44822. sw: 'nesw',
  44823. nw: 'nwse',
  44824. se: 'nwse'
  44825. };
  44826. var DEFAULT_BRUSH_OPT = {
  44827. brushStyle: {
  44828. lineWidth: 2,
  44829. stroke: 'rgba(210,219,238,0.3)',
  44830. fill: '#D2DBEE'
  44831. },
  44832. transformable: true,
  44833. brushMode: 'single',
  44834. removeOnClick: false
  44835. };
  44836. var baseUID = 0;
  44837. /**
  44838. * params:
  44839. * areas: Array.<Array>, coord relates to container group,
  44840. * If no container specified, to global.
  44841. * opt {
  44842. * isEnd: boolean,
  44843. * removeOnClick: boolean
  44844. * }
  44845. */
  44846. var BrushController =
  44847. /** @class */
  44848. function (_super) {
  44849. __extends(BrushController, _super);
  44850. function BrushController(zr) {
  44851. var _this = _super.call(this) || this;
  44852. /**
  44853. * @internal
  44854. */
  44855. _this._track = [];
  44856. /**
  44857. * @internal
  44858. */
  44859. _this._covers = [];
  44860. _this._handlers = {};
  44861. if ("development" !== 'production') {
  44862. assert(zr);
  44863. }
  44864. _this._zr = zr;
  44865. _this.group = new Group();
  44866. _this._uid = 'brushController_' + baseUID++;
  44867. each(pointerHandlers, function (handler, eventName) {
  44868. this._handlers[eventName] = bind(handler, this);
  44869. }, _this);
  44870. return _this;
  44871. }
  44872. /**
  44873. * If set to `false`, select disabled.
  44874. */
  44875. BrushController.prototype.enableBrush = function (brushOption) {
  44876. if ("development" !== 'production') {
  44877. assert(this._mounted);
  44878. }
  44879. this._brushType && this._doDisableBrush();
  44880. brushOption.brushType && this._doEnableBrush(brushOption);
  44881. return this;
  44882. };
  44883. BrushController.prototype._doEnableBrush = function (brushOption) {
  44884. var zr = this._zr; // Consider roam, which takes globalPan too.
  44885. if (!this._enableGlobalPan) {
  44886. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  44887. }
  44888. each(this._handlers, function (handler, eventName) {
  44889. zr.on(eventName, handler);
  44890. });
  44891. this._brushType = brushOption.brushType;
  44892. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  44893. };
  44894. BrushController.prototype._doDisableBrush = function () {
  44895. var zr = this._zr;
  44896. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  44897. each(this._handlers, function (handler, eventName) {
  44898. zr.off(eventName, handler);
  44899. });
  44900. this._brushType = this._brushOption = null;
  44901. };
  44902. /**
  44903. * @param panelOpts If not pass, it is global brush.
  44904. */
  44905. BrushController.prototype.setPanels = function (panelOpts) {
  44906. if (panelOpts && panelOpts.length) {
  44907. var panels_1 = this._panels = {};
  44908. each(panelOpts, function (panelOpts) {
  44909. panels_1[panelOpts.panelId] = clone(panelOpts);
  44910. });
  44911. } else {
  44912. this._panels = null;
  44913. }
  44914. return this;
  44915. };
  44916. BrushController.prototype.mount = function (opt) {
  44917. opt = opt || {};
  44918. if ("development" !== 'production') {
  44919. this._mounted = true; // should be at first.
  44920. }
  44921. this._enableGlobalPan = opt.enableGlobalPan;
  44922. var thisGroup = this.group;
  44923. this._zr.add(thisGroup);
  44924. thisGroup.attr({
  44925. x: opt.x || 0,
  44926. y: opt.y || 0,
  44927. rotation: opt.rotation || 0,
  44928. scaleX: opt.scaleX || 1,
  44929. scaleY: opt.scaleY || 1
  44930. });
  44931. this._transform = thisGroup.getLocalTransform();
  44932. return this;
  44933. }; // eachCover(cb, context): void {
  44934. // each(this._covers, cb, context);
  44935. // }
  44936. /**
  44937. * Update covers.
  44938. * @param coverConfigList
  44939. * If coverConfigList is null/undefined, all covers removed.
  44940. */
  44941. BrushController.prototype.updateCovers = function (coverConfigList) {
  44942. if ("development" !== 'production') {
  44943. assert(this._mounted);
  44944. }
  44945. coverConfigList = map(coverConfigList, function (coverConfig) {
  44946. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  44947. });
  44948. var tmpIdPrefix = '\0-brush-index-';
  44949. var oldCovers = this._covers;
  44950. var newCovers = this._covers = [];
  44951. var controller = this;
  44952. var creatingCover = this._creatingCover;
  44953. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  44954. return this;
  44955. function getKey(brushOption, index) {
  44956. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  44957. }
  44958. function oldGetKey(cover, index) {
  44959. return getKey(cover.__brushOption, index);
  44960. }
  44961. function addOrUpdate(newIndex, oldIndex) {
  44962. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  44963. // where updating cover when creating should be forbiden.
  44964. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  44965. newCovers[newIndex] = oldCovers[oldIndex];
  44966. } else {
  44967. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  44968. updateCoverAfterCreation(controller, cover);
  44969. }
  44970. }
  44971. function remove(oldIndex) {
  44972. if (oldCovers[oldIndex] !== creatingCover) {
  44973. controller.group.remove(oldCovers[oldIndex]);
  44974. }
  44975. }
  44976. };
  44977. BrushController.prototype.unmount = function () {
  44978. if ("development" !== 'production') {
  44979. if (!this._mounted) {
  44980. return;
  44981. }
  44982. }
  44983. this.enableBrush(false); // container may 'removeAll' outside.
  44984. clearCovers(this);
  44985. this._zr.remove(this.group);
  44986. if ("development" !== 'production') {
  44987. this._mounted = false; // should be at last.
  44988. }
  44989. return this;
  44990. };
  44991. BrushController.prototype.dispose = function () {
  44992. this.unmount();
  44993. this.off();
  44994. };
  44995. return BrushController;
  44996. }(Eventful);
  44997. function createCover(controller, brushOption) {
  44998. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  44999. cover.__brushOption = brushOption;
  45000. updateZ(cover, brushOption);
  45001. controller.group.add(cover);
  45002. return cover;
  45003. }
  45004. function endCreating(controller, creatingCover) {
  45005. var coverRenderer = getCoverRenderer(creatingCover);
  45006. if (coverRenderer.endCreating) {
  45007. coverRenderer.endCreating(controller, creatingCover);
  45008. updateZ(creatingCover, creatingCover.__brushOption);
  45009. }
  45010. return creatingCover;
  45011. }
  45012. function updateCoverShape(controller, cover) {
  45013. var brushOption = cover.__brushOption;
  45014. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  45015. }
  45016. function updateZ(cover, brushOption) {
  45017. var z = brushOption.z;
  45018. z == null && (z = COVER_Z);
  45019. cover.traverse(function (el) {
  45020. el.z = z;
  45021. el.z2 = z; // Consider in given container.
  45022. });
  45023. }
  45024. function updateCoverAfterCreation(controller, cover) {
  45025. getCoverRenderer(cover).updateCommon(controller, cover);
  45026. updateCoverShape(controller, cover);
  45027. }
  45028. function getCoverRenderer(cover) {
  45029. return coverRenderers[cover.__brushOption.brushType];
  45030. } // return target panel or `true` (means global panel)
  45031. function getPanelByPoint(controller, e, localCursorPoint) {
  45032. var panels = controller._panels;
  45033. if (!panels) {
  45034. return BRUSH_PANEL_GLOBAL; // Global panel
  45035. }
  45036. var panel;
  45037. var transform = controller._transform;
  45038. each(panels, function (pn) {
  45039. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  45040. });
  45041. return panel;
  45042. } // Return a panel or true
  45043. function getPanelByCover(controller, cover) {
  45044. var panels = controller._panels;
  45045. if (!panels) {
  45046. return BRUSH_PANEL_GLOBAL; // Global panel
  45047. }
  45048. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  45049. // which is then treated as global panel.
  45050. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  45051. }
  45052. function clearCovers(controller) {
  45053. var covers = controller._covers;
  45054. var originalLength = covers.length;
  45055. each(covers, function (cover) {
  45056. controller.group.remove(cover);
  45057. }, controller);
  45058. covers.length = 0;
  45059. return !!originalLength;
  45060. }
  45061. function trigger(controller, opt) {
  45062. var areas = map(controller._covers, function (cover) {
  45063. var brushOption = cover.__brushOption;
  45064. var range = clone(brushOption.range);
  45065. return {
  45066. brushType: brushOption.brushType,
  45067. panelId: brushOption.panelId,
  45068. range: range
  45069. };
  45070. });
  45071. controller.trigger('brush', {
  45072. areas: areas,
  45073. isEnd: !!opt.isEnd,
  45074. removeOnClick: !!opt.removeOnClick
  45075. });
  45076. }
  45077. function shouldShowCover(controller) {
  45078. var track = controller._track;
  45079. if (!track.length) {
  45080. return false;
  45081. }
  45082. var p2 = track[track.length - 1];
  45083. var p1 = track[0];
  45084. var dx = p2[0] - p1[0];
  45085. var dy = p2[1] - p1[1];
  45086. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  45087. return dist > UNSELECT_THRESHOLD;
  45088. }
  45089. function getTrackEnds(track) {
  45090. var tail = track.length - 1;
  45091. tail < 0 && (tail = 0);
  45092. return [track[0], track[tail]];
  45093. }
  45094. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  45095. var cover = new Group();
  45096. cover.add(new Rect({
  45097. name: 'main',
  45098. style: makeStyle(brushOption),
  45099. silent: true,
  45100. draggable: true,
  45101. cursor: 'move',
  45102. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  45103. ondragend: curry(trigger, controller, {
  45104. isEnd: true
  45105. })
  45106. }));
  45107. each(edgeNameSequences, function (nameSequence) {
  45108. cover.add(new Rect({
  45109. name: nameSequence.join(''),
  45110. style: {
  45111. opacity: 0
  45112. },
  45113. draggable: true,
  45114. silent: true,
  45115. invisible: true,
  45116. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  45117. ondragend: curry(trigger, controller, {
  45118. isEnd: true
  45119. })
  45120. }));
  45121. });
  45122. return cover;
  45123. }
  45124. function updateBaseRect(controller, cover, localRange, brushOption) {
  45125. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  45126. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  45127. var x = localRange[0][0];
  45128. var y = localRange[1][0];
  45129. var xa = x - lineWidth / 2;
  45130. var ya = y - lineWidth / 2;
  45131. var x2 = localRange[0][1];
  45132. var y2 = localRange[1][1];
  45133. var x2a = x2 - handleSize + lineWidth / 2;
  45134. var y2a = y2 - handleSize + lineWidth / 2;
  45135. var width = x2 - x;
  45136. var height = y2 - y;
  45137. var widtha = width + lineWidth;
  45138. var heighta = height + lineWidth;
  45139. updateRectShape(controller, cover, 'main', x, y, width, height);
  45140. if (brushOption.transformable) {
  45141. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  45142. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  45143. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  45144. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  45145. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  45146. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  45147. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  45148. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  45149. }
  45150. }
  45151. function updateCommon(controller, cover) {
  45152. var brushOption = cover.__brushOption;
  45153. var transformable = brushOption.transformable;
  45154. var mainEl = cover.childAt(0);
  45155. mainEl.useStyle(makeStyle(brushOption));
  45156. mainEl.attr({
  45157. silent: !transformable,
  45158. cursor: transformable ? 'move' : 'default'
  45159. });
  45160. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  45161. var el = cover.childOfName(nameSequence.join(''));
  45162. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  45163. el && el.attr({
  45164. silent: !transformable,
  45165. invisible: !transformable,
  45166. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  45167. });
  45168. });
  45169. }
  45170. function updateRectShape(controller, cover, name, x, y, w, h) {
  45171. var el = cover.childOfName(name);
  45172. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  45173. }
  45174. function makeStyle(brushOption) {
  45175. return defaults({
  45176. strokeNoScale: true
  45177. }, brushOption.brushStyle);
  45178. }
  45179. function formatRectRange(x, y, x2, y2) {
  45180. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  45181. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  45182. return [[min[0], max[0]], [min[1], max[1]] // y range
  45183. ];
  45184. }
  45185. function getTransform$1(controller) {
  45186. return getTransform(controller.group);
  45187. }
  45188. function getGlobalDirection1(controller, localDirName) {
  45189. var map = {
  45190. w: 'left',
  45191. e: 'right',
  45192. n: 'top',
  45193. s: 'bottom'
  45194. };
  45195. var inverseMap = {
  45196. left: 'w',
  45197. right: 'e',
  45198. top: 'n',
  45199. bottom: 's'
  45200. };
  45201. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  45202. return inverseMap[dir];
  45203. }
  45204. function getGlobalDirection2(controller, localDirNameSeq) {
  45205. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  45206. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  45207. return globalDir.join('');
  45208. }
  45209. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  45210. var brushOption = cover.__brushOption;
  45211. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  45212. var localDelta = toLocalDelta(controller, dx, dy);
  45213. each(dirNameSequence, function (dirName) {
  45214. var ind = DIRECTION_MAP[dirName];
  45215. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  45216. });
  45217. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  45218. updateCoverAfterCreation(controller, cover);
  45219. trigger(controller, {
  45220. isEnd: false
  45221. });
  45222. }
  45223. function driftPolygon(controller, cover, dx, dy) {
  45224. var range = cover.__brushOption.range;
  45225. var localDelta = toLocalDelta(controller, dx, dy);
  45226. each(range, function (point) {
  45227. point[0] += localDelta[0];
  45228. point[1] += localDelta[1];
  45229. });
  45230. updateCoverAfterCreation(controller, cover);
  45231. trigger(controller, {
  45232. isEnd: false
  45233. });
  45234. }
  45235. function toLocalDelta(controller, dx, dy) {
  45236. var thisGroup = controller.group;
  45237. var localD = thisGroup.transformCoordToLocal(dx, dy);
  45238. var localZero = thisGroup.transformCoordToLocal(0, 0);
  45239. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  45240. }
  45241. function clipByPanel(controller, cover, data) {
  45242. var panel = getPanelByCover(controller, cover);
  45243. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  45244. }
  45245. function pointsToRect(points) {
  45246. var xmin = mathMin$7(points[0][0], points[1][0]);
  45247. var ymin = mathMin$7(points[0][1], points[1][1]);
  45248. var xmax = mathMax$7(points[0][0], points[1][0]);
  45249. var ymax = mathMax$7(points[0][1], points[1][1]);
  45250. return {
  45251. x: xmin,
  45252. y: ymin,
  45253. width: xmax - xmin,
  45254. height: ymax - ymin
  45255. };
  45256. }
  45257. function resetCursor(controller, e, localCursorPoint) {
  45258. if ( // Check active
  45259. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  45260. // but not called when mouse is out of zr area to avoid bad influence
  45261. // if `mousemove`, `mouseup` are triggered from `document` event.
  45262. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  45263. return;
  45264. }
  45265. var zr = controller._zr;
  45266. var covers = controller._covers;
  45267. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  45268. if (!controller._dragging) {
  45269. for (var i = 0; i < covers.length; i++) {
  45270. var brushOption = covers[i].__brushOption;
  45271. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  45272. // Use cursor style set on cover.
  45273. return;
  45274. }
  45275. }
  45276. }
  45277. currPanel && zr.setCursorStyle('crosshair');
  45278. }
  45279. function preventDefault(e) {
  45280. var rawE = e.event;
  45281. rawE.preventDefault && rawE.preventDefault();
  45282. }
  45283. function mainShapeContain(cover, x, y) {
  45284. return cover.childOfName('main').contain(x, y);
  45285. }
  45286. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  45287. var creatingCover = controller._creatingCover;
  45288. var panel = controller._creatingPanel;
  45289. var thisBrushOption = controller._brushOption;
  45290. var eventParams;
  45291. controller._track.push(localCursorPoint.slice());
  45292. if (shouldShowCover(controller) || creatingCover) {
  45293. if (panel && !creatingCover) {
  45294. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  45295. var brushOption = clone(thisBrushOption);
  45296. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  45297. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  45298. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  45299. controller._covers.push(creatingCover);
  45300. }
  45301. if (creatingCover) {
  45302. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  45303. var coverBrushOption = creatingCover.__brushOption;
  45304. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  45305. if (isEnd) {
  45306. endCreating(controller, creatingCover);
  45307. coverRenderer.updateCommon(controller, creatingCover);
  45308. }
  45309. updateCoverShape(controller, creatingCover);
  45310. eventParams = {
  45311. isEnd: isEnd
  45312. };
  45313. }
  45314. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  45315. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  45316. // But a single click do not clear covers, because user may have casual
  45317. // clicks (for example, click on other component and do not expect covers
  45318. // disappear).
  45319. // Only some cover removed, trigger action, but not every click trigger action.
  45320. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  45321. eventParams = {
  45322. isEnd: isEnd,
  45323. removeOnClick: true
  45324. };
  45325. }
  45326. }
  45327. return eventParams;
  45328. }
  45329. function determineBrushType(brushType, panel) {
  45330. if (brushType === 'auto') {
  45331. if ("development" !== 'production') {
  45332. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  45333. }
  45334. return panel.defaultBrushType;
  45335. }
  45336. return brushType;
  45337. }
  45338. var pointerHandlers = {
  45339. mousedown: function (e) {
  45340. if (this._dragging) {
  45341. // In case some browser do not support globalOut,
  45342. // and release mouse out side the browser.
  45343. handleDragEnd(this, e);
  45344. } else if (!e.target || !e.target.draggable) {
  45345. preventDefault(e);
  45346. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  45347. this._creatingCover = null;
  45348. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  45349. if (panel) {
  45350. this._dragging = true;
  45351. this._track = [localCursorPoint.slice()];
  45352. }
  45353. }
  45354. },
  45355. mousemove: function (e) {
  45356. var x = e.offsetX;
  45357. var y = e.offsetY;
  45358. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  45359. resetCursor(this, e, localCursorPoint);
  45360. if (this._dragging) {
  45361. preventDefault(e);
  45362. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  45363. eventParams && trigger(this, eventParams);
  45364. }
  45365. },
  45366. mouseup: function (e) {
  45367. handleDragEnd(this, e);
  45368. }
  45369. };
  45370. function handleDragEnd(controller, e) {
  45371. if (controller._dragging) {
  45372. preventDefault(e);
  45373. var x = e.offsetX;
  45374. var y = e.offsetY;
  45375. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  45376. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  45377. controller._dragging = false;
  45378. controller._track = [];
  45379. controller._creatingCover = null; // trigger event shoule be at final, after procedure will be nested.
  45380. eventParams && trigger(controller, eventParams);
  45381. }
  45382. }
  45383. function isOutsideZrArea(controller, x, y) {
  45384. var zr = controller._zr;
  45385. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  45386. }
  45387. /**
  45388. * key: brushType
  45389. */
  45390. var coverRenderers = {
  45391. lineX: getLineRenderer(0),
  45392. lineY: getLineRenderer(1),
  45393. rect: {
  45394. createCover: function (controller, brushOption) {
  45395. function returnInput(range) {
  45396. return range;
  45397. }
  45398. return createBaseRectCover({
  45399. toRectRange: returnInput,
  45400. fromRectRange: returnInput
  45401. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  45402. },
  45403. getCreatingRange: function (localTrack) {
  45404. var ends = getTrackEnds(localTrack);
  45405. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  45406. },
  45407. updateCoverShape: function (controller, cover, localRange, brushOption) {
  45408. updateBaseRect(controller, cover, localRange, brushOption);
  45409. },
  45410. updateCommon: updateCommon,
  45411. contain: mainShapeContain
  45412. },
  45413. polygon: {
  45414. createCover: function (controller, brushOption) {
  45415. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  45416. // border of the shape when drawing, which is a better experience for user.
  45417. cover.add(new Polyline({
  45418. name: 'main',
  45419. style: makeStyle(brushOption),
  45420. silent: true
  45421. }));
  45422. return cover;
  45423. },
  45424. getCreatingRange: function (localTrack) {
  45425. return localTrack;
  45426. },
  45427. endCreating: function (controller, cover) {
  45428. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  45429. cover.add(new Polygon({
  45430. name: 'main',
  45431. draggable: true,
  45432. drift: curry(driftPolygon, controller, cover),
  45433. ondragend: curry(trigger, controller, {
  45434. isEnd: true
  45435. })
  45436. }));
  45437. },
  45438. updateCoverShape: function (controller, cover, localRange, brushOption) {
  45439. cover.childAt(0).setShape({
  45440. points: clipByPanel(controller, cover, localRange)
  45441. });
  45442. },
  45443. updateCommon: updateCommon,
  45444. contain: mainShapeContain
  45445. }
  45446. };
  45447. function getLineRenderer(xyIndex) {
  45448. return {
  45449. createCover: function (controller, brushOption) {
  45450. return createBaseRectCover({
  45451. toRectRange: function (range) {
  45452. var rectRange = [range, [0, 100]];
  45453. xyIndex && rectRange.reverse();
  45454. return rectRange;
  45455. },
  45456. fromRectRange: function (rectRange) {
  45457. return rectRange[xyIndex];
  45458. }
  45459. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  45460. },
  45461. getCreatingRange: function (localTrack) {
  45462. var ends = getTrackEnds(localTrack);
  45463. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  45464. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  45465. return [min, max];
  45466. },
  45467. updateCoverShape: function (controller, cover, localRange, brushOption) {
  45468. var otherExtent; // If brushWidth not specified, fit the panel.
  45469. var panel = getPanelByCover(controller, cover);
  45470. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  45471. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  45472. } else {
  45473. var zr = controller._zr;
  45474. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  45475. }
  45476. var rectRange = [localRange, otherExtent];
  45477. xyIndex && rectRange.reverse();
  45478. updateBaseRect(controller, cover, rectRange, brushOption);
  45479. },
  45480. updateCommon: updateCommon,
  45481. contain: mainShapeContain
  45482. };
  45483. }
  45484. /*
  45485. * Licensed to the Apache Software Foundation (ASF) under one
  45486. * or more contributor license agreements. See the NOTICE file
  45487. * distributed with this work for additional information
  45488. * regarding copyright ownership. The ASF licenses this file
  45489. * to you under the Apache License, Version 2.0 (the
  45490. * "License"); you may not use this file except in compliance
  45491. * with the License. You may obtain a copy of the License at
  45492. *
  45493. * http://www.apache.org/licenses/LICENSE-2.0
  45494. *
  45495. * Unless required by applicable law or agreed to in writing,
  45496. * software distributed under the License is distributed on an
  45497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45498. * KIND, either express or implied. See the License for the
  45499. * specific language governing permissions and limitations
  45500. * under the License.
  45501. */
  45502. /**
  45503. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45504. */
  45505. /*
  45506. * Licensed to the Apache Software Foundation (ASF) under one
  45507. * or more contributor license agreements. See the NOTICE file
  45508. * distributed with this work for additional information
  45509. * regarding copyright ownership. The ASF licenses this file
  45510. * to you under the Apache License, Version 2.0 (the
  45511. * "License"); you may not use this file except in compliance
  45512. * with the License. You may obtain a copy of the License at
  45513. *
  45514. * http://www.apache.org/licenses/LICENSE-2.0
  45515. *
  45516. * Unless required by applicable law or agreed to in writing,
  45517. * software distributed under the License is distributed on an
  45518. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45519. * KIND, either express or implied. See the License for the
  45520. * specific language governing permissions and limitations
  45521. * under the License.
  45522. */
  45523. var IRRELEVANT_EXCLUDES = {
  45524. 'axisPointer': 1,
  45525. 'tooltip': 1,
  45526. 'brush': 1
  45527. };
  45528. /**
  45529. * Avoid that: mouse click on a elements that is over geo or graph,
  45530. * but roam is triggered.
  45531. */
  45532. function onIrrelevantElement(e, api, targetCoordSysModel) {
  45533. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  45534. var coordSys = model && model.coordinateSystem;
  45535. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  45536. }
  45537. function makeRectPanelClipPath(rect) {
  45538. rect = normalizeRect(rect);
  45539. return function (localPoints) {
  45540. return clipPointsByRect(localPoints, rect);
  45541. };
  45542. }
  45543. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  45544. rect = normalizeRect(rect);
  45545. return function (xyIndex) {
  45546. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  45547. var brushWidth = idx ? rect.width : rect.height;
  45548. var base = idx ? rect.x : rect.y;
  45549. return [base, base + (brushWidth || 0)];
  45550. };
  45551. }
  45552. function makeRectIsTargetByCursor(rect, api, targetModel) {
  45553. var boundingRect = normalizeRect(rect);
  45554. return function (e, localCursorPoint) {
  45555. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  45556. };
  45557. } // Consider width/height is negative.
  45558. function normalizeRect(rect) {
  45559. return BoundingRect.create(rect);
  45560. }
  45561. var COORD_CONVERTS = ['dataToPoint', 'pointToData']; // FIXME
  45562. // how to genarialize to more coordinate systems.
  45563. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  45564. var BrushTargetManager =
  45565. /** @class */
  45566. function () {
  45567. /**
  45568. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  45569. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  45570. * @param opt.include include coordinate system types.
  45571. */
  45572. function BrushTargetManager(finder, ecModel, opt) {
  45573. var _this = this;
  45574. this._targetInfoList = [];
  45575. var foundCpts = parseFinder$1(ecModel, finder);
  45576. each(targetInfoBuilders, function (builder, type) {
  45577. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  45578. builder(foundCpts, _this._targetInfoList);
  45579. }
  45580. });
  45581. }
  45582. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  45583. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  45584. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  45585. if (!area.coordRange) {
  45586. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  45587. // rebuild range by coordRange accrately, which may bring trouble when
  45588. // brushing only one item. So we use __rangeOffset to rebuilding range
  45589. // by coordRange. And this it only used in brush component so it is no
  45590. // need to be adapted to coordRanges.
  45591. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  45592. area.__rangeOffset = {
  45593. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  45594. xyMinMax: result.xyMinMax
  45595. };
  45596. }
  45597. });
  45598. return areas;
  45599. };
  45600. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  45601. each(areas, function (area) {
  45602. var targetInfo = this.findTargetInfo(area, ecModel);
  45603. if (targetInfo && targetInfo !== true) {
  45604. each(targetInfo.coordSyses, function (coordSys) {
  45605. var result = coordConvert[area.brushType](1, coordSys, area.range);
  45606. cb(area, result.values, coordSys, ecModel);
  45607. });
  45608. }
  45609. }, this);
  45610. };
  45611. /**
  45612. * the `areas` is `BrushModel.areas`.
  45613. * Called in layout stage.
  45614. * convert `area.coordRange` to global range and set panelId to `area.range`.
  45615. */
  45616. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  45617. each(areas, function (area) {
  45618. var targetInfo = this.findTargetInfo(area, ecModel);
  45619. if ("development" !== 'production') {
  45620. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  45621. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  45622. }
  45623. area.range = area.range || []; // convert coordRange to global range and set panelId.
  45624. if (targetInfo && targetInfo !== true) {
  45625. area.panelId = targetInfo.panelId; // (1) area.range shoule always be calculate from coordRange but does
  45626. // not keep its original value, for the sake of the dataZoom scenario,
  45627. // where area.coordRange remains unchanged but area.range may be changed.
  45628. // (2) Only support converting one coordRange to pixel range in brush
  45629. // component. So do not consider `coordRanges`.
  45630. // (3) About __rangeOffset, see comment above.
  45631. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  45632. var rangeOffset = area.__rangeOffset;
  45633. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  45634. }
  45635. }, this);
  45636. };
  45637. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  45638. return map(this._targetInfoList, function (targetInfo) {
  45639. var rect = targetInfo.getPanelRect();
  45640. return {
  45641. panelId: targetInfo.panelId,
  45642. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  45643. clipPath: makeRectPanelClipPath(rect),
  45644. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  45645. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  45646. };
  45647. });
  45648. };
  45649. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  45650. // Check whether area is bound in coord, and series do not belong to that coord.
  45651. // If do not do this check, some brush (like lineX) will controll all axes.
  45652. var targetInfo = this.findTargetInfo(area, ecModel);
  45653. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  45654. };
  45655. /**
  45656. * If return Object, a coord found.
  45657. * If reutrn true, global found.
  45658. * Otherwise nothing found.
  45659. */
  45660. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  45661. var targetInfoList = this._targetInfoList;
  45662. var foundCpts = parseFinder$1(ecModel, area);
  45663. for (var i = 0; i < targetInfoList.length; i++) {
  45664. var targetInfo = targetInfoList[i];
  45665. var areaPanelId = area.panelId;
  45666. if (areaPanelId) {
  45667. if (targetInfo.panelId === areaPanelId) {
  45668. return targetInfo;
  45669. }
  45670. } else {
  45671. for (var j = 0; j < targetInfoMatchers.length; j++) {
  45672. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  45673. return targetInfo;
  45674. }
  45675. }
  45676. }
  45677. }
  45678. return true;
  45679. };
  45680. return BrushTargetManager;
  45681. }();
  45682. function formatMinMax(minMax) {
  45683. minMax[0] > minMax[1] && minMax.reverse();
  45684. return minMax;
  45685. }
  45686. function parseFinder$1(ecModel, finder) {
  45687. return parseFinder(ecModel, finder, {
  45688. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  45689. });
  45690. }
  45691. var targetInfoBuilders = {
  45692. grid: function (foundCpts, targetInfoList) {
  45693. var xAxisModels = foundCpts.xAxisModels;
  45694. var yAxisModels = foundCpts.yAxisModels;
  45695. var gridModels = foundCpts.gridModels; // Remove duplicated.
  45696. var gridModelMap = createHashMap();
  45697. var xAxesHas = {};
  45698. var yAxesHas = {};
  45699. if (!xAxisModels && !yAxisModels && !gridModels) {
  45700. return;
  45701. }
  45702. each(xAxisModels, function (axisModel) {
  45703. var gridModel = axisModel.axis.grid.model;
  45704. gridModelMap.set(gridModel.id, gridModel);
  45705. xAxesHas[gridModel.id] = true;
  45706. });
  45707. each(yAxisModels, function (axisModel) {
  45708. var gridModel = axisModel.axis.grid.model;
  45709. gridModelMap.set(gridModel.id, gridModel);
  45710. yAxesHas[gridModel.id] = true;
  45711. });
  45712. each(gridModels, function (gridModel) {
  45713. gridModelMap.set(gridModel.id, gridModel);
  45714. xAxesHas[gridModel.id] = true;
  45715. yAxesHas[gridModel.id] = true;
  45716. });
  45717. gridModelMap.each(function (gridModel) {
  45718. var grid = gridModel.coordinateSystem;
  45719. var cartesians = [];
  45720. each(grid.getCartesians(), function (cartesian, index) {
  45721. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  45722. cartesians.push(cartesian);
  45723. }
  45724. });
  45725. targetInfoList.push({
  45726. panelId: 'grid--' + gridModel.id,
  45727. gridModel: gridModel,
  45728. coordSysModel: gridModel,
  45729. // Use the first one as the representitive coordSys.
  45730. coordSys: cartesians[0],
  45731. coordSyses: cartesians,
  45732. getPanelRect: panelRectBuilders.grid,
  45733. xAxisDeclared: xAxesHas[gridModel.id],
  45734. yAxisDeclared: yAxesHas[gridModel.id]
  45735. });
  45736. });
  45737. },
  45738. geo: function (foundCpts, targetInfoList) {
  45739. each(foundCpts.geoModels, function (geoModel) {
  45740. var coordSys = geoModel.coordinateSystem;
  45741. targetInfoList.push({
  45742. panelId: 'geo--' + geoModel.id,
  45743. geoModel: geoModel,
  45744. coordSysModel: geoModel,
  45745. coordSys: coordSys,
  45746. coordSyses: [coordSys],
  45747. getPanelRect: panelRectBuilders.geo
  45748. });
  45749. });
  45750. }
  45751. };
  45752. var targetInfoMatchers = [// grid
  45753. function (foundCpts, targetInfo) {
  45754. var xAxisModel = foundCpts.xAxisModel;
  45755. var yAxisModel = foundCpts.yAxisModel;
  45756. var gridModel = foundCpts.gridModel;
  45757. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  45758. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  45759. return gridModel && gridModel === targetInfo.gridModel;
  45760. }, // geo
  45761. function (foundCpts, targetInfo) {
  45762. var geoModel = foundCpts.geoModel;
  45763. return geoModel && geoModel === targetInfo.geoModel;
  45764. }];
  45765. var panelRectBuilders = {
  45766. grid: function () {
  45767. // grid is not Transformable.
  45768. return this.coordSys.master.getRect().clone();
  45769. },
  45770. geo: function () {
  45771. var coordSys = this.coordSys;
  45772. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  45773. rect.applyTransform(getTransform(coordSys));
  45774. return rect;
  45775. }
  45776. };
  45777. var coordConvert = {
  45778. lineX: curry(axisConvert, 0),
  45779. lineY: curry(axisConvert, 1),
  45780. rect: function (to, coordSys, rangeOrCoordRange) {
  45781. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  45782. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  45783. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  45784. return {
  45785. values: values,
  45786. xyMinMax: values
  45787. };
  45788. },
  45789. polygon: function (to, coordSys, rangeOrCoordRange) {
  45790. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  45791. var values = map(rangeOrCoordRange, function (item) {
  45792. var p = coordSys[COORD_CONVERTS[to]](item);
  45793. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  45794. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  45795. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  45796. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  45797. return p;
  45798. });
  45799. return {
  45800. values: values,
  45801. xyMinMax: xyMinMax
  45802. };
  45803. }
  45804. };
  45805. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  45806. if ("development" !== 'production') {
  45807. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  45808. }
  45809. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  45810. var values = formatMinMax(map([0, 1], function (i) {
  45811. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i])) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  45812. }));
  45813. var xyMinMax = [];
  45814. xyMinMax[axisNameIndex] = values;
  45815. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  45816. return {
  45817. values: values,
  45818. xyMinMax: xyMinMax
  45819. };
  45820. }
  45821. var diffProcessor = {
  45822. lineX: curry(axisDiffProcessor, 0),
  45823. lineY: curry(axisDiffProcessor, 1),
  45824. rect: function (values, refer, scales) {
  45825. 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]]];
  45826. },
  45827. polygon: function (values, refer, scales) {
  45828. return map(values, function (item, idx) {
  45829. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  45830. });
  45831. }
  45832. };
  45833. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  45834. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  45835. } // We have to process scale caused by dataZoom manually,
  45836. // although it might be not accurate.
  45837. // Return [0~1, 0~1]
  45838. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  45839. var sizeCurr = getSize(xyMinMaxCurr);
  45840. var sizeOrigin = getSize(xyMinMaxOrigin);
  45841. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  45842. isNaN(scales[0]) && (scales[0] = 1);
  45843. isNaN(scales[1]) && (scales[1] = 1);
  45844. return scales;
  45845. }
  45846. function getSize(xyMinMax) {
  45847. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  45848. }
  45849. var each$7 = each;
  45850. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  45851. var DataZoomFeature =
  45852. /** @class */
  45853. function (_super) {
  45854. __extends(DataZoomFeature, _super);
  45855. function DataZoomFeature() {
  45856. return _super !== null && _super.apply(this, arguments) || this;
  45857. }
  45858. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  45859. if (!this._brushController) {
  45860. this._brushController = new BrushController(api.getZr());
  45861. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  45862. }
  45863. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  45864. updateBackBtnStatus(featureModel, ecModel);
  45865. };
  45866. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  45867. handlers[type].call(this);
  45868. };
  45869. DataZoomFeature.prototype.remove = function (ecModel, api) {
  45870. this._brushController && this._brushController.unmount();
  45871. };
  45872. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  45873. this._brushController && this._brushController.dispose();
  45874. };
  45875. DataZoomFeature.prototype._onBrush = function (eventParam) {
  45876. var areas = eventParam.areas;
  45877. if (!eventParam.isEnd || !areas.length) {
  45878. return;
  45879. }
  45880. var snapshot = {};
  45881. var ecModel = this.ecModel;
  45882. this._brushController.updateCovers([]); // remove cover
  45883. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  45884. include: ['grid']
  45885. });
  45886. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  45887. if (coordSys.type !== 'cartesian2d') {
  45888. return;
  45889. }
  45890. var brushType = area.brushType;
  45891. if (brushType === 'rect') {
  45892. setBatch('x', coordSys, coordRange[0]);
  45893. setBatch('y', coordSys, coordRange[1]);
  45894. } else {
  45895. setBatch({
  45896. lineX: 'x',
  45897. lineY: 'y'
  45898. }[brushType], coordSys, coordRange);
  45899. }
  45900. });
  45901. push(ecModel, snapshot);
  45902. this._dispatchZoomAction(snapshot);
  45903. function setBatch(dimName, coordSys, minMax) {
  45904. var axis = coordSys.getAxis(dimName);
  45905. var axisModel = axis.model;
  45906. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  45907. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  45908. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  45909. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  45910. }
  45911. dataZoomModel && (snapshot[dataZoomModel.id] = {
  45912. dataZoomId: dataZoomModel.id,
  45913. startValue: minMax[0],
  45914. endValue: minMax[1]
  45915. });
  45916. }
  45917. function findDataZoom(dimName, axisModel, ecModel) {
  45918. var found;
  45919. ecModel.eachComponent({
  45920. mainType: 'dataZoom',
  45921. subType: 'select'
  45922. }, function (dzModel) {
  45923. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  45924. has && (found = dzModel);
  45925. });
  45926. return found;
  45927. }
  45928. };
  45929. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  45930. var batch = []; // Convert from hash map to array.
  45931. each$7(snapshot, function (batchItem, dataZoomId) {
  45932. batch.push(clone(batchItem));
  45933. });
  45934. batch.length && this.api.dispatchAction({
  45935. type: 'dataZoom',
  45936. from: this.uid,
  45937. batch: batch
  45938. });
  45939. };
  45940. DataZoomFeature.getDefaultOption = function (ecModel) {
  45941. var defaultOption = {
  45942. show: true,
  45943. filterMode: 'filter',
  45944. // Icon group
  45945. icon: {
  45946. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  45947. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  45948. },
  45949. // `zoom`, `back`
  45950. title: ecModel.getLocale(['toolbox', 'dataZoom', 'title']),
  45951. brushStyle: {
  45952. borderWidth: 0,
  45953. color: 'rgba(210,219,238,0.2)'
  45954. }
  45955. };
  45956. return defaultOption;
  45957. };
  45958. return DataZoomFeature;
  45959. }(ToolboxFeature);
  45960. var handlers = {
  45961. zoom: function () {
  45962. var nextActive = !this._isZoomActive;
  45963. this.api.dispatchAction({
  45964. type: 'takeGlobalCursor',
  45965. key: 'dataZoomSelect',
  45966. dataZoomSelectActive: nextActive
  45967. });
  45968. },
  45969. back: function () {
  45970. this._dispatchZoomAction(pop(this.ecModel));
  45971. }
  45972. };
  45973. function makeAxisFinder(dzFeatureModel) {
  45974. var setting = {
  45975. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  45976. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  45977. xAxisId: dzFeatureModel.get('xAxisId', true),
  45978. yAxisId: dzFeatureModel.get('yAxisId', true)
  45979. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  45980. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  45981. // Some old cases set like this below to close yAxis control but leave xAxis control:
  45982. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  45983. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  45984. setting.xAxisIndex = 'all';
  45985. }
  45986. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  45987. setting.yAxisIndex = 'all';
  45988. }
  45989. return setting;
  45990. }
  45991. function updateBackBtnStatus(featureModel, ecModel) {
  45992. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  45993. }
  45994. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  45995. var zoomActive = view._isZoomActive;
  45996. if (payload && payload.type === 'takeGlobalCursor') {
  45997. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  45998. }
  45999. view._isZoomActive = zoomActive;
  46000. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  46001. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  46002. include: ['grid']
  46003. });
  46004. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  46005. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  46006. });
  46007. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  46008. brushType: 'auto',
  46009. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  46010. } : false);
  46011. }
  46012. registerInternalOptionCreator('dataZoom', function (ecModel) {
  46013. var toolboxModel = ecModel.getComponent('toolbox', 0);
  46014. if (!toolboxModel) {
  46015. return;
  46016. }
  46017. var dzFeatureModel = toolboxModel.getModel(['feature', 'dataZoom']);
  46018. var dzOptions = [];
  46019. var finder = makeAxisFinder(dzFeatureModel);
  46020. var finderResult = parseFinder(ecModel, finder);
  46021. each$7(finderResult.xAxisModels, function (axisModel) {
  46022. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  46023. });
  46024. each$7(finderResult.yAxisModels, function (axisModel) {
  46025. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  46026. });
  46027. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  46028. var axisIndex = axisModel.componentIndex;
  46029. var newOpt = {
  46030. type: 'select',
  46031. $fromToolbox: true,
  46032. // Default to be filter
  46033. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  46034. // Id for merge mapping.
  46035. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  46036. };
  46037. newOpt[axisIndexPropName] = axisIndex;
  46038. dzOptions.push(newOpt);
  46039. }
  46040. return dzOptions;
  46041. });
  46042. function install$b(registers) {
  46043. registers.registerComponentModel(ToolboxModel);
  46044. registers.registerComponentView(ToolboxView);
  46045. registerFeature('saveAsImage', SaveAsImage);
  46046. registerFeature('magicType', MagicType);
  46047. registerFeature('dataView', DataView);
  46048. registerFeature('dataZoom', DataZoomFeature);
  46049. registerFeature('restore', RestoreOption);
  46050. use(install$a);
  46051. }
  46052. var TooltipModel =
  46053. /** @class */
  46054. function (_super) {
  46055. __extends(TooltipModel, _super);
  46056. function TooltipModel() {
  46057. var _this = _super !== null && _super.apply(this, arguments) || this;
  46058. _this.type = TooltipModel.type;
  46059. return _this;
  46060. }
  46061. TooltipModel.type = 'tooltip';
  46062. TooltipModel.dependencies = ['axisPointer'];
  46063. TooltipModel.defaultOption = {
  46064. zlevel: 0,
  46065. z: 60,
  46066. show: true,
  46067. // tooltip main content
  46068. showContent: true,
  46069. // 'trigger' only works on coordinate system.
  46070. // 'item' | 'axis' | 'none'
  46071. trigger: 'item',
  46072. // 'click' | 'mousemove' | 'none'
  46073. triggerOn: 'mousemove|click',
  46074. alwaysShowContent: false,
  46075. displayMode: 'single',
  46076. renderMode: 'auto',
  46077. // whether restraint content inside viewRect.
  46078. // If renderMode: 'richText', default true.
  46079. // If renderMode: 'html', defaut false (for backward compat).
  46080. confine: null,
  46081. showDelay: 0,
  46082. hideDelay: 100,
  46083. // Animation transition time, unit is second
  46084. transitionDuration: 0.4,
  46085. enterable: false,
  46086. backgroundColor: '#fff',
  46087. // box shadow
  46088. shadowBlur: 10,
  46089. shadowColor: 'rgba(0, 0, 0, .2)',
  46090. shadowOffsetX: 1,
  46091. shadowOffsetY: 2,
  46092. // tooltip border radius, unit is px, default is 4
  46093. borderRadius: 4,
  46094. // tooltip border width, unit is px, default is 0 (no border)
  46095. borderWidth: 1,
  46096. // Tooltip inside padding, default is 5 for all direction
  46097. // Array is allowed to set up, right, bottom, left, same with css
  46098. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  46099. padding: null,
  46100. // Extra css text
  46101. extraCssText: '',
  46102. // axis indicator, trigger by axis
  46103. axisPointer: {
  46104. // default is line
  46105. // legal values: 'line' | 'shadow' | 'cross'
  46106. type: 'line',
  46107. // Valid when type is line, appoint tooltip line locate on which line. Optional
  46108. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  46109. // default is 'auto', chose the axis which type is category.
  46110. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  46111. axis: 'auto',
  46112. animation: 'auto',
  46113. animationDurationUpdate: 200,
  46114. animationEasingUpdate: 'exponentialOut',
  46115. crossStyle: {
  46116. color: '#999',
  46117. width: 1,
  46118. type: 'dashed',
  46119. // TODO formatter
  46120. textStyle: {}
  46121. } // lineStyle and shadowStyle should not be specified here,
  46122. // otherwise it will always override those styles on option.axisPointer.
  46123. },
  46124. textStyle: {
  46125. color: '#666',
  46126. fontSize: 14
  46127. }
  46128. };
  46129. return TooltipModel;
  46130. }(ComponentModel);
  46131. /*
  46132. * Licensed to the Apache Software Foundation (ASF) under one
  46133. * or more contributor license agreements. See the NOTICE file
  46134. * distributed with this work for additional information
  46135. * regarding copyright ownership. The ASF licenses this file
  46136. * to you under the Apache License, Version 2.0 (the
  46137. * "License"); you may not use this file except in compliance
  46138. * with the License. You may obtain a copy of the License at
  46139. *
  46140. * http://www.apache.org/licenses/LICENSE-2.0
  46141. *
  46142. * Unless required by applicable law or agreed to in writing,
  46143. * software distributed under the License is distributed on an
  46144. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46145. * KIND, either express or implied. See the License for the
  46146. * specific language governing permissions and limitations
  46147. * under the License.
  46148. */
  46149. /**
  46150. * AUTO-GENERATED FILE. DO NOT MODIFY.
  46151. */
  46152. /*
  46153. * Licensed to the Apache Software Foundation (ASF) under one
  46154. * or more contributor license agreements. See the NOTICE file
  46155. * distributed with this work for additional information
  46156. * regarding copyright ownership. The ASF licenses this file
  46157. * to you under the Apache License, Version 2.0 (the
  46158. * "License"); you may not use this file except in compliance
  46159. * with the License. You may obtain a copy of the License at
  46160. *
  46161. * http://www.apache.org/licenses/LICENSE-2.0
  46162. *
  46163. * Unless required by applicable law or agreed to in writing,
  46164. * software distributed under the License is distributed on an
  46165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46166. * KIND, either express or implied. See the License for the
  46167. * specific language governing permissions and limitations
  46168. * under the License.
  46169. */
  46170. function shouldTooltipConfine(tooltipModel) {
  46171. var confineOption = tooltipModel.get('confine');
  46172. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  46173. : tooltipModel.get('renderMode') === 'richText';
  46174. }
  46175. var vendors = ['-ms-', '-moz-', '-o-', '-webkit-', ''];
  46176. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  46177. function mirrorPos(pos) {
  46178. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  46179. return pos;
  46180. }
  46181. function assembleArrow(backgroundColor, borderColor, arrowPosition) {
  46182. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  46183. return '';
  46184. }
  46185. borderColor = convertToColorString(borderColor);
  46186. var arrowPos = mirrorPos(arrowPosition);
  46187. var positionStyle = '';
  46188. var transformStyle = '';
  46189. if (indexOf(['left', 'right'], arrowPos) > -1) {
  46190. positionStyle = arrowPos + ":-6px;top:50%;";
  46191. transformStyle = "translateY(-50%) rotate(" + (arrowPos === 'left' ? -225 : -45) + "deg)";
  46192. } else {
  46193. positionStyle = arrowPos + ":-6px;left:50%;";
  46194. transformStyle = "translateX(-50%) rotate(" + (arrowPos === 'top' ? 225 : 45) + "deg)";
  46195. }
  46196. transformStyle = map(vendors, function (vendorPrefix) {
  46197. return vendorPrefix + 'transform:' + transformStyle;
  46198. }).join(';');
  46199. 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;'];
  46200. return "<div style=\"" + styleCss.join('') + "\"></div>";
  46201. }
  46202. function assembleTransition(duration, onlyFade) {
  46203. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  46204. var transitionText = 'opacity ' + duration / 2 + 's ' + transitionCurve + ',' + 'visibility ' + duration / 2 + 's ' + transitionCurve;
  46205. if (!onlyFade) {
  46206. transitionText += ',left ' + duration + 's ' + transitionCurve + ',top ' + duration + 's ' + transitionCurve;
  46207. }
  46208. return map(vendors, function (vendorPrefix) {
  46209. return vendorPrefix + 'transition:' + transitionText;
  46210. }).join(';');
  46211. }
  46212. /**
  46213. * @param {Object} textStyle
  46214. * @return {string}
  46215. * @inner
  46216. */
  46217. function assembleFont(textStyleModel) {
  46218. var cssText = [];
  46219. var fontSize = textStyleModel.get('fontSize');
  46220. var color = textStyleModel.getTextColor();
  46221. color && cssText.push('color:' + color);
  46222. cssText.push('font:' + textStyleModel.getFont());
  46223. fontSize // @ts-ignore, leave it to the tooltip refactor.
  46224. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  46225. var shadowColor = textStyleModel.get('textShadowColor');
  46226. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  46227. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  46228. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  46229. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  46230. each(['decoration', 'align'], function (name) {
  46231. var val = textStyleModel.get(name);
  46232. val && cssText.push('text-' + name + ':' + val);
  46233. });
  46234. return cssText.join(';');
  46235. }
  46236. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  46237. var cssText = [];
  46238. var transitionDuration = tooltipModel.get('transitionDuration');
  46239. var backgroundColor = tooltipModel.get('backgroundColor');
  46240. var shadowBlur = tooltipModel.get('shadowBlur');
  46241. var shadowColor = tooltipModel.get('shadowColor');
  46242. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  46243. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  46244. var textStyleModel = tooltipModel.getModel('textStyle');
  46245. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  46246. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  46247. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  46248. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  46249. if (backgroundColor) {
  46250. if (env.canvasSupported) {
  46251. cssText.push('background-Color:' + backgroundColor);
  46252. } else {
  46253. // for ie
  46254. cssText.push('background-Color:#' + toHex(backgroundColor));
  46255. cssText.push('filter:alpha(opacity=70)');
  46256. }
  46257. } // Border style
  46258. each(['width', 'color', 'radius'], function (name) {
  46259. var borderName = 'border-' + name;
  46260. var camelCase = toCamelCase(borderName);
  46261. var val = tooltipModel.get(camelCase);
  46262. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  46263. }); // Text style
  46264. cssText.push(assembleFont(textStyleModel)); // Padding
  46265. if (padding != null) {
  46266. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  46267. }
  46268. return cssText.join(';') + ';';
  46269. } // If not able to make, do not modify the input `out`.
  46270. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  46271. var zrPainter = zr && zr.painter;
  46272. if (appendToBody) {
  46273. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  46274. if (zrViewportRoot) {
  46275. // Some APPs might use scale on body, so we support CSS transform here.
  46276. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  46277. }
  46278. } else {
  46279. out[0] = zrX;
  46280. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  46281. // the sibling of canvas root. So padding of ec container
  46282. // should be considered here.
  46283. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  46284. if (viewportRootOffset) {
  46285. out[0] += viewportRootOffset.offsetLeft;
  46286. out[1] += viewportRootOffset.offsetTop;
  46287. }
  46288. }
  46289. out[2] = out[0] / zr.getWidth();
  46290. out[3] = out[1] / zr.getHeight();
  46291. }
  46292. var TooltipHTMLContent =
  46293. /** @class */
  46294. function () {
  46295. function TooltipHTMLContent(container, api, opt) {
  46296. this._show = false;
  46297. this._styleCoord = [0, 0, 0, 0];
  46298. this._enterable = true;
  46299. this._firstShow = true;
  46300. this._longHide = true;
  46301. if (env.wxa) {
  46302. return null;
  46303. }
  46304. var el = document.createElement('div'); // TODO: TYPE
  46305. el.domBelongToZr = true;
  46306. this.el = el;
  46307. var zr = this._zr = api.getZr();
  46308. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  46309. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  46310. if (appendToBody) {
  46311. document.body.appendChild(el);
  46312. } else {
  46313. container.appendChild(el);
  46314. }
  46315. this._container = container; // FIXME
  46316. // Is it needed to trigger zr event manually if
  46317. // the browser do not support `pointer-events: none`.
  46318. var self = this;
  46319. el.onmouseenter = function () {
  46320. // clear the timeout in hideLater and keep showing tooltip
  46321. if (self._enterable) {
  46322. clearTimeout(self._hideTimeout);
  46323. self._show = true;
  46324. }
  46325. self._inContent = true;
  46326. };
  46327. el.onmousemove = function (e) {
  46328. e = e || window.event;
  46329. if (!self._enterable) {
  46330. // `pointer-events: none` is set to tooltip content div
  46331. // if `enterable` is set as `false`, and `el.onmousemove`
  46332. // can not be triggered. But in browser that do not
  46333. // support `pointer-events`, we need to do this:
  46334. // Try trigger zrender event to avoid mouse
  46335. // in and out shape too frequently
  46336. var handler = zr.handler;
  46337. var zrViewportRoot = zr.painter.getViewportRoot();
  46338. normalizeEvent(zrViewportRoot, e, true);
  46339. handler.dispatch('mousemove', e);
  46340. }
  46341. };
  46342. el.onmouseleave = function () {
  46343. // set `_inContent` to `false` before `hideLater`
  46344. self._inContent = false;
  46345. if (self._enterable) {
  46346. if (self._show) {
  46347. self.hideLater(self._hideDelay);
  46348. }
  46349. }
  46350. };
  46351. }
  46352. /**
  46353. * Update when tooltip is rendered
  46354. */
  46355. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  46356. // FIXME
  46357. // Move this logic to ec main?
  46358. var container = this._container;
  46359. var stl = container.currentStyle || document.defaultView.getComputedStyle(container);
  46360. var domStyle = container.style;
  46361. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  46362. domStyle.position = 'relative';
  46363. } // move tooltip if chart resized
  46364. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  46365. alwaysShowContent && this._moveIfResized(); // update className
  46366. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  46367. // PENDING
  46368. // this.hide();
  46369. };
  46370. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  46371. clearTimeout(this._hideTimeout);
  46372. clearTimeout(this._longHideTimeout);
  46373. var el = this.el;
  46374. var styleCoord = this._styleCoord;
  46375. var offset = el.offsetHeight / 2;
  46376. nearPointColor = convertToColorString(nearPointColor);
  46377. el.style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // Because of the reason described in:
  46378. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  46379. // we should set initial value to `left` and `top`.
  46380. + ';left:' + styleCoord[0] + 'px;top:' + (styleCoord[1] - offset) + 'px;' + ("border-color: " + nearPointColor + ";") + (tooltipModel.get('extraCssText') || '');
  46381. el.style.display = el.innerHTML ? 'block' : 'none'; // If mouse occasionally move over the tooltip, a mouseout event will be
  46382. // triggered by canvas, and cause some unexpectable result like dragging
  46383. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  46384. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  46385. // scenario.
  46386. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  46387. this._show = true;
  46388. this._firstShow = false;
  46389. this._longHide = false;
  46390. };
  46391. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  46392. if (content == null) {
  46393. return;
  46394. }
  46395. var el = this.el;
  46396. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  46397. content += assembleArrow(tooltipModel.get('backgroundColor'), borderColor, arrowPosition);
  46398. }
  46399. if (isString(content)) {
  46400. el.innerHTML = content;
  46401. } else if (content) {
  46402. // Clear previous
  46403. el.innerHTML = '';
  46404. if (!isArray(content)) {
  46405. content = [content];
  46406. }
  46407. for (var i = 0; i < content.length; i++) {
  46408. if (isDom(content[i]) && content[i].parentNode !== el) {
  46409. el.appendChild(content[i]);
  46410. }
  46411. }
  46412. }
  46413. };
  46414. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  46415. this._enterable = enterable;
  46416. };
  46417. TooltipHTMLContent.prototype.getSize = function () {
  46418. var el = this.el;
  46419. return [el.clientWidth, el.clientHeight];
  46420. };
  46421. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  46422. var styleCoord = this._styleCoord;
  46423. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  46424. if (styleCoord[0] != null && styleCoord[1] != null) {
  46425. var style = this.el.style; // If using float on style, the final width of the dom might
  46426. // keep changing slightly while mouse move. So `toFixed(0)` them.
  46427. style.left = styleCoord[0].toFixed(0) + 'px';
  46428. style.top = styleCoord[1].toFixed(0) + 'px';
  46429. }
  46430. };
  46431. /**
  46432. * when `alwaysShowContent` is true,
  46433. * move the tooltip after chart resized
  46434. */
  46435. TooltipHTMLContent.prototype._moveIfResized = function () {
  46436. // The ratio of left to width
  46437. var ratioX = this._styleCoord[2]; // The ratio of top to height
  46438. var ratioY = this._styleCoord[3];
  46439. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  46440. };
  46441. TooltipHTMLContent.prototype.hide = function () {
  46442. var _this = this;
  46443. this.el.style.visibility = 'hidden';
  46444. this.el.style.opacity = '0';
  46445. this._show = false;
  46446. this._longHideTimeout = setTimeout(function () {
  46447. return _this._longHide = true;
  46448. }, 500);
  46449. };
  46450. TooltipHTMLContent.prototype.hideLater = function (time) {
  46451. if (this._show && !(this._inContent && this._enterable)) {
  46452. if (time) {
  46453. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  46454. this._show = false;
  46455. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  46456. } else {
  46457. this.hide();
  46458. }
  46459. }
  46460. };
  46461. TooltipHTMLContent.prototype.isShow = function () {
  46462. return this._show;
  46463. };
  46464. TooltipHTMLContent.prototype.dispose = function () {
  46465. this.el.parentNode.removeChild(this.el);
  46466. };
  46467. TooltipHTMLContent.prototype.getOuterSize = function () {
  46468. var width = this.el.clientWidth;
  46469. var height = this.el.clientHeight; // Consider browser compatibility.
  46470. // IE8 does not support getComputedStyle.
  46471. if (document.defaultView && document.defaultView.getComputedStyle) {
  46472. var stl = document.defaultView.getComputedStyle(this.el);
  46473. if (stl) {
  46474. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  46475. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  46476. }
  46477. }
  46478. return {
  46479. width: width,
  46480. height: height
  46481. };
  46482. };
  46483. return TooltipHTMLContent;
  46484. }();
  46485. var TooltipRichContent =
  46486. /** @class */
  46487. function () {
  46488. function TooltipRichContent(api) {
  46489. this._show = false;
  46490. this._styleCoord = [0, 0, 0, 0];
  46491. this._enterable = true;
  46492. this._zr = api.getZr();
  46493. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  46494. }
  46495. /**
  46496. * Update when tooltip is rendered
  46497. */
  46498. TooltipRichContent.prototype.update = function (tooltipModel) {
  46499. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  46500. alwaysShowContent && this._moveIfResized();
  46501. };
  46502. TooltipRichContent.prototype.show = function () {
  46503. if (this._hideTimeout) {
  46504. clearTimeout(this._hideTimeout);
  46505. }
  46506. this.el.show();
  46507. this._show = true;
  46508. };
  46509. /**
  46510. * Set tooltip content
  46511. */
  46512. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  46513. if (isObject(content)) {
  46514. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  46515. }
  46516. if (this.el) {
  46517. this._zr.remove(this.el);
  46518. }
  46519. var textStyleModel = tooltipModel.getModel('textStyle');
  46520. this.el = new ZRText({
  46521. style: {
  46522. rich: markupStyleCreator.richTextStyles,
  46523. text: content,
  46524. lineHeight: 22,
  46525. backgroundColor: tooltipModel.get('backgroundColor'),
  46526. borderRadius: tooltipModel.get('borderRadius'),
  46527. borderWidth: 1,
  46528. borderColor: borderColor,
  46529. shadowColor: tooltipModel.get('shadowColor'),
  46530. shadowBlur: tooltipModel.get('shadowBlur'),
  46531. shadowOffsetX: tooltipModel.get('shadowOffsetX'),
  46532. shadowOffsetY: tooltipModel.get('shadowOffsetY'),
  46533. textShadowColor: textStyleModel.get('textShadowColor'),
  46534. textShadowBlur: textStyleModel.get('textShadowBlur') || 0,
  46535. textShadowOffsetX: textStyleModel.get('textShadowOffsetX') || 0,
  46536. textShadowOffsetY: textStyleModel.get('textShadowOffsetY') || 0,
  46537. fill: tooltipModel.get(['textStyle', 'color']),
  46538. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  46539. verticalAlign: 'top',
  46540. align: 'left'
  46541. },
  46542. z: tooltipModel.get('z')
  46543. });
  46544. this._zr.add(this.el);
  46545. var self = this;
  46546. this.el.on('mouseover', function () {
  46547. // clear the timeout in hideLater and keep showing tooltip
  46548. if (self._enterable) {
  46549. clearTimeout(self._hideTimeout);
  46550. self._show = true;
  46551. }
  46552. self._inContent = true;
  46553. });
  46554. this.el.on('mouseout', function () {
  46555. if (self._enterable) {
  46556. if (self._show) {
  46557. self.hideLater(self._hideDelay);
  46558. }
  46559. }
  46560. self._inContent = false;
  46561. });
  46562. };
  46563. TooltipRichContent.prototype.setEnterable = function (enterable) {
  46564. this._enterable = enterable;
  46565. };
  46566. TooltipRichContent.prototype.getSize = function () {
  46567. var el = this.el;
  46568. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  46569. // if overflow, it will be cut. So calculate them accurately.
  46570. var shadowOuterSize = calcShadowOuterSize(el.style);
  46571. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  46572. };
  46573. TooltipRichContent.prototype.moveTo = function (x, y) {
  46574. var el = this.el;
  46575. if (el) {
  46576. var styleCoord = this._styleCoord;
  46577. makeStyleCoord$1(styleCoord, this._zr, x, y);
  46578. x = styleCoord[0];
  46579. y = styleCoord[1];
  46580. var style = el.style;
  46581. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  46582. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  46583. el.x = x + borderWidth + shadowOuterSize.left;
  46584. el.y = y + borderWidth + shadowOuterSize.top;
  46585. el.markRedraw();
  46586. }
  46587. };
  46588. /**
  46589. * when `alwaysShowContent` is true,
  46590. * move the tooltip after chart resized
  46591. */
  46592. TooltipRichContent.prototype._moveIfResized = function () {
  46593. // The ratio of left to width
  46594. var ratioX = this._styleCoord[2]; // The ratio of top to height
  46595. var ratioY = this._styleCoord[3];
  46596. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  46597. };
  46598. TooltipRichContent.prototype.hide = function () {
  46599. if (this.el) {
  46600. this.el.hide();
  46601. }
  46602. this._show = false;
  46603. };
  46604. TooltipRichContent.prototype.hideLater = function (time) {
  46605. if (this._show && !(this._inContent && this._enterable)) {
  46606. if (time) {
  46607. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  46608. this._show = false;
  46609. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  46610. } else {
  46611. this.hide();
  46612. }
  46613. }
  46614. };
  46615. TooltipRichContent.prototype.isShow = function () {
  46616. return this._show;
  46617. };
  46618. TooltipRichContent.prototype.getOuterSize = function () {
  46619. var size = this.getSize();
  46620. return {
  46621. width: size[0],
  46622. height: size[1]
  46623. };
  46624. };
  46625. TooltipRichContent.prototype.dispose = function () {
  46626. this._zr.remove(this.el);
  46627. };
  46628. return TooltipRichContent;
  46629. }();
  46630. function mathMaxWith0(val) {
  46631. return Math.max(0, val);
  46632. }
  46633. function calcShadowOuterSize(style) {
  46634. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  46635. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  46636. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  46637. return {
  46638. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  46639. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  46640. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  46641. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  46642. };
  46643. }
  46644. function makeStyleCoord$1(out, zr, zrX, zrY) {
  46645. out[0] = zrX;
  46646. out[1] = zrY;
  46647. out[2] = out[0] / zr.getWidth();
  46648. out[3] = out[1] / zr.getHeight();
  46649. }
  46650. var bind$2 = bind;
  46651. var each$8 = each;
  46652. var parsePercent$3 = parsePercent$1;
  46653. var proxyRect = new Rect({
  46654. shape: {
  46655. x: -1,
  46656. y: -1,
  46657. width: 2,
  46658. height: 2
  46659. }
  46660. });
  46661. var TooltipView =
  46662. /** @class */
  46663. function (_super) {
  46664. __extends(TooltipView, _super);
  46665. function TooltipView() {
  46666. var _this = _super !== null && _super.apply(this, arguments) || this;
  46667. _this.type = TooltipView.type;
  46668. return _this;
  46669. }
  46670. TooltipView.prototype.init = function (ecModel, api) {
  46671. if (env.node) {
  46672. return;
  46673. }
  46674. var tooltipModel = ecModel.getComponent('tooltip');
  46675. var renderMode = tooltipModel.get('renderMode');
  46676. this._renderMode = getTooltipRenderMode(renderMode);
  46677. this._tooltipContent = this._renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  46678. appendToBody: tooltipModel.get('appendToBody', true)
  46679. });
  46680. };
  46681. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  46682. if (env.node) {
  46683. return;
  46684. } // Reset
  46685. this.group.removeAll();
  46686. this._tooltipModel = tooltipModel;
  46687. this._ecModel = ecModel;
  46688. this._api = api;
  46689. /**
  46690. * @private
  46691. * @type {boolean}
  46692. */
  46693. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  46694. var tooltipContent = this._tooltipContent;
  46695. tooltipContent.update(tooltipModel);
  46696. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  46697. this._initGlobalListener();
  46698. this._keepShow();
  46699. };
  46700. TooltipView.prototype._initGlobalListener = function () {
  46701. var tooltipModel = this._tooltipModel;
  46702. var triggerOn = tooltipModel.get('triggerOn');
  46703. register('itemTooltip', this._api, bind$2(function (currTrigger, e, dispatchAction) {
  46704. // If 'none', it is not controlled by mouse totally.
  46705. if (triggerOn !== 'none') {
  46706. if (triggerOn.indexOf(currTrigger) >= 0) {
  46707. this._tryShow(e, dispatchAction);
  46708. } else if (currTrigger === 'leave') {
  46709. this._hide(dispatchAction);
  46710. }
  46711. }
  46712. }, this));
  46713. };
  46714. TooltipView.prototype._keepShow = function () {
  46715. var tooltipModel = this._tooltipModel;
  46716. var ecModel = this._ecModel;
  46717. var api = this._api; // Try to keep the tooltip show when refreshing
  46718. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  46719. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  46720. // which is not expected.
  46721. && tooltipModel.get('triggerOn') !== 'none') {
  46722. var self_1 = this;
  46723. clearTimeout(this._refreshUpdateTimeout);
  46724. this._refreshUpdateTimeout = setTimeout(function () {
  46725. // Show tip next tick after other charts are rendered
  46726. // In case highlight action has wrong result
  46727. // FIXME
  46728. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  46729. x: self_1._lastX,
  46730. y: self_1._lastY,
  46731. dataByCoordSys: self_1._lastDataByCoordSys
  46732. });
  46733. });
  46734. }
  46735. };
  46736. /**
  46737. * Show tip manually by
  46738. * dispatchAction({
  46739. * type: 'showTip',
  46740. * x: 10,
  46741. * y: 10
  46742. * });
  46743. * Or
  46744. * dispatchAction({
  46745. * type: 'showTip',
  46746. * seriesIndex: 0,
  46747. * dataIndex or dataIndexInside or name
  46748. * });
  46749. *
  46750. * TODO Batch
  46751. */
  46752. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  46753. if (payload.from === this.uid || env.node) {
  46754. return;
  46755. }
  46756. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  46757. this._ticket = ''; // When triggered from axisPointer.
  46758. var dataByCoordSys = payload.dataByCoordSys;
  46759. if (payload.tooltip && payload.x != null && payload.y != null) {
  46760. var el = proxyRect;
  46761. el.x = payload.x;
  46762. el.y = payload.y;
  46763. el.update();
  46764. el.tooltip = payload.tooltip; // Manually show tooltip while view is not using zrender elements.
  46765. this._tryShow({
  46766. offsetX: payload.x,
  46767. offsetY: payload.y,
  46768. target: el
  46769. }, dispatchAction);
  46770. } else if (dataByCoordSys) {
  46771. this._tryShow({
  46772. offsetX: payload.x,
  46773. offsetY: payload.y,
  46774. position: payload.position,
  46775. dataByCoordSys: dataByCoordSys,
  46776. tooltipOption: payload.tooltipOption
  46777. }, dispatchAction);
  46778. } else if (payload.seriesIndex != null) {
  46779. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  46780. return;
  46781. }
  46782. var pointInfo = findPointFromSeries(payload, ecModel);
  46783. var cx = pointInfo.point[0];
  46784. var cy = pointInfo.point[1];
  46785. if (cx != null && cy != null) {
  46786. this._tryShow({
  46787. offsetX: cx,
  46788. offsetY: cy,
  46789. position: payload.position,
  46790. target: pointInfo.el
  46791. }, dispatchAction);
  46792. }
  46793. } else if (payload.x != null && payload.y != null) {
  46794. // FIXME
  46795. // should wrap dispatchAction like `axisPointer/globalListener` ?
  46796. api.dispatchAction({
  46797. type: 'updateAxisPointer',
  46798. x: payload.x,
  46799. y: payload.y
  46800. });
  46801. this._tryShow({
  46802. offsetX: payload.x,
  46803. offsetY: payload.y,
  46804. position: payload.position,
  46805. target: api.getZr().findHover(payload.x, payload.y).target
  46806. }, dispatchAction);
  46807. }
  46808. };
  46809. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  46810. var tooltipContent = this._tooltipContent;
  46811. if (!this._alwaysShowContent && this._tooltipModel) {
  46812. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  46813. }
  46814. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  46815. if (payload.from !== this.uid) {
  46816. this._hide(makeDispatchAction$1(payload, api));
  46817. }
  46818. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  46819. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  46820. // and tooltip.
  46821. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  46822. var seriesIndex = payload.seriesIndex;
  46823. var dataIndex = payload.dataIndex; // @ts-ignore
  46824. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  46825. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  46826. return;
  46827. }
  46828. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  46829. if (!seriesModel) {
  46830. return;
  46831. }
  46832. var data = seriesModel.getData();
  46833. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model, tooltipModel]);
  46834. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  46835. return;
  46836. }
  46837. api.dispatchAction({
  46838. type: 'updateAxisPointer',
  46839. seriesIndex: seriesIndex,
  46840. dataIndex: dataIndex,
  46841. position: payload.position
  46842. });
  46843. return true;
  46844. };
  46845. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  46846. var el = e.target;
  46847. var tooltipModel = this._tooltipModel;
  46848. if (!tooltipModel) {
  46849. return;
  46850. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  46851. this._lastX = e.offsetX;
  46852. this._lastY = e.offsetY;
  46853. var dataByCoordSys = e.dataByCoordSys;
  46854. if (dataByCoordSys && dataByCoordSys.length) {
  46855. this._showAxisTooltip(dataByCoordSys, e);
  46856. } // Always show item tooltip if mouse is on the element with dataIndex
  46857. else if (el && findEventDispatcher(el, function (target) {
  46858. return getECData(target).dataIndex != null;
  46859. }, true)) {
  46860. this._lastDataByCoordSys = null;
  46861. this._showSeriesItemTooltip(e, el, dispatchAction);
  46862. } // Tooltip provided directly. Like legend.
  46863. else if (el && el.tooltip) {
  46864. this._lastDataByCoordSys = null;
  46865. this._showComponentItemTooltip(e, el, dispatchAction);
  46866. } else {
  46867. this._lastDataByCoordSys = null;
  46868. this._hide(dispatchAction);
  46869. }
  46870. };
  46871. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  46872. // showDelay is used in this case: tooltip.enterable is set
  46873. // as true. User intent to move mouse into tooltip and click
  46874. // something. `showDelay` makes it easier to enter the content
  46875. // but tooltip do not move immediately.
  46876. var delay = tooltipModel.get('showDelay');
  46877. cb = bind(cb, this);
  46878. clearTimeout(this._showTimout);
  46879. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  46880. };
  46881. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  46882. var ecModel = this._ecModel;
  46883. var globalTooltipModel = this._tooltipModel;
  46884. var point = [e.offsetX, e.offsetY];
  46885. var singleTooltipModel = buildTooltipModel([e.tooltipOption, globalTooltipModel]);
  46886. var renderMode = this._renderMode;
  46887. var cbParamsList = [];
  46888. var articleMarkup = createTooltipMarkup('section', {
  46889. blocks: [],
  46890. noHeader: true
  46891. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  46892. var markupTextArrLegacy = [];
  46893. var markupStyleCreator = new TooltipMarkupStyleCreator();
  46894. each$8(dataByCoordSys, function (itemCoordSys) {
  46895. each$8(itemCoordSys.dataByAxis, function (axisItem) {
  46896. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  46897. var axisValue = axisItem.value;
  46898. if (!axisModel || axisValue == null) {
  46899. return;
  46900. }
  46901. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  46902. var axisSectionMarkup = createTooltipMarkup('section', {
  46903. header: axisValueLabel,
  46904. noHeader: !trim(axisValueLabel),
  46905. sortBlocks: true,
  46906. blocks: []
  46907. });
  46908. articleMarkup.blocks.push(axisSectionMarkup);
  46909. each(axisItem.seriesDataIndices, function (idxItem) {
  46910. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  46911. var dataIndex = idxItem.dataIndexInside;
  46912. var cbParams = series.getDataParams(dataIndex);
  46913. cbParams.axisDim = axisItem.axisDim;
  46914. cbParams.axisIndex = axisItem.axisIndex;
  46915. cbParams.axisType = axisItem.axisType;
  46916. cbParams.axisId = axisItem.axisId;
  46917. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  46918. value: axisValue
  46919. });
  46920. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  46921. // text in `formatter` callback and use those markers style.
  46922. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  46923. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  46924. if (seriesTooltipResult.markupFragment) {
  46925. axisSectionMarkup.blocks.push(seriesTooltipResult.markupFragment);
  46926. }
  46927. if (seriesTooltipResult.markupText) {
  46928. markupTextArrLegacy.push(seriesTooltipResult.markupText);
  46929. }
  46930. cbParamsList.push(cbParams);
  46931. });
  46932. });
  46933. }); // In most cases, the second axis is displays upper on the first one.
  46934. // So we reverse it to look better.
  46935. articleMarkup.blocks.reverse();
  46936. markupTextArrLegacy.reverse();
  46937. var positionExpr = e.position;
  46938. var orderMode = singleTooltipModel.get('order');
  46939. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  46940. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  46941. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  46942. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  46943. this._showOrMove(singleTooltipModel, function () {
  46944. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  46945. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  46946. } else {
  46947. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  46948. }
  46949. }); // Do not trigger events here, because this branch only be entered
  46950. // from dispatchAction.
  46951. };
  46952. TooltipView.prototype._showSeriesItemTooltip = function (e, el, dispatchAction) {
  46953. var dispatcher = findEventDispatcher(el, function (target) {
  46954. return getECData(target).dataIndex != null;
  46955. }, true);
  46956. var ecModel = this._ecModel;
  46957. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  46958. // Used when mouseover on a element like markPoint or edge
  46959. // In which case, the data is not main data in series.
  46960. var seriesIndex = ecData.seriesIndex;
  46961. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  46962. var dataModel = ecData.dataModel || seriesModel;
  46963. var dataIndex = ecData.dataIndex;
  46964. var dataType = ecData.dataType;
  46965. var data = dataModel.getData(dataType);
  46966. var renderMode = this._renderMode;
  46967. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model, this._tooltipModel]);
  46968. var tooltipTrigger = tooltipModel.get('trigger');
  46969. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  46970. return;
  46971. }
  46972. var params = dataModel.getDataParams(dataIndex, dataType);
  46973. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  46974. // text in `formatter` callback and use those markers style.
  46975. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  46976. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  46977. var orderMode = tooltipModel.get('order');
  46978. var markupText = seriesTooltipResult.markupFragment ? buildTooltipMarkup(seriesTooltipResult.markupFragment, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.markupText;
  46979. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  46980. this._showOrMove(tooltipModel, function () {
  46981. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  46982. }); // FIXME
  46983. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  46984. dispatchAction({
  46985. type: 'showTip',
  46986. dataIndexInside: dataIndex,
  46987. dataIndex: data.getRawIndex(dataIndex),
  46988. seriesIndex: seriesIndex,
  46989. from: this.uid
  46990. });
  46991. };
  46992. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  46993. var tooltipOpt = el.tooltip;
  46994. if (isString(tooltipOpt)) {
  46995. var content = tooltipOpt;
  46996. tooltipOpt = {
  46997. content: content,
  46998. // Fixed formatter
  46999. formatter: content
  47000. };
  47001. }
  47002. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  47003. var defaultHtml = subTooltipModel.get('content');
  47004. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  47005. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  47006. // only works on coordinate system. In fact, we have not found case
  47007. // that requires setting `trigger` nothing on component yet.
  47008. this._showOrMove(subTooltipModel, function () {
  47009. this._showTooltipContent( // Use formatterParams from element defined in component
  47010. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {}, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  47011. }); // If not dispatch showTip, tip may be hide triggered by axis.
  47012. dispatchAction({
  47013. type: 'showTip',
  47014. from: this.uid
  47015. });
  47016. };
  47017. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  47018. // Instead of top level tooltip.
  47019. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  47020. // Reset ticket
  47021. this._ticket = '';
  47022. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  47023. return;
  47024. }
  47025. var tooltipContent = this._tooltipContent;
  47026. var formatter = tooltipModel.get('formatter');
  47027. positionExpr = positionExpr || tooltipModel.get('position');
  47028. var html = defaultHtml;
  47029. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  47030. if (formatter && isString(formatter)) {
  47031. var useUTC = tooltipModel.ecModel.get('useUTC');
  47032. var params0 = isArray(params) ? params[0] : params;
  47033. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  47034. html = formatter;
  47035. if (isTimeAxis) {
  47036. html = format(params0.axisValue, html, useUTC);
  47037. }
  47038. html = formatTpl(html, params, true);
  47039. } else if (isFunction(formatter)) {
  47040. var callback = bind$2(function (cbTicket, html) {
  47041. if (cbTicket === this._ticket) {
  47042. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPoint.color, positionExpr);
  47043. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  47044. }
  47045. }, this);
  47046. this._ticket = asyncTicket;
  47047. html = formatter(params, asyncTicket, callback);
  47048. }
  47049. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPoint.color, positionExpr);
  47050. tooltipContent.show(tooltipModel, nearPoint.color);
  47051. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  47052. };
  47053. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  47054. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  47055. return {
  47056. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  47057. };
  47058. }
  47059. if (!isArray(tooltipDataParams)) {
  47060. return {
  47061. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  47062. };
  47063. }
  47064. };
  47065. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  47066. y, // Mouse y
  47067. content, params, el) {
  47068. var viewWidth = this._api.getWidth();
  47069. var viewHeight = this._api.getHeight();
  47070. positionExpr = positionExpr || tooltipModel.get('position');
  47071. var contentSize = content.getSize();
  47072. var align = tooltipModel.get('align');
  47073. var vAlign = tooltipModel.get('verticalAlign');
  47074. var rect = el && el.getBoundingRect().clone();
  47075. el && rect.applyTransform(el.transform);
  47076. if (isFunction(positionExpr)) {
  47077. // Callback of position can be an array or a string specify the position
  47078. positionExpr = positionExpr([x, y], params, content.el, rect, {
  47079. viewSize: [viewWidth, viewHeight],
  47080. contentSize: contentSize.slice()
  47081. });
  47082. }
  47083. if (isArray(positionExpr)) {
  47084. x = parsePercent$3(positionExpr[0], viewWidth);
  47085. y = parsePercent$3(positionExpr[1], viewHeight);
  47086. } else if (isObject(positionExpr)) {
  47087. var boxLayoutPosition = positionExpr;
  47088. boxLayoutPosition.width = contentSize[0];
  47089. boxLayoutPosition.height = contentSize[1];
  47090. var layoutRect = getLayoutRect(boxLayoutPosition, {
  47091. width: viewWidth,
  47092. height: viewHeight
  47093. });
  47094. x = layoutRect.x;
  47095. y = layoutRect.y;
  47096. align = null; // When positionExpr is left/top/right/bottom,
  47097. // align and verticalAlign will not work.
  47098. vAlign = null;
  47099. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  47100. else if (isString(positionExpr) && el) {
  47101. var pos = calcTooltipPosition(positionExpr, rect, contentSize);
  47102. x = pos[0];
  47103. y = pos[1];
  47104. } else {
  47105. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  47106. x = pos[0];
  47107. y = pos[1];
  47108. }
  47109. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  47110. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  47111. if (shouldTooltipConfine(tooltipModel)) {
  47112. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  47113. x = pos[0];
  47114. y = pos[1];
  47115. }
  47116. content.moveTo(x, y);
  47117. }; // FIXME
  47118. // Should we remove this but leave this to user?
  47119. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys) {
  47120. var lastCoordSys = this._lastDataByCoordSys;
  47121. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  47122. contentNotChanged && each$8(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  47123. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  47124. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  47125. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  47126. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  47127. contentNotChanged && each$8(lastDataByAxis, function (lastItem, indexAxis) {
  47128. var thisItem = thisDataByAxis[indexAxis] || {};
  47129. var lastIndices = lastItem.seriesDataIndices || [];
  47130. var newIndices = thisItem.seriesDataIndices || [];
  47131. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  47132. contentNotChanged && each$8(lastIndices, function (lastIdxItem, j) {
  47133. var newIdxItem = newIndices[j];
  47134. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  47135. });
  47136. });
  47137. });
  47138. this._lastDataByCoordSys = dataByCoordSys;
  47139. return !!contentNotChanged;
  47140. };
  47141. TooltipView.prototype._hide = function (dispatchAction) {
  47142. // Do not directly hideLater here, because this behavior may be prevented
  47143. // in dispatchAction when showTip is dispatched.
  47144. // FIXME
  47145. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  47146. this._lastDataByCoordSys = null;
  47147. dispatchAction({
  47148. type: 'hideTip',
  47149. from: this.uid
  47150. });
  47151. };
  47152. TooltipView.prototype.dispose = function (ecModel, api) {
  47153. if (env.node) {
  47154. return;
  47155. }
  47156. this._tooltipContent.dispose();
  47157. unregister('itemTooltip', api);
  47158. };
  47159. TooltipView.type = 'tooltip';
  47160. return TooltipView;
  47161. }(ComponentView);
  47162. /**
  47163. * From top to bottom. (the last one should be globalTooltipModel);
  47164. */
  47165. function buildTooltipModel(modelCascade) {
  47166. // Last is always tooltip model.
  47167. var resultModel = modelCascade.pop();
  47168. while (modelCascade.length) {
  47169. var tooltipOpt = modelCascade.pop();
  47170. if (tooltipOpt) {
  47171. if (tooltipOpt instanceof Model) {
  47172. tooltipOpt = tooltipOpt.get('tooltip', true);
  47173. } // In each data item tooltip can be simply write:
  47174. // {
  47175. // value: 10,
  47176. // tooltip: 'Something you need to know'
  47177. // }
  47178. if (isString(tooltipOpt)) {
  47179. tooltipOpt = {
  47180. formatter: tooltipOpt
  47181. };
  47182. }
  47183. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  47184. }
  47185. }
  47186. return resultModel;
  47187. }
  47188. function makeDispatchAction$1(payload, api) {
  47189. return payload.dispatchAction || bind(api.dispatchAction, api);
  47190. }
  47191. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  47192. var size = content.getOuterSize();
  47193. var width = size.width;
  47194. var height = size.height;
  47195. if (gapH != null) {
  47196. // Add extra 2 pixels for this case:
  47197. // At present the "values" in defaut tooltip are using CSS `float: right`.
  47198. // When the right edge of the tooltip box is on the right side of the
  47199. // viewport, the `float` layout might push the "values" to the second line.
  47200. if (x + width + gapH + 2 > viewWidth) {
  47201. x -= width + gapH;
  47202. } else {
  47203. x += gapH;
  47204. }
  47205. }
  47206. if (gapV != null) {
  47207. if (y + height + gapV > viewHeight) {
  47208. y -= height + gapV;
  47209. } else {
  47210. y += gapV;
  47211. }
  47212. }
  47213. return [x, y];
  47214. }
  47215. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  47216. var size = content.getOuterSize();
  47217. var width = size.width;
  47218. var height = size.height;
  47219. x = Math.min(x + width, viewWidth) - width;
  47220. y = Math.min(y + height, viewHeight) - height;
  47221. x = Math.max(x, 0);
  47222. y = Math.max(y, 0);
  47223. return [x, y];
  47224. }
  47225. function calcTooltipPosition(position, rect, contentSize) {
  47226. var domWidth = contentSize[0];
  47227. var domHeight = contentSize[1];
  47228. var gap = 10;
  47229. var offset = 5;
  47230. var x = 0;
  47231. var y = 0;
  47232. var rectWidth = rect.width;
  47233. var rectHeight = rect.height;
  47234. switch (position) {
  47235. case 'inside':
  47236. x = rect.x + rectWidth / 2 - domWidth / 2;
  47237. y = rect.y + rectHeight / 2 - domHeight / 2;
  47238. break;
  47239. case 'top':
  47240. x = rect.x + rectWidth / 2 - domWidth / 2;
  47241. y = rect.y - domHeight - gap;
  47242. break;
  47243. case 'bottom':
  47244. x = rect.x + rectWidth / 2 - domWidth / 2;
  47245. y = rect.y + rectHeight + gap;
  47246. break;
  47247. case 'left':
  47248. x = rect.x - domWidth - gap - offset;
  47249. y = rect.y + rectHeight / 2 - domHeight / 2;
  47250. break;
  47251. case 'right':
  47252. x = rect.x + rectWidth + gap + offset;
  47253. y = rect.y + rectHeight / 2 - domHeight / 2;
  47254. }
  47255. return [x, y];
  47256. }
  47257. function isCenterAlign(align) {
  47258. return align === 'center' || align === 'middle';
  47259. }
  47260. function install$c(registers) {
  47261. use(install$7);
  47262. registers.registerComponentModel(TooltipModel);
  47263. registers.registerComponentView(TooltipView);
  47264. /**
  47265. * @action
  47266. * @property {string} type
  47267. * @property {number} seriesIndex
  47268. * @property {number} dataIndex
  47269. * @property {number} [x]
  47270. * @property {number} [y]
  47271. */
  47272. registers.registerAction({
  47273. type: 'showTip',
  47274. event: 'showTip',
  47275. update: 'tooltip:manuallyShowTip'
  47276. }, // noop
  47277. function () {});
  47278. registers.registerAction({
  47279. type: 'hideTip',
  47280. event: 'hideTip',
  47281. update: 'tooltip:manuallyHideTip'
  47282. }, // noop
  47283. function () {});
  47284. }
  47285. var TitleModel =
  47286. /** @class */
  47287. function (_super) {
  47288. __extends(TitleModel, _super);
  47289. function TitleModel() {
  47290. var _this = _super !== null && _super.apply(this, arguments) || this;
  47291. _this.type = TitleModel.type;
  47292. _this.layoutMode = {
  47293. type: 'box',
  47294. ignoreSize: true
  47295. };
  47296. return _this;
  47297. }
  47298. TitleModel.type = 'title';
  47299. TitleModel.defaultOption = {
  47300. zlevel: 0,
  47301. z: 6,
  47302. show: true,
  47303. text: '',
  47304. target: 'blank',
  47305. subtext: '',
  47306. subtarget: 'blank',
  47307. left: 0,
  47308. top: 0,
  47309. backgroundColor: 'rgba(0,0,0,0)',
  47310. borderColor: '#ccc',
  47311. borderWidth: 0,
  47312. padding: 5,
  47313. itemGap: 10,
  47314. textStyle: {
  47315. fontSize: 18,
  47316. fontWeight: 'bold',
  47317. color: '#464646'
  47318. },
  47319. subtextStyle: {
  47320. fontSize: 12,
  47321. color: '#6E7079'
  47322. }
  47323. };
  47324. return TitleModel;
  47325. }(ComponentModel); // View
  47326. var TitleView =
  47327. /** @class */
  47328. function (_super) {
  47329. __extends(TitleView, _super);
  47330. function TitleView() {
  47331. var _this = _super !== null && _super.apply(this, arguments) || this;
  47332. _this.type = TitleView.type;
  47333. return _this;
  47334. }
  47335. TitleView.prototype.render = function (titleModel, ecModel, api) {
  47336. this.group.removeAll();
  47337. if (!titleModel.get('show')) {
  47338. return;
  47339. }
  47340. var group = this.group;
  47341. var textStyleModel = titleModel.getModel('textStyle');
  47342. var subtextStyleModel = titleModel.getModel('subtextStyle');
  47343. var textAlign = titleModel.get('textAlign');
  47344. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  47345. var textEl = new ZRText({
  47346. style: createTextStyle(textStyleModel, {
  47347. text: titleModel.get('text'),
  47348. fill: textStyleModel.getTextColor()
  47349. }, {
  47350. disableBox: true
  47351. }),
  47352. z2: 10
  47353. });
  47354. var textRect = textEl.getBoundingRect();
  47355. var subText = titleModel.get('subtext');
  47356. var subTextEl = new ZRText({
  47357. style: createTextStyle(subtextStyleModel, {
  47358. text: subText,
  47359. fill: subtextStyleModel.getTextColor(),
  47360. y: textRect.height + titleModel.get('itemGap'),
  47361. verticalAlign: 'top'
  47362. }, {
  47363. disableBox: true
  47364. }),
  47365. z2: 10
  47366. });
  47367. var link = titleModel.get('link');
  47368. var sublink = titleModel.get('sublink');
  47369. var triggerEvent = titleModel.get('triggerEvent', true);
  47370. textEl.silent = !link && !triggerEvent;
  47371. subTextEl.silent = !sublink && !triggerEvent;
  47372. if (link) {
  47373. textEl.on('click', function () {
  47374. windowOpen(link, '_' + titleModel.get('target'));
  47375. });
  47376. }
  47377. if (sublink) {
  47378. subTextEl.on('click', function () {
  47379. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  47380. });
  47381. }
  47382. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  47383. componentType: 'title',
  47384. componentIndex: titleModel.componentIndex
  47385. } : null;
  47386. group.add(textEl);
  47387. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  47388. var groupRect = group.getBoundingRect();
  47389. var layoutOption = titleModel.getBoxLayoutParams();
  47390. layoutOption.width = groupRect.width;
  47391. layoutOption.height = groupRect.height;
  47392. var layoutRect = getLayoutRect(layoutOption, {
  47393. width: api.getWidth(),
  47394. height: api.getHeight()
  47395. }, titleModel.get('padding')); // Adjust text align based on position
  47396. if (!textAlign) {
  47397. // Align left if title is on the left. center and right is same
  47398. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  47399. if (textAlign === 'middle') {
  47400. textAlign = 'center';
  47401. } // Adjust layout by text align
  47402. if (textAlign === 'right') {
  47403. layoutRect.x += layoutRect.width;
  47404. } else if (textAlign === 'center') {
  47405. layoutRect.x += layoutRect.width / 2;
  47406. }
  47407. }
  47408. if (!textVerticalAlign) {
  47409. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  47410. if (textVerticalAlign === 'center') {
  47411. textVerticalAlign = 'middle';
  47412. }
  47413. if (textVerticalAlign === 'bottom') {
  47414. layoutRect.y += layoutRect.height;
  47415. } else if (textVerticalAlign === 'middle') {
  47416. layoutRect.y += layoutRect.height / 2;
  47417. }
  47418. textVerticalAlign = textVerticalAlign || 'top';
  47419. }
  47420. group.x = layoutRect.x;
  47421. group.y = layoutRect.y;
  47422. group.markRedraw();
  47423. var alignStyle = {
  47424. align: textAlign,
  47425. verticalAlign: textVerticalAlign
  47426. };
  47427. textEl.setStyle(alignStyle);
  47428. subTextEl.setStyle(alignStyle); // Render background
  47429. // Get groupRect again because textAlign has been changed
  47430. groupRect = group.getBoundingRect();
  47431. var padding = layoutRect.margin;
  47432. var style = titleModel.getItemStyle(['color', 'opacity']);
  47433. style.fill = titleModel.get('backgroundColor');
  47434. var rect = new Rect({
  47435. shape: {
  47436. x: groupRect.x - padding[3],
  47437. y: groupRect.y - padding[0],
  47438. width: groupRect.width + padding[1] + padding[3],
  47439. height: groupRect.height + padding[0] + padding[2],
  47440. r: titleModel.get('borderRadius')
  47441. },
  47442. style: style,
  47443. subPixelOptimize: true,
  47444. silent: true
  47445. });
  47446. group.add(rect);
  47447. };
  47448. TitleView.type = 'title';
  47449. return TitleView;
  47450. }(ComponentView);
  47451. function install$d(registers) {
  47452. registers.registerComponentModel(TitleModel);
  47453. registers.registerComponentView(TitleView);
  47454. }
  47455. function fillLabel(opt) {
  47456. defaultEmphasis(opt, 'label', ['show']);
  47457. } // { [componentType]: MarkerModel }
  47458. var inner$b = makeInner();
  47459. var MarkerModel =
  47460. /** @class */
  47461. function (_super) {
  47462. __extends(MarkerModel, _super);
  47463. function MarkerModel() {
  47464. var _this = _super !== null && _super.apply(this, arguments) || this;
  47465. _this.type = MarkerModel.type;
  47466. /**
  47467. * If marker model is created by self from series
  47468. */
  47469. _this.createdBySelf = false;
  47470. return _this;
  47471. }
  47472. /**
  47473. * @overrite
  47474. */
  47475. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  47476. if ("development" !== 'production') {
  47477. if (this.type === 'marker') {
  47478. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  47479. }
  47480. }
  47481. this.mergeDefaultAndTheme(option, ecModel);
  47482. this._mergeOption(option, ecModel, false, true);
  47483. };
  47484. MarkerModel.prototype.isAnimationEnabled = function () {
  47485. if (env.node) {
  47486. return false;
  47487. }
  47488. var hostSeries = this.__hostSeries;
  47489. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  47490. };
  47491. /**
  47492. * @overrite
  47493. */
  47494. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  47495. this._mergeOption(newOpt, ecModel, false, false);
  47496. };
  47497. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  47498. var componentType = this.mainType;
  47499. if (!createdBySelf) {
  47500. ecModel.eachSeries(function (seriesModel) {
  47501. // mainType can be markPoint, markLine, markArea
  47502. var markerOpt = seriesModel.get(this.mainType, true);
  47503. var markerModel = inner$b(seriesModel)[componentType];
  47504. if (!markerOpt || !markerOpt.data) {
  47505. inner$b(seriesModel)[componentType] = null;
  47506. return;
  47507. }
  47508. if (!markerModel) {
  47509. if (isInit) {
  47510. // Default label emphasis `position` and `show`
  47511. fillLabel(markerOpt);
  47512. }
  47513. each(markerOpt.data, function (item) {
  47514. // FIXME Overwrite fillLabel method ?
  47515. if (item instanceof Array) {
  47516. fillLabel(item[0]);
  47517. fillLabel(item[1]);
  47518. } else {
  47519. fillLabel(item);
  47520. }
  47521. });
  47522. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  47523. // markerOpt, this, ecModel
  47524. // );
  47525. extend(markerModel, {
  47526. mainType: this.mainType,
  47527. // Use the same series index and name
  47528. seriesIndex: seriesModel.seriesIndex,
  47529. name: seriesModel.name,
  47530. createdBySelf: true
  47531. });
  47532. markerModel.__hostSeries = seriesModel;
  47533. } else {
  47534. markerModel._mergeOption(markerOpt, ecModel, true);
  47535. }
  47536. inner$b(seriesModel)[componentType] = markerModel;
  47537. }, this);
  47538. }
  47539. };
  47540. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  47541. var data = this.getData();
  47542. var value = this.getRawValue(dataIndex);
  47543. var itemName = data.getName(dataIndex);
  47544. return createTooltipMarkup('section', {
  47545. header: this.name,
  47546. blocks: [createTooltipMarkup('nameValue', {
  47547. name: itemName,
  47548. value: value,
  47549. noName: !itemName,
  47550. noValue: value == null
  47551. })]
  47552. });
  47553. };
  47554. MarkerModel.prototype.getData = function () {
  47555. return this._data;
  47556. };
  47557. MarkerModel.prototype.setData = function (data) {
  47558. this._data = data;
  47559. };
  47560. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  47561. componentType) {
  47562. return inner$b(seriesModel)[componentType];
  47563. };
  47564. MarkerModel.type = 'marker';
  47565. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  47566. return MarkerModel;
  47567. }(ComponentModel);
  47568. mixin(MarkerModel, DataFormatMixin.prototype);
  47569. var MarkPointModel =
  47570. /** @class */
  47571. function (_super) {
  47572. __extends(MarkPointModel, _super);
  47573. function MarkPointModel() {
  47574. var _this = _super !== null && _super.apply(this, arguments) || this;
  47575. _this.type = MarkPointModel.type;
  47576. return _this;
  47577. }
  47578. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  47579. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  47580. };
  47581. MarkPointModel.type = 'markPoint';
  47582. MarkPointModel.defaultOption = {
  47583. zlevel: 0,
  47584. z: 5,
  47585. symbol: 'pin',
  47586. symbolSize: 50,
  47587. //symbolRotate: 0,
  47588. //symbolOffset: [0, 0]
  47589. tooltip: {
  47590. trigger: 'item'
  47591. },
  47592. label: {
  47593. show: true,
  47594. position: 'inside'
  47595. },
  47596. itemStyle: {
  47597. borderWidth: 2
  47598. },
  47599. emphasis: {
  47600. label: {
  47601. show: true
  47602. }
  47603. }
  47604. };
  47605. return MarkPointModel;
  47606. }(MarkerModel);
  47607. function hasXOrY(item) {
  47608. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  47609. }
  47610. function hasXAndY(item) {
  47611. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  47612. } // Make it simple, do not visit all stacked value to count precision.
  47613. // function getPrecision(data, valueAxisDim, dataIndex) {
  47614. // let precision = -1;
  47615. // let stackedDim = data.mapDimension(valueAxisDim);
  47616. // do {
  47617. // precision = Math.max(
  47618. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  47619. // precision
  47620. // );
  47621. // let stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  47622. // if (stackedOnSeries) {
  47623. // let byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  47624. // data = stackedOnSeries.getData();
  47625. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  47626. // stackedDim = data.getCalculationInfo('stackedDimension');
  47627. // }
  47628. // else {
  47629. // data = null;
  47630. // }
  47631. // } while (data);
  47632. // return precision;
  47633. // }
  47634. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  47635. var coordArr = [];
  47636. var stacked = isDimensionStacked(data, targetDataDim
  47637. /*, otherDataDim*/
  47638. );
  47639. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  47640. var value = numCalculate(data, calcDataDim, markerType);
  47641. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  47642. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  47643. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  47644. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  47645. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  47646. precision = Math.min(precision, 20);
  47647. if (precision >= 0) {
  47648. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  47649. }
  47650. return [coordArr, coordArrValue];
  47651. } // TODO Specified percent
  47652. var markerTypeCalculator = {
  47653. min: curry(markerTypeCalculatorWithExtent, 'min'),
  47654. max: curry(markerTypeCalculatorWithExtent, 'max'),
  47655. average: curry(markerTypeCalculatorWithExtent, 'average'),
  47656. median: curry(markerTypeCalculatorWithExtent, 'median')
  47657. };
  47658. /**
  47659. * Transform markPoint data item to format used in List by do the following
  47660. * 1. Calculate statistic like `max`, `min`, `average`
  47661. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  47662. * @param {module:echarts/model/Series} seriesModel
  47663. * @param {module:echarts/coord/*} [coordSys]
  47664. * @param {Object} item
  47665. * @return {Object}
  47666. */
  47667. function dataTransform(seriesModel, item) {
  47668. var data = seriesModel.getData();
  47669. var coordSys = seriesModel.coordinateSystem; // 1. If not specify the position with pixel directly
  47670. // 2. If `coord` is not a data array. Which uses `xAxis`,
  47671. // `yAxis` to specify the coord on each dimension
  47672. // parseFloat first because item.x and item.y can be percent string like '20%'
  47673. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  47674. var dims = coordSys.dimensions;
  47675. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  47676. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  47677. item = clone(item);
  47678. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  47679. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  47680. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  47681. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  47682. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  47683. // let item use the value without stack.
  47684. item.value = coordInfo[1];
  47685. } else {
  47686. // FIXME Only has one of xAxis and yAxis.
  47687. var coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis]; // Each coord support max, min, average
  47688. for (var i = 0; i < 2; i++) {
  47689. if (markerTypeCalculator[coord[i]]) {
  47690. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  47691. }
  47692. }
  47693. item.coord = coord;
  47694. }
  47695. }
  47696. return item;
  47697. }
  47698. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  47699. var ret = {};
  47700. if (item.valueIndex != null || item.valueDim != null) {
  47701. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  47702. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  47703. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  47704. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  47705. } else {
  47706. ret.baseAxis = seriesModel.getBaseAxis();
  47707. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  47708. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  47709. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  47710. }
  47711. return ret;
  47712. }
  47713. function dataDimToCoordDim(seriesModel, dataDim) {
  47714. var data = seriesModel.getData();
  47715. var dimensions = data.dimensions;
  47716. dataDim = data.getDimension(dataDim);
  47717. for (var i = 0; i < dimensions.length; i++) {
  47718. var dimItem = data.getDimensionInfo(dimensions[i]);
  47719. if (dimItem.name === dataDim) {
  47720. return dimItem.coordDim;
  47721. }
  47722. }
  47723. }
  47724. /**
  47725. * Filter data which is out of coordinateSystem range
  47726. * [dataFilter description]
  47727. */
  47728. function dataFilter$1( // Currently only polar and cartesian has containData.
  47729. coordSys, item) {
  47730. // Alwalys return true if there is no coordSys
  47731. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  47732. }
  47733. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  47734. // x, y, radius, angle
  47735. if (dimIndex < 2) {
  47736. return item.coord && item.coord[dimIndex];
  47737. }
  47738. return item.value;
  47739. }
  47740. function numCalculate(data, valueDataDim, type) {
  47741. if (type === 'average') {
  47742. var sum_1 = 0;
  47743. var count_1 = 0;
  47744. data.each(valueDataDim, function (val, idx) {
  47745. if (!isNaN(val)) {
  47746. sum_1 += val;
  47747. count_1++;
  47748. }
  47749. });
  47750. return sum_1 / count_1;
  47751. } else if (type === 'median') {
  47752. return data.getMedian(valueDataDim);
  47753. } else {
  47754. // max & min
  47755. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  47756. }
  47757. }
  47758. var inner$c = makeInner();
  47759. var MarkerView =
  47760. /** @class */
  47761. function (_super) {
  47762. __extends(MarkerView, _super);
  47763. function MarkerView() {
  47764. var _this = _super !== null && _super.apply(this, arguments) || this;
  47765. _this.type = MarkerView.type;
  47766. return _this;
  47767. }
  47768. MarkerView.prototype.init = function () {
  47769. this.markerGroupMap = createHashMap();
  47770. };
  47771. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  47772. var _this = this;
  47773. var markerGroupMap = this.markerGroupMap;
  47774. markerGroupMap.each(function (item) {
  47775. inner$c(item).keep = false;
  47776. });
  47777. ecModel.eachSeries(function (seriesModel) {
  47778. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  47779. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  47780. });
  47781. markerGroupMap.each(function (item) {
  47782. !inner$c(item).keep && _this.group.remove(item.group);
  47783. });
  47784. };
  47785. MarkerView.prototype.markKeep = function (drawGroup) {
  47786. inner$c(drawGroup).keep = true;
  47787. };
  47788. MarkerView.prototype.blurSeries = function (seriesModelList) {
  47789. var _this = this;
  47790. each(seriesModelList, function (seriesModel) {
  47791. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  47792. if (markerModel) {
  47793. var data = markerModel.getData();
  47794. data.eachItemGraphicEl(function (el) {
  47795. if (el) {
  47796. enterBlur(el);
  47797. }
  47798. });
  47799. }
  47800. });
  47801. };
  47802. MarkerView.type = 'marker';
  47803. return MarkerView;
  47804. }(ComponentView);
  47805. function updateMarkerLayout(mpData, seriesModel, api) {
  47806. var coordSys = seriesModel.coordinateSystem;
  47807. mpData.each(function (idx) {
  47808. var itemModel = mpData.getItemModel(idx);
  47809. var point;
  47810. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  47811. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  47812. if (!isNaN(xPx) && !isNaN(yPx)) {
  47813. point = [xPx, yPx];
  47814. } // Chart like bar may have there own marker positioning logic
  47815. else if (seriesModel.getMarkerPosition) {
  47816. // Use the getMarkerPoisition
  47817. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  47818. } else if (coordSys) {
  47819. var x = mpData.get(coordSys.dimensions[0], idx);
  47820. var y = mpData.get(coordSys.dimensions[1], idx);
  47821. point = coordSys.dataToPoint([x, y]);
  47822. } // Use x, y if has any
  47823. if (!isNaN(xPx)) {
  47824. point[0] = xPx;
  47825. }
  47826. if (!isNaN(yPx)) {
  47827. point[1] = yPx;
  47828. }
  47829. mpData.setItemLayout(idx, point);
  47830. });
  47831. }
  47832. var MarkPointView =
  47833. /** @class */
  47834. function (_super) {
  47835. __extends(MarkPointView, _super);
  47836. function MarkPointView() {
  47837. var _this = _super !== null && _super.apply(this, arguments) || this;
  47838. _this.type = MarkPointView.type;
  47839. return _this;
  47840. }
  47841. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  47842. ecModel.eachSeries(function (seriesModel) {
  47843. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  47844. if (mpModel) {
  47845. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  47846. this.markerGroupMap.get(seriesModel.id).updateLayout();
  47847. }
  47848. }, this);
  47849. };
  47850. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  47851. var coordSys = seriesModel.coordinateSystem;
  47852. var seriesId = seriesModel.id;
  47853. var seriesData = seriesModel.getData();
  47854. var symbolDrawMap = this.markerGroupMap;
  47855. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  47856. var mpData = createList$1(coordSys, seriesModel, mpModel); // FIXME
  47857. mpModel.setData(mpData);
  47858. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  47859. mpData.each(function (idx) {
  47860. var itemModel = mpData.getItemModel(idx);
  47861. var symbol = itemModel.getShallow('symbol');
  47862. var symbolSize = itemModel.getShallow('symbolSize');
  47863. var symbolRotate = itemModel.getShallow('symbolRotate');
  47864. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate)) {
  47865. var rawIdx = mpModel.getRawValue(idx);
  47866. var dataParams = mpModel.getDataParams(idx);
  47867. if (isFunction(symbol)) {
  47868. symbol = symbol(rawIdx, dataParams);
  47869. }
  47870. if (isFunction(symbolSize)) {
  47871. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  47872. symbolSize = symbolSize(rawIdx, dataParams);
  47873. }
  47874. if (isFunction(symbolRotate)) {
  47875. symbolRotate = symbolRotate(rawIdx, dataParams);
  47876. }
  47877. }
  47878. var style = itemModel.getModel('itemStyle').getItemStyle();
  47879. var color = getVisualFromData(seriesData, 'color');
  47880. if (!style.fill) {
  47881. style.fill = color;
  47882. }
  47883. mpData.setItemVisual(idx, {
  47884. symbol: symbol,
  47885. symbolSize: symbolSize,
  47886. symbolRotate: symbolRotate,
  47887. style: style
  47888. });
  47889. }); // TODO Text are wrong
  47890. symbolDraw.updateData(mpData);
  47891. this.group.add(symbolDraw.group); // Set host model for tooltip
  47892. // FIXME
  47893. mpData.eachItemGraphicEl(function (el) {
  47894. el.traverse(function (child) {
  47895. getECData(child).dataModel = mpModel;
  47896. });
  47897. });
  47898. this.markKeep(symbolDraw);
  47899. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  47900. };
  47901. MarkPointView.type = 'markPoint';
  47902. return MarkPointView;
  47903. }(MarkerView);
  47904. function createList$1(coordSys, seriesModel, mpModel) {
  47905. var coordDimsInfos;
  47906. if (coordSys) {
  47907. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  47908. 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
  47909. return defaults({
  47910. name: coordDim
  47911. }, info);
  47912. });
  47913. } else {
  47914. coordDimsInfos = [{
  47915. name: 'value',
  47916. type: 'float'
  47917. }];
  47918. }
  47919. var mpData = new List(coordDimsInfos, mpModel);
  47920. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  47921. if (coordSys) {
  47922. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  47923. }
  47924. mpData.initData(dataOpt, null, coordSys ? dimValueGetter : function (item) {
  47925. return item.value;
  47926. });
  47927. return mpData;
  47928. }
  47929. function install$e(registers) {
  47930. registers.registerComponentModel(MarkPointModel);
  47931. registers.registerComponentView(MarkPointView);
  47932. registers.registerPreprocessor(function (opt) {
  47933. // Make sure markPoint component is enabled
  47934. opt.markPoint = opt.markPoint || {};
  47935. });
  47936. }
  47937. var MarkLineModel =
  47938. /** @class */
  47939. function (_super) {
  47940. __extends(MarkLineModel, _super);
  47941. function MarkLineModel() {
  47942. var _this = _super !== null && _super.apply(this, arguments) || this;
  47943. _this.type = MarkLineModel.type;
  47944. return _this;
  47945. }
  47946. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  47947. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  47948. };
  47949. MarkLineModel.type = 'markLine';
  47950. MarkLineModel.defaultOption = {
  47951. zlevel: 0,
  47952. z: 5,
  47953. symbol: ['circle', 'arrow'],
  47954. symbolSize: [8, 16],
  47955. //symbolRotate: 0,
  47956. precision: 2,
  47957. tooltip: {
  47958. trigger: 'item'
  47959. },
  47960. label: {
  47961. show: true,
  47962. position: 'end',
  47963. distance: 5
  47964. },
  47965. lineStyle: {
  47966. type: 'dashed'
  47967. },
  47968. emphasis: {
  47969. label: {
  47970. show: true
  47971. },
  47972. lineStyle: {
  47973. width: 3
  47974. }
  47975. },
  47976. animationEasing: 'linear'
  47977. };
  47978. return MarkLineModel;
  47979. }(MarkerModel);
  47980. var straightLineProto = Line.prototype;
  47981. var bezierCurveProto = BezierCurve.prototype;
  47982. var StraightLineShape =
  47983. /** @class */
  47984. function () {
  47985. function StraightLineShape() {
  47986. // Start point
  47987. this.x1 = 0;
  47988. this.y1 = 0; // End point
  47989. this.x2 = 0;
  47990. this.y2 = 0;
  47991. this.percent = 1;
  47992. }
  47993. return StraightLineShape;
  47994. }();
  47995. var CurveShape =
  47996. /** @class */
  47997. function (_super) {
  47998. __extends(CurveShape, _super);
  47999. function CurveShape() {
  48000. return _super !== null && _super.apply(this, arguments) || this;
  48001. }
  48002. return CurveShape;
  48003. }(StraightLineShape);
  48004. function isStraightLine(shape) {
  48005. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  48006. }
  48007. var ECLinePath =
  48008. /** @class */
  48009. function (_super) {
  48010. __extends(ECLinePath, _super);
  48011. function ECLinePath(opts) {
  48012. var _this = _super.call(this, opts) || this;
  48013. _this.type = 'ec-line';
  48014. return _this;
  48015. }
  48016. ECLinePath.prototype.getDefaultStyle = function () {
  48017. return {
  48018. stroke: '#000',
  48019. fill: null
  48020. };
  48021. };
  48022. ECLinePath.prototype.getDefaultShape = function () {
  48023. return new StraightLineShape();
  48024. };
  48025. ECLinePath.prototype.buildPath = function (ctx, shape) {
  48026. if (isStraightLine(shape)) {
  48027. straightLineProto.buildPath.call(this, ctx, shape);
  48028. } else {
  48029. bezierCurveProto.buildPath.call(this, ctx, shape);
  48030. }
  48031. };
  48032. ECLinePath.prototype.pointAt = function (t) {
  48033. if (isStraightLine(this.shape)) {
  48034. return straightLineProto.pointAt.call(this, t);
  48035. } else {
  48036. return bezierCurveProto.pointAt.call(this, t);
  48037. }
  48038. };
  48039. ECLinePath.prototype.tangentAt = function (t) {
  48040. var shape = this.shape;
  48041. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  48042. return normalize(p, p);
  48043. };
  48044. return ECLinePath;
  48045. }(Path);
  48046. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  48047. function makeSymbolTypeKey(symbolCategory) {
  48048. return '_' + symbolCategory + 'Type';
  48049. }
  48050. /**
  48051. * @inner
  48052. */
  48053. function createSymbol$1(name, lineData, idx) {
  48054. var symbolType = lineData.getItemVisual(idx, name);
  48055. if (!symbolType || symbolType === 'none') {
  48056. return;
  48057. }
  48058. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  48059. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  48060. var symbolSizeArr = isArray(symbolSize) ? symbolSize : [symbolSize, symbolSize];
  48061. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2, -symbolSizeArr[1] / 2, symbolSizeArr[0], symbolSizeArr[1]);
  48062. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  48063. symbolPath.name = name;
  48064. return symbolPath;
  48065. }
  48066. function createLine(points) {
  48067. var line = new ECLinePath({
  48068. name: 'line',
  48069. subPixelOptimize: true
  48070. });
  48071. setLinePoints(line.shape, points);
  48072. return line;
  48073. }
  48074. function setLinePoints(targetShape, points) {
  48075. targetShape.x1 = points[0][0];
  48076. targetShape.y1 = points[0][1];
  48077. targetShape.x2 = points[1][0];
  48078. targetShape.y2 = points[1][1];
  48079. targetShape.percent = 1;
  48080. var cp1 = points[2];
  48081. if (cp1) {
  48082. targetShape.cpx1 = cp1[0];
  48083. targetShape.cpy1 = cp1[1];
  48084. } else {
  48085. targetShape.cpx1 = NaN;
  48086. targetShape.cpy1 = NaN;
  48087. }
  48088. }
  48089. var Line$1 =
  48090. /** @class */
  48091. function (_super) {
  48092. __extends(Line, _super);
  48093. function Line(lineData, idx, seriesScope) {
  48094. var _this = _super.call(this) || this;
  48095. _this._createLine(lineData, idx, seriesScope);
  48096. return _this;
  48097. }
  48098. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  48099. var seriesModel = lineData.hostModel;
  48100. var linePoints = lineData.getItemLayout(idx);
  48101. var line = createLine(linePoints);
  48102. line.shape.percent = 0;
  48103. initProps(line, {
  48104. shape: {
  48105. percent: 1
  48106. }
  48107. }, seriesModel, idx);
  48108. this.add(line);
  48109. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  48110. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  48111. // it will be updated after line#update.
  48112. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  48113. this.add(symbol);
  48114. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  48115. }, this);
  48116. this._updateCommonStl(lineData, idx, seriesScope);
  48117. }; // TODO More strict on the List type in parameters?
  48118. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  48119. var seriesModel = lineData.hostModel;
  48120. var line = this.childOfName('line');
  48121. var linePoints = lineData.getItemLayout(idx);
  48122. var target = {
  48123. shape: {}
  48124. };
  48125. setLinePoints(target.shape, linePoints);
  48126. updateProps(line, target, seriesModel, idx);
  48127. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  48128. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  48129. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  48130. if (this[key] !== symbolType) {
  48131. this.remove(this.childOfName(symbolCategory));
  48132. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  48133. this.add(symbol);
  48134. }
  48135. this[key] = symbolType;
  48136. }, this);
  48137. this._updateCommonStl(lineData, idx, seriesScope);
  48138. };
  48139. Line.prototype.getLinePath = function () {
  48140. return this.childAt(0);
  48141. };
  48142. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  48143. var seriesModel = lineData.hostModel;
  48144. var line = this.childOfName('line');
  48145. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  48146. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  48147. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  48148. var labelStatesModels = seriesScope && seriesScope.labelStatesModels; // Optimization for large dataset
  48149. if (!seriesScope || lineData.hasItemOption) {
  48150. var itemModel = lineData.getItemModel(idx);
  48151. emphasisLineStyle = itemModel.getModel(['emphasis', 'lineStyle']).getLineStyle();
  48152. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  48153. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  48154. labelStatesModels = getLabelStatesModels(itemModel);
  48155. }
  48156. var lineStyle = lineData.getItemVisual(idx, 'style');
  48157. var visualColor = lineStyle.stroke;
  48158. line.useStyle(lineStyle);
  48159. line.style.fill = null;
  48160. line.style.strokeNoScale = true;
  48161. line.ensureState('emphasis').style = emphasisLineStyle;
  48162. line.ensureState('blur').style = blurLineStyle;
  48163. line.ensureState('select').style = selectLineStyle; // Update symbol
  48164. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  48165. var symbol = this.childOfName(symbolCategory);
  48166. if (symbol) {
  48167. // Share opacity and color with line.
  48168. symbol.setColor(visualColor);
  48169. symbol.style.opacity = lineStyle.opacity;
  48170. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  48171. var stateName = SPECIAL_STATES[i];
  48172. var lineState = line.getState(stateName);
  48173. if (lineState) {
  48174. var lineStateStyle = lineState.style || {};
  48175. var state = symbol.ensureState(stateName);
  48176. var stateStyle = state.style || (state.style = {});
  48177. if (lineStateStyle.stroke != null) {
  48178. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  48179. }
  48180. if (lineStateStyle.opacity != null) {
  48181. stateStyle.opacity = lineStateStyle.opacity;
  48182. }
  48183. }
  48184. }
  48185. symbol.markRedraw();
  48186. }
  48187. }, this);
  48188. var rawVal = seriesModel.getRawValue(idx);
  48189. setLabelStyle(this, labelStatesModels, {
  48190. labelDataIndex: idx,
  48191. labelFetcher: {
  48192. getFormattedLabel: function (dataIndex, stateName) {
  48193. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  48194. }
  48195. },
  48196. inheritColor: visualColor || '#000',
  48197. defaultOpacity: lineStyle.opacity,
  48198. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  48199. });
  48200. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  48201. // values have to be set on `normalStyle`.
  48202. if (label) {
  48203. var labelNormalModel = labelStatesModels.normal;
  48204. label.__align = label.style.align;
  48205. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  48206. label.__position = labelNormalModel.get('position') || 'middle';
  48207. var distance = labelNormalModel.get('distance');
  48208. if (!isArray(distance)) {
  48209. distance = [distance, distance];
  48210. }
  48211. label.__labelDistance = distance;
  48212. }
  48213. this.setTextConfig({
  48214. position: null,
  48215. local: true,
  48216. inside: false // Can't be inside for stroke element.
  48217. });
  48218. enableHoverEmphasis(this);
  48219. };
  48220. Line.prototype.highlight = function () {
  48221. enterEmphasis(this);
  48222. };
  48223. Line.prototype.downplay = function () {
  48224. leaveEmphasis(this);
  48225. };
  48226. Line.prototype.updateLayout = function (lineData, idx) {
  48227. this.setLinePoints(lineData.getItemLayout(idx));
  48228. };
  48229. Line.prototype.setLinePoints = function (points) {
  48230. var linePath = this.childOfName('line');
  48231. setLinePoints(linePath.shape, points);
  48232. linePath.dirty();
  48233. };
  48234. Line.prototype.beforeUpdate = function () {
  48235. var lineGroup = this;
  48236. var symbolFrom = lineGroup.childOfName('fromSymbol');
  48237. var symbolTo = lineGroup.childOfName('toSymbol');
  48238. var label = lineGroup.getTextContent(); // Quick reject
  48239. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  48240. return;
  48241. }
  48242. var invScale = 1;
  48243. var parentNode = this.parent;
  48244. while (parentNode) {
  48245. if (parentNode.scaleX) {
  48246. invScale /= parentNode.scaleX;
  48247. }
  48248. parentNode = parentNode.parent;
  48249. }
  48250. var line = lineGroup.childOfName('line'); // If line not changed
  48251. // FIXME Parent scale changed
  48252. if (!this.__dirty && !line.__dirty) {
  48253. return;
  48254. }
  48255. var percent = line.shape.percent;
  48256. var fromPos = line.pointAt(0);
  48257. var toPos = line.pointAt(percent);
  48258. var d = sub([], toPos, fromPos);
  48259. normalize(d, d);
  48260. function setSymbolRotation(symbol, percent) {
  48261. // Fix #12388
  48262. // when symbol is set to be 'arrow' in markLine,
  48263. // symbolRotate value will be ignored, and compulsively use tangent angle.
  48264. // rotate by default if symbol rotation is not specified
  48265. var specifiedRotation = symbol.__specifiedRotation;
  48266. if (specifiedRotation == null) {
  48267. var tangent = line.tangentAt(percent);
  48268. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  48269. } else {
  48270. symbol.attr('rotation', specifiedRotation);
  48271. }
  48272. }
  48273. if (symbolFrom) {
  48274. symbolFrom.setPosition(fromPos);
  48275. setSymbolRotation(symbolFrom, 0);
  48276. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  48277. symbolFrom.markRedraw();
  48278. }
  48279. if (symbolTo) {
  48280. symbolTo.setPosition(toPos);
  48281. setSymbolRotation(symbolTo, 1);
  48282. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  48283. symbolTo.markRedraw();
  48284. }
  48285. if (label && !label.ignore) {
  48286. label.x = label.y = 0;
  48287. label.originX = label.originY = 0;
  48288. var textAlign = void 0;
  48289. var textVerticalAlign = void 0;
  48290. var distance = label.__labelDistance;
  48291. var distanceX = distance[0] * invScale;
  48292. var distanceY = distance[1] * invScale;
  48293. var halfPercent = percent / 2;
  48294. var tangent = line.tangentAt(halfPercent);
  48295. var n = [tangent[1], -tangent[0]];
  48296. var cp = line.pointAt(halfPercent);
  48297. if (n[1] > 0) {
  48298. n[0] = -n[0];
  48299. n[1] = -n[1];
  48300. }
  48301. var dir = tangent[0] < 0 ? -1 : 1;
  48302. if (label.__position !== 'start' && label.__position !== 'end') {
  48303. var rotation = -Math.atan2(tangent[1], tangent[0]);
  48304. if (toPos[0] < fromPos[0]) {
  48305. rotation = Math.PI + rotation;
  48306. }
  48307. label.rotation = rotation;
  48308. }
  48309. var dy = void 0;
  48310. switch (label.__position) {
  48311. case 'insideStartTop':
  48312. case 'insideMiddleTop':
  48313. case 'insideEndTop':
  48314. case 'middle':
  48315. dy = -distanceY;
  48316. textVerticalAlign = 'bottom';
  48317. break;
  48318. case 'insideStartBottom':
  48319. case 'insideMiddleBottom':
  48320. case 'insideEndBottom':
  48321. dy = distanceY;
  48322. textVerticalAlign = 'top';
  48323. break;
  48324. default:
  48325. dy = 0;
  48326. textVerticalAlign = 'middle';
  48327. }
  48328. switch (label.__position) {
  48329. case 'end':
  48330. label.x = d[0] * distanceX + toPos[0];
  48331. label.y = d[1] * distanceY + toPos[1];
  48332. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  48333. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  48334. break;
  48335. case 'start':
  48336. label.x = -d[0] * distanceX + fromPos[0];
  48337. label.y = -d[1] * distanceY + fromPos[1];
  48338. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  48339. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  48340. break;
  48341. case 'insideStartTop':
  48342. case 'insideStart':
  48343. case 'insideStartBottom':
  48344. label.x = distanceX * dir + fromPos[0];
  48345. label.y = fromPos[1] + dy;
  48346. textAlign = tangent[0] < 0 ? 'right' : 'left';
  48347. label.originX = -distanceX * dir;
  48348. label.originY = -dy;
  48349. break;
  48350. case 'insideMiddleTop':
  48351. case 'insideMiddle':
  48352. case 'insideMiddleBottom':
  48353. case 'middle':
  48354. label.x = cp[0];
  48355. label.y = cp[1] + dy;
  48356. textAlign = 'center';
  48357. label.originY = -dy;
  48358. break;
  48359. case 'insideEndTop':
  48360. case 'insideEnd':
  48361. case 'insideEndBottom':
  48362. label.x = -distanceX * dir + toPos[0];
  48363. label.y = toPos[1] + dy;
  48364. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  48365. label.originX = distanceX * dir;
  48366. label.originY = -dy;
  48367. break;
  48368. }
  48369. label.scaleX = label.scaleY = invScale;
  48370. label.setStyle({
  48371. // Use the user specified text align and baseline first
  48372. verticalAlign: label.__verticalAlign || textVerticalAlign,
  48373. align: label.__align || textAlign
  48374. });
  48375. }
  48376. };
  48377. return Line;
  48378. }(Group);
  48379. var LineDraw =
  48380. /** @class */
  48381. function () {
  48382. function LineDraw(LineCtor) {
  48383. this.group = new Group();
  48384. this._LineCtor = LineCtor || Line$1;
  48385. }
  48386. LineDraw.prototype.isPersistent = function () {
  48387. return true;
  48388. };
  48389. LineDraw.prototype.updateData = function (lineData) {
  48390. var _this = this;
  48391. var lineDraw = this;
  48392. var group = lineDraw.group;
  48393. var oldLineData = lineDraw._lineData;
  48394. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  48395. // stream mode to normal mode, where previous elements should be removed.
  48396. if (!oldLineData) {
  48397. group.removeAll();
  48398. }
  48399. var seriesScope = makeSeriesScope$1(lineData);
  48400. lineData.diff(oldLineData).add(function (idx) {
  48401. _this._doAdd(lineData, idx, seriesScope);
  48402. }).update(function (newIdx, oldIdx) {
  48403. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  48404. }).remove(function (idx) {
  48405. group.remove(oldLineData.getItemGraphicEl(idx));
  48406. }).execute();
  48407. };
  48408. LineDraw.prototype.updateLayout = function () {
  48409. var lineData = this._lineData; // Do not support update layout in incremental mode.
  48410. if (!lineData) {
  48411. return;
  48412. }
  48413. lineData.eachItemGraphicEl(function (el, idx) {
  48414. el.updateLayout(lineData, idx);
  48415. }, this);
  48416. };
  48417. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  48418. this._seriesScope = makeSeriesScope$1(lineData);
  48419. this._lineData = null;
  48420. this.group.removeAll();
  48421. };
  48422. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  48423. function updateIncrementalAndHover(el) {
  48424. if (!el.isGroup && !isEffectObject(el)) {
  48425. el.incremental = true;
  48426. el.ensureState('emphasis').hoverLayer = true;
  48427. }
  48428. }
  48429. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  48430. var itemLayout = lineData.getItemLayout(idx);
  48431. if (lineNeedsDraw(itemLayout)) {
  48432. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  48433. el.traverse(updateIncrementalAndHover);
  48434. this.group.add(el);
  48435. lineData.setItemGraphicEl(idx, el);
  48436. }
  48437. }
  48438. };
  48439. LineDraw.prototype.remove = function () {
  48440. this.group.removeAll();
  48441. };
  48442. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  48443. var itemLayout = lineData.getItemLayout(idx);
  48444. if (!lineNeedsDraw(itemLayout)) {
  48445. return;
  48446. }
  48447. var el = new this._LineCtor(lineData, idx, seriesScope);
  48448. lineData.setItemGraphicEl(idx, el);
  48449. this.group.add(el);
  48450. };
  48451. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  48452. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  48453. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  48454. this.group.remove(itemEl);
  48455. return;
  48456. }
  48457. if (!itemEl) {
  48458. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  48459. } else {
  48460. itemEl.updateData(newLineData, newIdx, seriesScope);
  48461. }
  48462. newLineData.setItemGraphicEl(newIdx, itemEl);
  48463. this.group.add(itemEl);
  48464. };
  48465. return LineDraw;
  48466. }();
  48467. function isEffectObject(el) {
  48468. return el.animators && el.animators.length > 0;
  48469. }
  48470. function makeSeriesScope$1(lineData) {
  48471. var hostModel = lineData.hostModel;
  48472. return {
  48473. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  48474. emphasisLineStyle: hostModel.getModel(['emphasis', 'lineStyle']).getLineStyle(),
  48475. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  48476. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  48477. labelStatesModels: getLabelStatesModels(hostModel)
  48478. };
  48479. }
  48480. function isPointNaN(pt) {
  48481. return isNaN(pt[0]) || isNaN(pt[1]);
  48482. }
  48483. function lineNeedsDraw(pts) {
  48484. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  48485. }
  48486. var inner$d = makeInner();
  48487. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  48488. var data = seriesModel.getData();
  48489. var itemArray;
  48490. if (!isArray(item)) {
  48491. // Special type markLine like 'min', 'max', 'average', 'median'
  48492. var mlType = item.type;
  48493. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  48494. // data: [{
  48495. // yAxis: 10
  48496. // }]
  48497. || item.xAxis != null || item.yAxis != null) {
  48498. var valueAxis = void 0;
  48499. var value = void 0;
  48500. if (item.yAxis != null || item.xAxis != null) {
  48501. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  48502. value = retrieve(item.yAxis, item.xAxis);
  48503. } else {
  48504. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  48505. valueAxis = axisInfo.valueAxis;
  48506. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  48507. value = numCalculate(data, valueDataDim, mlType);
  48508. }
  48509. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  48510. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  48511. var mlFrom = clone(item);
  48512. var mlTo = {
  48513. coord: []
  48514. };
  48515. mlFrom.type = null;
  48516. mlFrom.coord = [];
  48517. mlFrom.coord[baseIndex] = -Infinity;
  48518. mlTo.coord[baseIndex] = Infinity;
  48519. var precision = mlModel.get('precision');
  48520. if (precision >= 0 && typeof value === 'number') {
  48521. value = +value.toFixed(Math.min(precision, 20));
  48522. }
  48523. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  48524. itemArray = [mlFrom, mlTo, {
  48525. type: mlType,
  48526. valueIndex: item.valueIndex,
  48527. // Force to use the value of calculated value.
  48528. value: value
  48529. }];
  48530. } else {
  48531. // Invalid data
  48532. if ("development" !== 'production') {
  48533. logError('Invalid markLine data.');
  48534. }
  48535. itemArray = [];
  48536. }
  48537. } else {
  48538. itemArray = item;
  48539. }
  48540. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  48541. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  48542. merge(normalizedItem[2], normalizedItem[0]);
  48543. merge(normalizedItem[2], normalizedItem[1]);
  48544. return normalizedItem;
  48545. };
  48546. function isInifinity(val) {
  48547. return !isNaN(val) && !isFinite(val);
  48548. } // If a markLine has one dim
  48549. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  48550. var otherDimIndex = 1 - dimIndex;
  48551. var dimName = coordSys.dimensions[dimIndex];
  48552. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  48553. }
  48554. function markLineFilter(coordSys, item) {
  48555. if (coordSys.type === 'cartesian2d') {
  48556. var fromCoord = item[0].coord;
  48557. var toCoord = item[1].coord; // In case
  48558. // {
  48559. // markLine: {
  48560. // data: [{ yAxis: 2 }]
  48561. // }
  48562. // }
  48563. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  48564. return true;
  48565. }
  48566. }
  48567. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  48568. }
  48569. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  48570. var coordSys = seriesModel.coordinateSystem;
  48571. var itemModel = data.getItemModel(idx);
  48572. var point;
  48573. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  48574. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  48575. if (!isNaN(xPx) && !isNaN(yPx)) {
  48576. point = [xPx, yPx];
  48577. } else {
  48578. // Chart like bar may have there own marker positioning logic
  48579. if (seriesModel.getMarkerPosition) {
  48580. // Use the getMarkerPoisition
  48581. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  48582. } else {
  48583. var dims = coordSys.dimensions;
  48584. var x = data.get(dims[0], idx);
  48585. var y = data.get(dims[1], idx);
  48586. point = coordSys.dataToPoint([x, y]);
  48587. } // Expand line to the edge of grid if value on one axis is Inifnity
  48588. // In case
  48589. // markLine: {
  48590. // data: [{
  48591. // yAxis: 2
  48592. // // or
  48593. // type: 'average'
  48594. // }]
  48595. // }
  48596. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  48597. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  48598. var xAxis = coordSys.getAxis('x');
  48599. var yAxis = coordSys.getAxis('y');
  48600. var dims = coordSys.dimensions;
  48601. if (isInifinity(data.get(dims[0], idx))) {
  48602. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  48603. } else if (isInifinity(data.get(dims[1], idx))) {
  48604. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  48605. }
  48606. } // Use x, y if has any
  48607. if (!isNaN(xPx)) {
  48608. point[0] = xPx;
  48609. }
  48610. if (!isNaN(yPx)) {
  48611. point[1] = yPx;
  48612. }
  48613. }
  48614. data.setItemLayout(idx, point);
  48615. }
  48616. var MarkLineView =
  48617. /** @class */
  48618. function (_super) {
  48619. __extends(MarkLineView, _super);
  48620. function MarkLineView() {
  48621. var _this = _super !== null && _super.apply(this, arguments) || this;
  48622. _this.type = MarkLineView.type;
  48623. return _this;
  48624. }
  48625. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  48626. ecModel.eachSeries(function (seriesModel) {
  48627. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  48628. if (mlModel) {
  48629. var mlData_1 = mlModel.getData();
  48630. var fromData_1 = inner$d(mlModel).from;
  48631. var toData_1 = inner$d(mlModel).to; // Update visual and layout of from symbol and to symbol
  48632. fromData_1.each(function (idx) {
  48633. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  48634. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  48635. }); // Update layout of line
  48636. mlData_1.each(function (idx) {
  48637. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  48638. });
  48639. this.markerGroupMap.get(seriesModel.id).updateLayout();
  48640. }
  48641. }, this);
  48642. };
  48643. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  48644. var coordSys = seriesModel.coordinateSystem;
  48645. var seriesId = seriesModel.id;
  48646. var seriesData = seriesModel.getData();
  48647. var lineDrawMap = this.markerGroupMap;
  48648. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  48649. this.group.add(lineDraw.group);
  48650. var mlData = createList$2(coordSys, seriesModel, mlModel);
  48651. var fromData = mlData.from;
  48652. var toData = mlData.to;
  48653. var lineData = mlData.line;
  48654. inner$d(mlModel).from = fromData;
  48655. inner$d(mlModel).to = toData; // Line data for tooltip and formatter
  48656. mlModel.setData(lineData);
  48657. var symbolType = mlModel.get('symbol');
  48658. var symbolSize = mlModel.get('symbolSize');
  48659. if (!isArray(symbolType)) {
  48660. symbolType = [symbolType, symbolType];
  48661. }
  48662. if (!isArray(symbolSize)) {
  48663. symbolSize = [symbolSize, symbolSize];
  48664. } // Update visual and layout of from symbol and to symbol
  48665. mlData.from.each(function (idx) {
  48666. updateDataVisualAndLayout(fromData, idx, true);
  48667. updateDataVisualAndLayout(toData, idx, false);
  48668. }); // Update visual and layout of line
  48669. lineData.each(function (idx) {
  48670. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  48671. // color: lineColor || fromData.getItemVisual(idx, 'color')
  48672. // });
  48673. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  48674. if (lineStyle.stroke == null) {
  48675. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  48676. }
  48677. lineData.setItemVisual(idx, {
  48678. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  48679. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  48680. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  48681. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  48682. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  48683. toSymbol: toData.getItemVisual(idx, 'symbol'),
  48684. style: lineStyle
  48685. });
  48686. });
  48687. lineDraw.updateData(lineData); // Set host model for tooltip
  48688. // FIXME
  48689. mlData.line.eachItemGraphicEl(function (el, idx) {
  48690. el.traverse(function (child) {
  48691. getECData(child).dataModel = mlModel;
  48692. });
  48693. });
  48694. function updateDataVisualAndLayout(data, idx, isFrom) {
  48695. var itemModel = data.getItemModel(idx);
  48696. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  48697. var style = itemModel.getModel('itemStyle').getItemStyle();
  48698. if (style.fill == null) {
  48699. style.fill = getVisualFromData(seriesData, 'color');
  48700. }
  48701. data.setItemVisual(idx, {
  48702. symbolRotate: itemModel.get('symbolRotate'),
  48703. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  48704. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  48705. style: style
  48706. });
  48707. }
  48708. this.markKeep(lineDraw);
  48709. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  48710. };
  48711. MarkLineView.type = 'markLine';
  48712. return MarkLineView;
  48713. }(MarkerView);
  48714. function createList$2(coordSys, seriesModel, mlModel) {
  48715. var coordDimsInfos;
  48716. if (coordSys) {
  48717. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  48718. 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
  48719. return defaults({
  48720. name: coordDim
  48721. }, info);
  48722. });
  48723. } else {
  48724. coordDimsInfos = [{
  48725. name: 'value',
  48726. type: 'float'
  48727. }];
  48728. }
  48729. var fromData = new List(coordDimsInfos, mlModel);
  48730. var toData = new List(coordDimsInfos, mlModel); // No dimensions
  48731. var lineData = new List([], mlModel);
  48732. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  48733. if (coordSys) {
  48734. optData = filter(optData, curry(markLineFilter, coordSys));
  48735. }
  48736. var dimValueGetter$1 = coordSys ? dimValueGetter : function (item) {
  48737. return item.value;
  48738. };
  48739. fromData.initData(map(optData, function (item) {
  48740. return item[0];
  48741. }), null, dimValueGetter$1);
  48742. toData.initData(map(optData, function (item) {
  48743. return item[1];
  48744. }), null, dimValueGetter$1);
  48745. lineData.initData(map(optData, function (item) {
  48746. return item[2];
  48747. }));
  48748. lineData.hasItemOption = true;
  48749. return {
  48750. from: fromData,
  48751. to: toData,
  48752. line: lineData
  48753. };
  48754. }
  48755. function install$f(registers) {
  48756. registers.registerComponentModel(MarkLineModel);
  48757. registers.registerComponentView(MarkLineView);
  48758. registers.registerPreprocessor(function (opt) {
  48759. // Make sure markLine component is enabled
  48760. opt.markLine = opt.markLine || {};
  48761. });
  48762. }
  48763. var MarkAreaModel =
  48764. /** @class */
  48765. function (_super) {
  48766. __extends(MarkAreaModel, _super);
  48767. function MarkAreaModel() {
  48768. var _this = _super !== null && _super.apply(this, arguments) || this;
  48769. _this.type = MarkAreaModel.type;
  48770. return _this;
  48771. }
  48772. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  48773. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  48774. };
  48775. MarkAreaModel.type = 'markArea';
  48776. MarkAreaModel.defaultOption = {
  48777. zlevel: 0,
  48778. // PENDING
  48779. z: 1,
  48780. tooltip: {
  48781. trigger: 'item'
  48782. },
  48783. // markArea should fixed on the coordinate system
  48784. animation: false,
  48785. label: {
  48786. show: true,
  48787. position: 'top'
  48788. },
  48789. itemStyle: {
  48790. // color and borderColor default to use color from series
  48791. // color: 'auto'
  48792. // borderColor: 'auto'
  48793. borderWidth: 0
  48794. },
  48795. emphasis: {
  48796. label: {
  48797. show: true,
  48798. position: 'top'
  48799. }
  48800. }
  48801. };
  48802. return MarkAreaModel;
  48803. }(MarkerModel);
  48804. var inner$e = makeInner();
  48805. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  48806. var lt = dataTransform(seriesModel, item[0]);
  48807. var rb = dataTransform(seriesModel, item[1]); // FIXME make sure lt is less than rb
  48808. var ltCoord = lt.coord;
  48809. var rbCoord = rb.coord;
  48810. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  48811. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  48812. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  48813. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  48814. var result = mergeAll([{}, lt, rb]);
  48815. result.coord = [lt.coord, rb.coord];
  48816. result.x0 = lt.x;
  48817. result.y0 = lt.y;
  48818. result.x1 = rb.x;
  48819. result.y1 = rb.y;
  48820. return result;
  48821. };
  48822. function isInifinity$1(val) {
  48823. return !isNaN(val) && !isFinite(val);
  48824. } // If a markArea has one dim
  48825. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  48826. var otherDimIndex = 1 - dimIndex;
  48827. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  48828. }
  48829. function markAreaFilter(coordSys, item) {
  48830. var fromCoord = item.coord[0];
  48831. var toCoord = item.coord[1];
  48832. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  48833. // In case
  48834. // {
  48835. // markArea: {
  48836. // data: [{ yAxis: 2 }]
  48837. // }
  48838. // }
  48839. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  48840. return true;
  48841. }
  48842. }
  48843. return dataFilter$1(coordSys, {
  48844. coord: fromCoord,
  48845. x: item.x0,
  48846. y: item.y0
  48847. }) || dataFilter$1(coordSys, {
  48848. coord: toCoord,
  48849. x: item.x1,
  48850. y: item.y1
  48851. });
  48852. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  48853. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  48854. var coordSys = seriesModel.coordinateSystem;
  48855. var itemModel = data.getItemModel(idx);
  48856. var point;
  48857. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  48858. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  48859. if (!isNaN(xPx) && !isNaN(yPx)) {
  48860. point = [xPx, yPx];
  48861. } else {
  48862. // Chart like bar may have there own marker positioning logic
  48863. if (seriesModel.getMarkerPosition) {
  48864. // Use the getMarkerPoisition
  48865. point = seriesModel.getMarkerPosition(data.getValues(dims, idx));
  48866. } else {
  48867. var x = data.get(dims[0], idx);
  48868. var y = data.get(dims[1], idx);
  48869. var pt = [x, y];
  48870. coordSys.clampData && coordSys.clampData(pt, pt);
  48871. point = coordSys.dataToPoint(pt, true);
  48872. }
  48873. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  48874. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  48875. var xAxis = coordSys.getAxis('x');
  48876. var yAxis = coordSys.getAxis('y');
  48877. var x = data.get(dims[0], idx);
  48878. var y = data.get(dims[1], idx);
  48879. if (isInifinity$1(x)) {
  48880. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  48881. } else if (isInifinity$1(y)) {
  48882. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  48883. }
  48884. } // Use x, y if has any
  48885. if (!isNaN(xPx)) {
  48886. point[0] = xPx;
  48887. }
  48888. if (!isNaN(yPx)) {
  48889. point[1] = yPx;
  48890. }
  48891. }
  48892. return point;
  48893. }
  48894. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  48895. var MarkAreaView =
  48896. /** @class */
  48897. function (_super) {
  48898. __extends(MarkAreaView, _super);
  48899. function MarkAreaView() {
  48900. var _this = _super !== null && _super.apply(this, arguments) || this;
  48901. _this.type = MarkAreaView.type;
  48902. return _this;
  48903. }
  48904. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  48905. ecModel.eachSeries(function (seriesModel) {
  48906. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  48907. if (maModel) {
  48908. var areaData_1 = maModel.getData();
  48909. areaData_1.each(function (idx) {
  48910. var points = map(dimPermutations, function (dim) {
  48911. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  48912. }); // Layout
  48913. areaData_1.setItemLayout(idx, points);
  48914. var el = areaData_1.getItemGraphicEl(idx);
  48915. el.setShape('points', points);
  48916. });
  48917. }
  48918. }, this);
  48919. };
  48920. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  48921. var coordSys = seriesModel.coordinateSystem;
  48922. var seriesId = seriesModel.id;
  48923. var seriesData = seriesModel.getData();
  48924. var areaGroupMap = this.markerGroupMap;
  48925. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  48926. group: new Group()
  48927. });
  48928. this.group.add(polygonGroup.group);
  48929. this.markKeep(polygonGroup);
  48930. var areaData = createList$3(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  48931. maModel.setData(areaData); // Update visual and layout of line
  48932. areaData.each(function (idx) {
  48933. // Layout
  48934. var points = map(dimPermutations, function (dim) {
  48935. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  48936. }); // If none of the area is inside coordSys, allClipped is set to be true
  48937. // in layout so that label will not be displayed. See #12591
  48938. var allClipped = true;
  48939. each(dimPermutations, function (dim) {
  48940. if (!allClipped) {
  48941. return;
  48942. }
  48943. var xValue = areaData.get(dim[0], idx);
  48944. var yValue = areaData.get(dim[1], idx); // If is infinity, the axis should be considered not clipped
  48945. if ((isInifinity$1(xValue) || coordSys.getAxis('x').containData(xValue)) && (isInifinity$1(yValue) || coordSys.getAxis('y').containData(yValue))) {
  48946. allClipped = false;
  48947. }
  48948. });
  48949. areaData.setItemLayout(idx, {
  48950. points: points,
  48951. allClipped: allClipped
  48952. });
  48953. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  48954. var color$1 = getVisualFromData(seriesData, 'color');
  48955. if (!style.fill) {
  48956. style.fill = color$1;
  48957. if (typeof style.fill === 'string') {
  48958. style.fill = modifyAlpha(style.fill, 0.4);
  48959. }
  48960. }
  48961. if (!style.stroke) {
  48962. style.stroke = color$1;
  48963. } // Visual
  48964. areaData.setItemVisual(idx, 'style', style);
  48965. });
  48966. areaData.diff(inner$e(polygonGroup).data).add(function (idx) {
  48967. var layout = areaData.getItemLayout(idx);
  48968. if (!layout.allClipped) {
  48969. var polygon = new Polygon({
  48970. shape: {
  48971. points: layout.points
  48972. }
  48973. });
  48974. areaData.setItemGraphicEl(idx, polygon);
  48975. polygonGroup.group.add(polygon);
  48976. }
  48977. }).update(function (newIdx, oldIdx) {
  48978. var polygon = inner$e(polygonGroup).data.getItemGraphicEl(oldIdx);
  48979. var layout = areaData.getItemLayout(newIdx);
  48980. if (!layout.allClipped) {
  48981. if (polygon) {
  48982. updateProps(polygon, {
  48983. shape: {
  48984. points: layout.points
  48985. }
  48986. }, maModel, newIdx);
  48987. } else {
  48988. polygon = new Polygon({
  48989. shape: {
  48990. points: layout.points
  48991. }
  48992. });
  48993. }
  48994. areaData.setItemGraphicEl(newIdx, polygon);
  48995. polygonGroup.group.add(polygon);
  48996. } else if (polygon) {
  48997. polygonGroup.group.remove(polygon);
  48998. }
  48999. }).remove(function (idx) {
  49000. var polygon = inner$e(polygonGroup).data.getItemGraphicEl(idx);
  49001. polygonGroup.group.remove(polygon);
  49002. }).execute();
  49003. areaData.eachItemGraphicEl(function (polygon, idx) {
  49004. var itemModel = areaData.getItemModel(idx);
  49005. var style = areaData.getItemVisual(idx, 'style');
  49006. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  49007. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  49008. labelFetcher: maModel,
  49009. labelDataIndex: idx,
  49010. defaultText: areaData.getName(idx) || '',
  49011. inheritColor: typeof style.fill === 'string' ? modifyAlpha(style.fill, 1) : '#000'
  49012. });
  49013. setStatesStylesFromModel(polygon, itemModel);
  49014. enableHoverEmphasis(polygon);
  49015. getECData(polygon).dataModel = maModel;
  49016. });
  49017. inner$e(polygonGroup).data = areaData;
  49018. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  49019. };
  49020. MarkAreaView.type = 'markArea';
  49021. return MarkAreaView;
  49022. }(MarkerView);
  49023. function createList$3(coordSys, seriesModel, maModel) {
  49024. var coordDimsInfos;
  49025. var areaData;
  49026. var dims = ['x0', 'y0', 'x1', 'y1'];
  49027. if (coordSys) {
  49028. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  49029. var data = seriesModel.getData();
  49030. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  49031. return defaults({
  49032. name: coordDim
  49033. }, info);
  49034. });
  49035. areaData = new List(map(dims, function (dim, idx) {
  49036. return {
  49037. name: dim,
  49038. type: coordDimsInfos[idx % 2].type
  49039. };
  49040. }), maModel);
  49041. } else {
  49042. coordDimsInfos = [{
  49043. name: 'value',
  49044. type: 'float'
  49045. }];
  49046. areaData = new List(coordDimsInfos, maModel);
  49047. }
  49048. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  49049. if (coordSys) {
  49050. optData = filter(optData, curry(markAreaFilter, coordSys));
  49051. }
  49052. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  49053. // TODO should convert to ParsedValue?
  49054. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  49055. } : function (item) {
  49056. return item.value;
  49057. };
  49058. areaData.initData(optData, null, dimValueGetter);
  49059. areaData.hasItemOption = true;
  49060. return areaData;
  49061. }
  49062. function install$g(registers) {
  49063. registers.registerComponentModel(MarkAreaModel);
  49064. registers.registerComponentView(MarkAreaView);
  49065. registers.registerPreprocessor(function (opt) {
  49066. // Make sure markArea component is enabled
  49067. opt.markArea = opt.markArea || {};
  49068. });
  49069. }
  49070. var getDefaultSelectorOptions = function (ecModel, type) {
  49071. if (type === 'all') {
  49072. return {
  49073. type: 'all',
  49074. title: ecModel.getLocale(['legend', 'selector', 'all'])
  49075. };
  49076. } else if (type === 'inverse') {
  49077. return {
  49078. type: 'inverse',
  49079. title: ecModel.getLocale(['legend', 'selector', 'inverse'])
  49080. };
  49081. }
  49082. };
  49083. var LegendModel =
  49084. /** @class */
  49085. function (_super) {
  49086. __extends(LegendModel, _super);
  49087. function LegendModel() {
  49088. var _this = _super !== null && _super.apply(this, arguments) || this;
  49089. _this.type = LegendModel.type;
  49090. _this.layoutMode = {
  49091. type: 'box',
  49092. // legend.width/height are maxWidth/maxHeight actually,
  49093. // whereas realy width/height is calculated by its content.
  49094. // (Setting {left: 10, right: 10} does not make sense).
  49095. // So consider the case:
  49096. // `setOption({legend: {left: 10});`
  49097. // then `setOption({legend: {right: 10});`
  49098. // The previous `left` should be cleared by setting `ignoreSize`.
  49099. ignoreSize: true
  49100. };
  49101. return _this;
  49102. }
  49103. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  49104. this.mergeDefaultAndTheme(option, ecModel);
  49105. option.selected = option.selected || {};
  49106. this._updateSelector(option);
  49107. };
  49108. LegendModel.prototype.mergeOption = function (option, ecModel) {
  49109. _super.prototype.mergeOption.call(this, option, ecModel);
  49110. this._updateSelector(option);
  49111. };
  49112. LegendModel.prototype._updateSelector = function (option) {
  49113. var selector = option.selector;
  49114. var ecModel = this.ecModel;
  49115. if (selector === true) {
  49116. selector = option.selector = ['all', 'inverse'];
  49117. }
  49118. if (isArray(selector)) {
  49119. each(selector, function (item, index) {
  49120. isString(item) && (item = {
  49121. type: item
  49122. });
  49123. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  49124. });
  49125. }
  49126. };
  49127. LegendModel.prototype.optionUpdated = function () {
  49128. this._updateData(this.ecModel);
  49129. var legendData = this._data; // If selectedMode is single, try to select one
  49130. if (legendData[0] && this.get('selectedMode') === 'single') {
  49131. var hasSelected = false; // If has any selected in option.selected
  49132. for (var i = 0; i < legendData.length; i++) {
  49133. var name_1 = legendData[i].get('name');
  49134. if (this.isSelected(name_1)) {
  49135. // Force to unselect others
  49136. this.select(name_1);
  49137. hasSelected = true;
  49138. break;
  49139. }
  49140. } // Try select the first if selectedMode is single
  49141. !hasSelected && this.select(legendData[0].get('name'));
  49142. }
  49143. };
  49144. LegendModel.prototype._updateData = function (ecModel) {
  49145. var potentialData = [];
  49146. var availableNames = [];
  49147. ecModel.eachRawSeries(function (seriesModel) {
  49148. var seriesName = seriesModel.name;
  49149. availableNames.push(seriesName);
  49150. var isPotential;
  49151. if (seriesModel.legendVisualProvider) {
  49152. var provider = seriesModel.legendVisualProvider;
  49153. var names = provider.getAllNames();
  49154. if (!ecModel.isSeriesFiltered(seriesModel)) {
  49155. availableNames = availableNames.concat(names);
  49156. }
  49157. if (names.length) {
  49158. potentialData = potentialData.concat(names);
  49159. } else {
  49160. isPotential = true;
  49161. }
  49162. } else {
  49163. isPotential = true;
  49164. }
  49165. if (isPotential && isNameSpecified(seriesModel)) {
  49166. potentialData.push(seriesModel.name);
  49167. }
  49168. });
  49169. /**
  49170. * @type {Array.<string>}
  49171. * @private
  49172. */
  49173. this._availableNames = availableNames; // If legend.data not specified in option, use availableNames as data,
  49174. // which is convinient for user preparing option.
  49175. var rawData = this.get('data') || potentialData;
  49176. var legendData = map(rawData, function (dataItem) {
  49177. // Can be string or number
  49178. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  49179. dataItem = {
  49180. name: dataItem
  49181. };
  49182. }
  49183. return new Model(dataItem, this, this.ecModel);
  49184. }, this);
  49185. /**
  49186. * @type {Array.<module:echarts/model/Model>}
  49187. * @private
  49188. */
  49189. this._data = legendData;
  49190. };
  49191. LegendModel.prototype.getData = function () {
  49192. return this._data;
  49193. };
  49194. LegendModel.prototype.select = function (name) {
  49195. var selected = this.option.selected;
  49196. var selectedMode = this.get('selectedMode');
  49197. if (selectedMode === 'single') {
  49198. var data = this._data;
  49199. each(data, function (dataItem) {
  49200. selected[dataItem.get('name')] = false;
  49201. });
  49202. }
  49203. selected[name] = true;
  49204. };
  49205. LegendModel.prototype.unSelect = function (name) {
  49206. if (this.get('selectedMode') !== 'single') {
  49207. this.option.selected[name] = false;
  49208. }
  49209. };
  49210. LegendModel.prototype.toggleSelected = function (name) {
  49211. var selected = this.option.selected; // Default is true
  49212. if (!selected.hasOwnProperty(name)) {
  49213. selected[name] = true;
  49214. }
  49215. this[selected[name] ? 'unSelect' : 'select'](name);
  49216. };
  49217. LegendModel.prototype.allSelect = function () {
  49218. var data = this._data;
  49219. var selected = this.option.selected;
  49220. each(data, function (dataItem) {
  49221. selected[dataItem.get('name', true)] = true;
  49222. });
  49223. };
  49224. LegendModel.prototype.inverseSelect = function () {
  49225. var data = this._data;
  49226. var selected = this.option.selected;
  49227. each(data, function (dataItem) {
  49228. var name = dataItem.get('name', true); // Initially, default value is true
  49229. if (!selected.hasOwnProperty(name)) {
  49230. selected[name] = true;
  49231. }
  49232. selected[name] = !selected[name];
  49233. });
  49234. };
  49235. LegendModel.prototype.isSelected = function (name) {
  49236. var selected = this.option.selected;
  49237. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  49238. };
  49239. LegendModel.prototype.getOrient = function () {
  49240. return this.get('orient') === 'vertical' ? {
  49241. index: 1,
  49242. name: 'vertical'
  49243. } : {
  49244. index: 0,
  49245. name: 'horizontal'
  49246. };
  49247. };
  49248. LegendModel.type = 'legend.plain';
  49249. LegendModel.dependencies = ['series'];
  49250. LegendModel.defaultOption = {
  49251. zlevel: 0,
  49252. z: 4,
  49253. show: true,
  49254. orient: 'horizontal',
  49255. left: 'center',
  49256. // right: 'center',
  49257. top: 0,
  49258. // bottom: null,
  49259. align: 'auto',
  49260. backgroundColor: 'rgba(0,0,0,0)',
  49261. borderColor: '#ccc',
  49262. borderRadius: 0,
  49263. borderWidth: 0,
  49264. padding: 5,
  49265. itemGap: 10,
  49266. itemWidth: 25,
  49267. itemHeight: 14,
  49268. inactiveColor: '#ccc',
  49269. inactiveBorderColor: '#ccc',
  49270. itemStyle: {
  49271. borderWidth: 0
  49272. },
  49273. textStyle: {
  49274. color: '#333'
  49275. },
  49276. selectedMode: true,
  49277. selector: false,
  49278. selectorLabel: {
  49279. show: true,
  49280. borderRadius: 10,
  49281. padding: [3, 5, 3, 5],
  49282. fontSize: 12,
  49283. fontFamily: ' sans-serif',
  49284. color: '#666',
  49285. borderWidth: 1,
  49286. borderColor: '#666'
  49287. },
  49288. emphasis: {
  49289. selectorLabel: {
  49290. show: true,
  49291. color: '#eee',
  49292. backgroundColor: '#666'
  49293. }
  49294. },
  49295. selectorPosition: 'auto',
  49296. selectorItemGap: 7,
  49297. selectorButtonGap: 10,
  49298. tooltip: {
  49299. show: false
  49300. }
  49301. };
  49302. return LegendModel;
  49303. }(ComponentModel);
  49304. var curry$1 = curry;
  49305. var each$9 = each;
  49306. var Group$1 = Group;
  49307. var LegendView =
  49308. /** @class */
  49309. function (_super) {
  49310. __extends(LegendView, _super);
  49311. function LegendView() {
  49312. var _this = _super !== null && _super.apply(this, arguments) || this;
  49313. _this.type = LegendView.type;
  49314. _this.newlineDisabled = false;
  49315. return _this;
  49316. }
  49317. LegendView.prototype.init = function () {
  49318. this.group.add(this._contentGroup = new Group$1());
  49319. this.group.add(this._selectorGroup = new Group$1());
  49320. this._isFirstRender = true;
  49321. };
  49322. /**
  49323. * @protected
  49324. */
  49325. LegendView.prototype.getContentGroup = function () {
  49326. return this._contentGroup;
  49327. };
  49328. /**
  49329. * @protected
  49330. */
  49331. LegendView.prototype.getSelectorGroup = function () {
  49332. return this._selectorGroup;
  49333. };
  49334. /**
  49335. * @override
  49336. */
  49337. LegendView.prototype.render = function (legendModel, ecModel, api) {
  49338. var isFirstRender = this._isFirstRender;
  49339. this._isFirstRender = false;
  49340. this.resetInner();
  49341. if (!legendModel.get('show', true)) {
  49342. return;
  49343. }
  49344. var itemAlign = legendModel.get('align');
  49345. var orient = legendModel.get('orient');
  49346. if (!itemAlign || itemAlign === 'auto') {
  49347. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  49348. } // selector has been normalized to an array in model
  49349. var selector = legendModel.get('selector', true);
  49350. var selectorPosition = legendModel.get('selectorPosition', true);
  49351. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  49352. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  49353. }
  49354. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  49355. var positionInfo = legendModel.getBoxLayoutParams();
  49356. var viewportSize = {
  49357. width: api.getWidth(),
  49358. height: api.getHeight()
  49359. };
  49360. var padding = legendModel.get('padding');
  49361. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  49362. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  49363. var layoutRect = getLayoutRect(defaults({
  49364. width: mainRect.width,
  49365. height: mainRect.height
  49366. }, positionInfo), viewportSize, padding);
  49367. this.group.x = layoutRect.x - mainRect.x;
  49368. this.group.y = layoutRect.y - mainRect.y;
  49369. this.group.markRedraw(); // Render background after group is layout.
  49370. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  49371. };
  49372. LegendView.prototype.resetInner = function () {
  49373. this.getContentGroup().removeAll();
  49374. this._backgroundEl && this.group.remove(this._backgroundEl);
  49375. this.getSelectorGroup().removeAll();
  49376. };
  49377. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  49378. var contentGroup = this.getContentGroup();
  49379. var legendDrawnMap = createHashMap();
  49380. var selectMode = legendModel.get('selectedMode');
  49381. var excludeSeriesId = [];
  49382. ecModel.eachRawSeries(function (seriesModel) {
  49383. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  49384. });
  49385. each$9(legendModel.getData(), function (itemModel, dataIndex) {
  49386. var name = itemModel.get('name'); // Use empty string or \n as a newline string
  49387. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  49388. var g = new Group$1(); // @ts-ignore
  49389. g.newline = true;
  49390. contentGroup.add(g);
  49391. return;
  49392. } // Representitive series.
  49393. var seriesModel = ecModel.getSeriesByName(name)[0];
  49394. if (legendDrawnMap.get(name)) {
  49395. // Have been drawed
  49396. return;
  49397. } // Legend to control series.
  49398. if (seriesModel) {
  49399. var data = seriesModel.getData();
  49400. var style = data.getVisual('style');
  49401. var color = style[data.getVisual('drawType')] || style.fill;
  49402. var borderColor = style.stroke;
  49403. var decal = style.decal; // Using rect symbol defaultly
  49404. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  49405. var symbolType = data.getVisual('symbol');
  49406. var itemGroup = this._createItem(name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, decal, selectMode);
  49407. 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));
  49408. legendDrawnMap.set(name, true);
  49409. } else {
  49410. // Legend to control data. In pie and funnel.
  49411. ecModel.eachRawSeries(function (seriesModel) {
  49412. // In case multiple series has same data name
  49413. if (legendDrawnMap.get(name)) {
  49414. return;
  49415. }
  49416. if (seriesModel.legendVisualProvider) {
  49417. var provider = seriesModel.legendVisualProvider;
  49418. if (!provider.containName(name)) {
  49419. return;
  49420. }
  49421. var idx = provider.indexOfName(name);
  49422. var style = provider.getItemVisual(idx, 'style');
  49423. var borderColor = style.stroke;
  49424. var decal = style.decal;
  49425. var color = style.fill;
  49426. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  49427. // Do not show nothing.
  49428. if (colorArr && colorArr[3] === 0) {
  49429. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  49430. color = stringify(colorArr, 'rgba');
  49431. }
  49432. var legendSymbolType = 'roundRect';
  49433. 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.
  49434. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  49435. // more than one pie series.
  49436. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  49437. legendDrawnMap.set(name, true);
  49438. }
  49439. }, this);
  49440. }
  49441. if ("development" !== 'production') {
  49442. if (!legendDrawnMap.get(name)) {
  49443. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  49444. }
  49445. }
  49446. }, this);
  49447. if (selector) {
  49448. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  49449. }
  49450. };
  49451. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  49452. var selectorGroup = this.getSelectorGroup();
  49453. each$9(selector, function createSelectorButton(selectorItem) {
  49454. var type = selectorItem.type;
  49455. var labelText = new ZRText({
  49456. style: {
  49457. x: 0,
  49458. y: 0,
  49459. align: 'center',
  49460. verticalAlign: 'middle'
  49461. },
  49462. onclick: function () {
  49463. api.dispatchAction({
  49464. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  49465. });
  49466. }
  49467. });
  49468. selectorGroup.add(labelText);
  49469. var labelModel = legendModel.getModel('selectorLabel');
  49470. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  49471. setLabelStyle(labelText, {
  49472. normal: labelModel,
  49473. emphasis: emphasisLabelModel
  49474. }, {
  49475. defaultText: selectorItem.title
  49476. });
  49477. enableHoverEmphasis(labelText);
  49478. });
  49479. };
  49480. LegendView.prototype._createItem = function (name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, decal, selectMode) {
  49481. var itemWidth = legendModel.get('itemWidth');
  49482. var itemHeight = legendModel.get('itemHeight');
  49483. var inactiveColor = legendModel.get('inactiveColor');
  49484. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  49485. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  49486. var legendModelItemStyle = legendModel.getModel('itemStyle');
  49487. var isSelected = legendModel.isSelected(name);
  49488. var itemGroup = new Group$1();
  49489. var textStyleModel = itemModel.getModel('textStyle');
  49490. var itemIcon = itemModel.get('icon');
  49491. var tooltipModel = itemModel.getModel('tooltip');
  49492. var legendGlobalTooltipModel = tooltipModel.parentModel; // Use user given icon first
  49493. legendSymbolType = itemIcon || legendSymbolType;
  49494. var legendSymbol = createSymbol(legendSymbolType, 0, 0, itemWidth, itemHeight, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  49495. symbolKeepAspect == null ? true : symbolKeepAspect);
  49496. itemGroup.add(setSymbolStyle(legendSymbol, legendSymbolType, legendModelItemStyle, borderColor, inactiveBorderColor, decal, isSelected)); // Compose symbols
  49497. // PENDING
  49498. if (!itemIcon && symbolType // At least show one symbol, can't be all none
  49499. && (symbolType !== legendSymbolType || symbolType === 'none')) {
  49500. var size = itemHeight * 0.8;
  49501. if (symbolType === 'none') {
  49502. symbolType = 'circle';
  49503. }
  49504. var legendSymbolCenter = createSymbol(symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  49505. symbolKeepAspect == null ? true : symbolKeepAspect); // Put symbol in the center
  49506. itemGroup.add(setSymbolStyle(legendSymbolCenter, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, decal, isSelected));
  49507. }
  49508. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  49509. var textAlign = itemAlign;
  49510. var formatter = legendModel.get('formatter');
  49511. var content = name;
  49512. if (typeof formatter === 'string' && formatter) {
  49513. content = formatter.replace('{name}', name != null ? name : '');
  49514. } else if (typeof formatter === 'function') {
  49515. content = formatter(name);
  49516. }
  49517. itemGroup.add(new ZRText({
  49518. style: createTextStyle(textStyleModel, {
  49519. text: content,
  49520. x: textX,
  49521. y: itemHeight / 2,
  49522. fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  49523. align: textAlign,
  49524. verticalAlign: 'middle'
  49525. })
  49526. })); // Add a invisible rect to increase the area of mouse hover
  49527. var hitRect = new Rect({
  49528. shape: itemGroup.getBoundingRect(),
  49529. invisible: true
  49530. });
  49531. if (tooltipModel.get('show')) {
  49532. var formatterParams = {
  49533. componentType: 'legend',
  49534. legendIndex: legendModel.componentIndex,
  49535. name: name,
  49536. $vars: ['name']
  49537. };
  49538. hitRect.tooltip = extend({
  49539. content: name,
  49540. // Defaul formatter
  49541. formatter: legendGlobalTooltipModel.get('formatter', true) || function (params) {
  49542. return params.name;
  49543. },
  49544. formatterParams: formatterParams
  49545. }, tooltipModel.option);
  49546. }
  49547. itemGroup.add(hitRect);
  49548. itemGroup.eachChild(function (child) {
  49549. child.silent = true;
  49550. });
  49551. hitRect.silent = !selectMode;
  49552. this.getContentGroup().add(itemGroup);
  49553. enableHoverEmphasis(itemGroup); // @ts-ignore
  49554. itemGroup.__legendDataIndex = dataIndex;
  49555. return itemGroup;
  49556. };
  49557. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  49558. var contentGroup = this.getContentGroup();
  49559. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  49560. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  49561. var contentRect = contentGroup.getBoundingRect();
  49562. var contentPos = [-contentRect.x, -contentRect.y];
  49563. selectorGroup.markRedraw();
  49564. contentGroup.markRedraw();
  49565. if (selector) {
  49566. // Place buttons in selectorGroup
  49567. box( // Buttons in selectorGroup always layout horizontally
  49568. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  49569. var selectorRect = selectorGroup.getBoundingRect();
  49570. var selectorPos = [-selectorRect.x, -selectorRect.y];
  49571. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  49572. var orientIdx = legendModel.getOrient().index;
  49573. var wh = orientIdx === 0 ? 'width' : 'height';
  49574. var hw = orientIdx === 0 ? 'height' : 'width';
  49575. var yx = orientIdx === 0 ? 'y' : 'x';
  49576. if (selectorPosition === 'end') {
  49577. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  49578. } else {
  49579. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  49580. } //Always align selector to content as 'middle'
  49581. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  49582. selectorGroup.x = selectorPos[0];
  49583. selectorGroup.y = selectorPos[1];
  49584. contentGroup.x = contentPos[0];
  49585. contentGroup.y = contentPos[1];
  49586. var mainRect = {
  49587. x: 0,
  49588. y: 0
  49589. };
  49590. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  49591. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  49592. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  49593. return mainRect;
  49594. } else {
  49595. contentGroup.x = contentPos[0];
  49596. contentGroup.y = contentPos[1];
  49597. return this.group.getBoundingRect();
  49598. }
  49599. };
  49600. /**
  49601. * @protected
  49602. */
  49603. LegendView.prototype.remove = function () {
  49604. this.getContentGroup().removeAll();
  49605. this._isFirstRender = true;
  49606. };
  49607. LegendView.type = 'legend.plain';
  49608. return LegendView;
  49609. }(ComponentView);
  49610. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, decal, isSelected) {
  49611. var itemStyle;
  49612. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  49613. itemStyle = legendModelItemStyle.getItemStyle();
  49614. symbol.style.stroke = borderColor;
  49615. symbol.style.decal = decal;
  49616. if (!isSelected) {
  49617. itemStyle.stroke = inactiveBorderColor;
  49618. }
  49619. } else {
  49620. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  49621. }
  49622. symbol.setStyle(itemStyle);
  49623. return symbol;
  49624. }
  49625. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  49626. // downplay before unselect
  49627. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  49628. api.dispatchAction({
  49629. type: 'legendToggleSelect',
  49630. name: seriesName != null ? seriesName : dataName
  49631. }); // highlight after select
  49632. // TODO higlight immediately may cause animation loss.
  49633. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  49634. }
  49635. function isUseHoverLayer(api) {
  49636. var list = api.getZr().storage.getDisplayList();
  49637. var emphasisState;
  49638. var i = 0;
  49639. var len = list.length;
  49640. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  49641. i++;
  49642. }
  49643. return emphasisState && emphasisState.hoverLayer;
  49644. }
  49645. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  49646. // If element hover will move to a hoverLayer.
  49647. if (!isUseHoverLayer(api)) {
  49648. api.dispatchAction({
  49649. type: 'highlight',
  49650. seriesName: seriesName,
  49651. name: dataName,
  49652. excludeSeriesId: excludeSeriesId
  49653. });
  49654. }
  49655. }
  49656. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  49657. // If element hover will move to a hoverLayer.
  49658. if (!isUseHoverLayer(api)) {
  49659. api.dispatchAction({
  49660. type: 'downplay',
  49661. seriesName: seriesName,
  49662. name: dataName,
  49663. excludeSeriesId: excludeSeriesId
  49664. });
  49665. }
  49666. }
  49667. /*
  49668. * Licensed to the Apache Software Foundation (ASF) under one
  49669. * or more contributor license agreements. See the NOTICE file
  49670. * distributed with this work for additional information
  49671. * regarding copyright ownership. The ASF licenses this file
  49672. * to you under the Apache License, Version 2.0 (the
  49673. * "License"); you may not use this file except in compliance
  49674. * with the License. You may obtain a copy of the License at
  49675. *
  49676. * http://www.apache.org/licenses/LICENSE-2.0
  49677. *
  49678. * Unless required by applicable law or agreed to in writing,
  49679. * software distributed under the License is distributed on an
  49680. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49681. * KIND, either express or implied. See the License for the
  49682. * specific language governing permissions and limitations
  49683. * under the License.
  49684. */
  49685. /**
  49686. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49687. */
  49688. /*
  49689. * Licensed to the Apache Software Foundation (ASF) under one
  49690. * or more contributor license agreements. See the NOTICE file
  49691. * distributed with this work for additional information
  49692. * regarding copyright ownership. The ASF licenses this file
  49693. * to you under the Apache License, Version 2.0 (the
  49694. * "License"); you may not use this file except in compliance
  49695. * with the License. You may obtain a copy of the License at
  49696. *
  49697. * http://www.apache.org/licenses/LICENSE-2.0
  49698. *
  49699. * Unless required by applicable law or agreed to in writing,
  49700. * software distributed under the License is distributed on an
  49701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49702. * KIND, either express or implied. See the License for the
  49703. * specific language governing permissions and limitations
  49704. * under the License.
  49705. */
  49706. function legendFilter(ecModel) {
  49707. var legendModels = ecModel.findComponents({
  49708. mainType: 'legend'
  49709. });
  49710. if (legendModels && legendModels.length) {
  49711. ecModel.filterSeries(function (series) {
  49712. // If in any legend component the status is not selected.
  49713. // Because in legend series is assumed selected when it is not in the legend data.
  49714. for (var i = 0; i < legendModels.length; i++) {
  49715. if (!legendModels[i].isSelected(series.name)) {
  49716. return false;
  49717. }
  49718. }
  49719. return true;
  49720. });
  49721. }
  49722. }
  49723. function legendSelectActionHandler(methodName, payload, ecModel) {
  49724. var selectedMap = {};
  49725. var isToggleSelect = methodName === 'toggleSelected';
  49726. var isSelected; // Update all legend components
  49727. ecModel.eachComponent('legend', function (legendModel) {
  49728. if (isToggleSelect && isSelected != null) {
  49729. // Force other legend has same selected status
  49730. // Or the first is toggled to true and other are toggled to false
  49731. // In the case one legend has some item unSelected in option. And if other legend
  49732. // doesn't has the item, they will assume it is selected.
  49733. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  49734. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  49735. legendModel[methodName]();
  49736. } else {
  49737. legendModel[methodName](payload.name);
  49738. isSelected = legendModel.isSelected(payload.name);
  49739. }
  49740. var legendData = legendModel.getData();
  49741. each(legendData, function (model) {
  49742. var name = model.get('name'); // Wrap element
  49743. if (name === '\n' || name === '') {
  49744. return;
  49745. }
  49746. var isItemSelected = legendModel.isSelected(name);
  49747. if (selectedMap.hasOwnProperty(name)) {
  49748. // Unselected if any legend is unselected
  49749. selectedMap[name] = selectedMap[name] && isItemSelected;
  49750. } else {
  49751. selectedMap[name] = isItemSelected;
  49752. }
  49753. });
  49754. }); // Return the event explicitly
  49755. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  49756. selected: selectedMap
  49757. } : {
  49758. name: payload.name,
  49759. selected: selectedMap
  49760. };
  49761. }
  49762. function installLegendAction(registers) {
  49763. /**
  49764. * @event legendToggleSelect
  49765. * @type {Object}
  49766. * @property {string} type 'legendToggleSelect'
  49767. * @property {string} [from]
  49768. * @property {string} name Series name or data item name
  49769. */
  49770. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  49771. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  49772. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  49773. /**
  49774. * @event legendSelect
  49775. * @type {Object}
  49776. * @property {string} type 'legendSelect'
  49777. * @property {string} name Series name or data item name
  49778. */
  49779. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  49780. /**
  49781. * @event legendUnSelect
  49782. * @type {Object}
  49783. * @property {string} type 'legendUnSelect'
  49784. * @property {string} name Series name or data item name
  49785. */
  49786. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  49787. }
  49788. function install$h(registers) {
  49789. registers.registerComponentModel(LegendModel);
  49790. registers.registerComponentView(LegendView);
  49791. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  49792. registers.registerSubTypeDefaulter('legend', function () {
  49793. return 'plain';
  49794. });
  49795. installLegendAction(registers);
  49796. }
  49797. var ScrollableLegendModel =
  49798. /** @class */
  49799. function (_super) {
  49800. __extends(ScrollableLegendModel, _super);
  49801. function ScrollableLegendModel() {
  49802. var _this = _super !== null && _super.apply(this, arguments) || this;
  49803. _this.type = ScrollableLegendModel.type;
  49804. return _this;
  49805. }
  49806. /**
  49807. * @param {number} scrollDataIndex
  49808. */
  49809. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  49810. this.option.scrollDataIndex = scrollDataIndex;
  49811. };
  49812. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  49813. var inputPositionParams = getLayoutParams(option);
  49814. _super.prototype.init.call(this, option, parentModel, ecModel);
  49815. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  49816. };
  49817. /**
  49818. * @override
  49819. */
  49820. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  49821. _super.prototype.mergeOption.call(this, option, ecModel);
  49822. mergeAndNormalizeLayoutParams(this, this.option, option);
  49823. };
  49824. ScrollableLegendModel.type = 'legend.scroll';
  49825. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  49826. scrollDataIndex: 0,
  49827. pageButtonItemGap: 5,
  49828. pageButtonGap: null,
  49829. pageButtonPosition: 'end',
  49830. pageFormatter: '{current}/{total}',
  49831. pageIcons: {
  49832. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  49833. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  49834. },
  49835. pageIconColor: '#2f4554',
  49836. pageIconInactiveColor: '#aaa',
  49837. pageIconSize: 15,
  49838. pageTextStyle: {
  49839. color: '#333'
  49840. },
  49841. animationDurationUpdate: 800
  49842. });
  49843. return ScrollableLegendModel;
  49844. }(LegendModel);
  49845. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  49846. var orient = legendModel.getOrient();
  49847. var ignoreSize = [1, 1];
  49848. ignoreSize[orient.index] = 0;
  49849. mergeLayoutParam(target, raw, {
  49850. type: 'box',
  49851. ignoreSize: !!ignoreSize
  49852. });
  49853. }
  49854. var Group$2 = Group;
  49855. var WH = ['width', 'height'];
  49856. var XY = ['x', 'y'];
  49857. var ScrollableLegendView =
  49858. /** @class */
  49859. function (_super) {
  49860. __extends(ScrollableLegendView, _super);
  49861. function ScrollableLegendView() {
  49862. var _this = _super !== null && _super.apply(this, arguments) || this;
  49863. _this.type = ScrollableLegendView.type;
  49864. _this.newlineDisabled = true;
  49865. _this._currentIndex = 0;
  49866. return _this;
  49867. }
  49868. ScrollableLegendView.prototype.init = function () {
  49869. _super.prototype.init.call(this);
  49870. this.group.add(this._containerGroup = new Group$2());
  49871. this._containerGroup.add(this.getContentGroup());
  49872. this.group.add(this._controllerGroup = new Group$2());
  49873. };
  49874. /**
  49875. * @override
  49876. */
  49877. ScrollableLegendView.prototype.resetInner = function () {
  49878. _super.prototype.resetInner.call(this);
  49879. this._controllerGroup.removeAll();
  49880. this._containerGroup.removeClipPath();
  49881. this._containerGroup.__rectSize = null;
  49882. };
  49883. /**
  49884. * @override
  49885. */
  49886. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  49887. var self = this; // Render content items.
  49888. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  49889. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  49890. // e.g., '3/12345' should not overlap with the control arrow button.
  49891. var pageIconSize = legendModel.get('pageIconSize', true);
  49892. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  49893. createPageButton('pagePrev', 0);
  49894. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  49895. controllerGroup.add(new ZRText({
  49896. name: 'pageText',
  49897. style: {
  49898. // Placeholder to calculate a proper layout.
  49899. text: 'xx/xx',
  49900. fill: pageTextStyleModel.getTextColor(),
  49901. font: pageTextStyleModel.getFont(),
  49902. verticalAlign: 'middle',
  49903. align: 'center'
  49904. },
  49905. silent: true
  49906. }));
  49907. createPageButton('pageNext', 1);
  49908. function createPageButton(name, iconIdx) {
  49909. var pageDataIndexName = name + 'DataIndex';
  49910. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  49911. // Buttons will be created in each render, so we do not need
  49912. // to worry about avoiding using legendModel kept in scope.
  49913. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  49914. }, {
  49915. x: -pageIconSizeArr[0] / 2,
  49916. y: -pageIconSizeArr[1] / 2,
  49917. width: pageIconSizeArr[0],
  49918. height: pageIconSizeArr[1]
  49919. });
  49920. icon.name = name;
  49921. controllerGroup.add(icon);
  49922. }
  49923. };
  49924. /**
  49925. * @override
  49926. */
  49927. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  49928. var selectorGroup = this.getSelectorGroup();
  49929. var orientIdx = legendModel.getOrient().index;
  49930. var wh = WH[orientIdx];
  49931. var xy = XY[orientIdx];
  49932. var hw = WH[1 - orientIdx];
  49933. var yx = XY[1 - orientIdx];
  49934. selector && box( // Buttons in selectorGroup always layout horizontally
  49935. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  49936. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  49937. var selectorRect = selectorGroup.getBoundingRect();
  49938. var selectorPos = [-selectorRect.x, -selectorRect.y];
  49939. var processMaxSize = clone(maxSize);
  49940. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  49941. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  49942. if (selector) {
  49943. if (selectorPosition === 'end') {
  49944. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  49945. } else {
  49946. var offset = selectorRect[wh] + selectorButtonGap;
  49947. selectorPos[orientIdx] -= offset;
  49948. mainRect[xy] -= offset;
  49949. }
  49950. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  49951. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  49952. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  49953. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  49954. selectorGroup.x = selectorPos[0];
  49955. selectorGroup.y = selectorPos[1];
  49956. selectorGroup.markRedraw();
  49957. }
  49958. return mainRect;
  49959. };
  49960. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  49961. var contentGroup = this.getContentGroup();
  49962. var containerGroup = this._containerGroup;
  49963. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  49964. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  49965. box( // Buttons in controller are layout always horizontally.
  49966. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  49967. var contentRect = contentGroup.getBoundingRect();
  49968. var controllerRect = controllerGroup.getBoundingRect();
  49969. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  49970. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  49971. // If first rendering, `contentGroup.position` is [0, 0], which
  49972. // does not make sense and may cause unexepcted animation if adopted.
  49973. if (!isFirstRender) {
  49974. contentPos[orientIdx] = contentGroup[xy];
  49975. } // Layout container group based on 0.
  49976. var containerPos = [0, 0];
  49977. var controllerPos = [-controllerRect.x, -controllerRect.y];
  49978. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  49979. if (showController) {
  49980. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  49981. if (pageButtonPosition === 'end') {
  49982. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  49983. } // controller is on the left / top.
  49984. else {
  49985. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  49986. }
  49987. } // Always align controller to content as 'middle'.
  49988. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  49989. contentGroup.setPosition(contentPos);
  49990. containerGroup.setPosition(containerPos);
  49991. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  49992. // mainRect should not be calculated by `this.group.getBoundingRect()`
  49993. // for sake of the overflow.
  49994. var mainRect = {
  49995. x: 0,
  49996. y: 0
  49997. }; // Consider content may be overflow (should be clipped).
  49998. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  49999. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  50000. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  50001. containerGroup.__rectSize = maxSize[wh];
  50002. if (showController) {
  50003. var clipShape = {
  50004. x: 0,
  50005. y: 0
  50006. };
  50007. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  50008. clipShape[hw] = mainRect[hw];
  50009. containerGroup.setClipPath(new Rect({
  50010. shape: clipShape
  50011. })); // Consider content may be larger than container, container rect
  50012. // can not be obtained from `containerGroup.getBoundingRect()`.
  50013. containerGroup.__rectSize = clipShape[wh];
  50014. } else {
  50015. // Do not remove or ignore controller. Keep them set as placeholders.
  50016. controllerGroup.eachChild(function (child) {
  50017. child.attr({
  50018. invisible: true,
  50019. silent: true
  50020. });
  50021. });
  50022. } // Content translate animation.
  50023. var pageInfo = this._getPageInfo(legendModel);
  50024. pageInfo.pageIndex != null && updateProps(contentGroup, {
  50025. x: pageInfo.contentPosition[0],
  50026. y: pageInfo.contentPosition[1]
  50027. }, // When switch from "show controller" to "not show controller", view should be
  50028. // updated immediately without animation, otherwise causes weird effect.
  50029. showController ? legendModel : null);
  50030. this._updatePageInfoView(legendModel, pageInfo);
  50031. return mainRect;
  50032. };
  50033. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  50034. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  50035. scrollDataIndex != null && api.dispatchAction({
  50036. type: 'legendScroll',
  50037. scrollDataIndex: scrollDataIndex,
  50038. legendId: legendModel.id
  50039. });
  50040. };
  50041. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  50042. var controllerGroup = this._controllerGroup;
  50043. each(['pagePrev', 'pageNext'], function (name) {
  50044. var key = name + 'DataIndex';
  50045. var canJump = pageInfo[key] != null;
  50046. var icon = controllerGroup.childOfName(name);
  50047. if (icon) {
  50048. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  50049. icon.cursor = canJump ? 'pointer' : 'default';
  50050. }
  50051. });
  50052. var pageText = controllerGroup.childOfName('pageText');
  50053. var pageFormatter = legendModel.get('pageFormatter');
  50054. var pageIndex = pageInfo.pageIndex;
  50055. var current = pageIndex != null ? pageIndex + 1 : 0;
  50056. var total = pageInfo.pageCount;
  50057. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  50058. current: current,
  50059. total: total
  50060. }));
  50061. };
  50062. /**
  50063. * contentPosition: Array.<number>, null when data item not found.
  50064. * pageIndex: number, null when data item not found.
  50065. * pageCount: number, always be a number, can be 0.
  50066. * pagePrevDataIndex: number, null when no previous page.
  50067. * pageNextDataIndex: number, null when no next page.
  50068. * }
  50069. */
  50070. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  50071. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  50072. var contentGroup = this.getContentGroup();
  50073. var containerRectSize = this._containerGroup.__rectSize;
  50074. var orientIdx = legendModel.getOrient().index;
  50075. var wh = WH[orientIdx];
  50076. var xy = XY[orientIdx];
  50077. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  50078. var children = contentGroup.children();
  50079. var targetItem = children[targetItemIndex];
  50080. var itemCount = children.length;
  50081. var pCount = !itemCount ? 0 : 1;
  50082. var result = {
  50083. contentPosition: [contentGroup.x, contentGroup.y],
  50084. pageCount: pCount,
  50085. pageIndex: pCount - 1,
  50086. pagePrevDataIndex: null,
  50087. pageNextDataIndex: null
  50088. };
  50089. if (!targetItem) {
  50090. return result;
  50091. }
  50092. var targetItemInfo = getItemInfo(targetItem);
  50093. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  50094. // (1) Always align based on the left/top most item.
  50095. // (2) It is user-friendly that the last item shown in the
  50096. // current window is shown at the begining of next window.
  50097. // Otherwise if half of the last item is cut by the window,
  50098. // it will have no chance to display entirely.
  50099. // (3) Consider that item size probably be different, we
  50100. // have calculate pageIndex by size rather than item index,
  50101. // and we can not get page index directly by division.
  50102. // (4) The window is to narrow to contain more than
  50103. // one item, we should make sure that the page can be fliped.
  50104. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  50105. currItemInfo = getItemInfo(children[i]);
  50106. if ( // Half of the last item is out of the window.
  50107. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  50108. // can be started at the current item or the last item.
  50109. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  50110. if (winEndItemInfo.i > winStartItemInfo.i) {
  50111. winStartItemInfo = winEndItemInfo;
  50112. } else {
  50113. // e.g., when page size is smaller than item size.
  50114. winStartItemInfo = currItemInfo;
  50115. }
  50116. if (winStartItemInfo) {
  50117. if (result.pageNextDataIndex == null) {
  50118. result.pageNextDataIndex = winStartItemInfo.i;
  50119. }
  50120. ++result.pageCount;
  50121. }
  50122. }
  50123. winEndItemInfo = currItemInfo;
  50124. }
  50125. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  50126. currItemInfo = getItemInfo(children[i]);
  50127. if ( // If the the end item does not intersect with the window started
  50128. // from the current item, a page can be settled.
  50129. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  50130. winStartItemInfo.i < winEndItemInfo.i) {
  50131. winEndItemInfo = winStartItemInfo;
  50132. if (result.pagePrevDataIndex == null) {
  50133. result.pagePrevDataIndex = winStartItemInfo.i;
  50134. }
  50135. ++result.pageCount;
  50136. ++result.pageIndex;
  50137. }
  50138. winStartItemInfo = currItemInfo;
  50139. }
  50140. return result;
  50141. function getItemInfo(el) {
  50142. if (el) {
  50143. var itemRect = el.getBoundingRect();
  50144. var start = itemRect[xy] + el[xy];
  50145. return {
  50146. s: start,
  50147. e: start + itemRect[wh],
  50148. i: el.__legendDataIndex
  50149. };
  50150. }
  50151. }
  50152. function intersect(itemInfo, winStart) {
  50153. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  50154. }
  50155. };
  50156. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  50157. if (!this._showController) {
  50158. return 0;
  50159. }
  50160. var index;
  50161. var contentGroup = this.getContentGroup();
  50162. var defaultIndex;
  50163. contentGroup.eachChild(function (child, idx) {
  50164. var legendDataIdx = child.__legendDataIndex; // FIXME
  50165. // If the given targetDataIndex (from model) is illegal,
  50166. // we use defaultIndex. But the index on the legend model and
  50167. // action payload is still illegal. That case will not be
  50168. // changed until some scenario requires.
  50169. if (defaultIndex == null && legendDataIdx != null) {
  50170. defaultIndex = idx;
  50171. }
  50172. if (legendDataIdx === targetDataIndex) {
  50173. index = idx;
  50174. }
  50175. });
  50176. return index != null ? index : defaultIndex;
  50177. };
  50178. ScrollableLegendView.type = 'legend.scroll';
  50179. return ScrollableLegendView;
  50180. }(LegendView);
  50181. /*
  50182. * Licensed to the Apache Software Foundation (ASF) under one
  50183. * or more contributor license agreements. See the NOTICE file
  50184. * distributed with this work for additional information
  50185. * regarding copyright ownership. The ASF licenses this file
  50186. * to you under the Apache License, Version 2.0 (the
  50187. * "License"); you may not use this file except in compliance
  50188. * with the License. You may obtain a copy of the License at
  50189. *
  50190. * http://www.apache.org/licenses/LICENSE-2.0
  50191. *
  50192. * Unless required by applicable law or agreed to in writing,
  50193. * software distributed under the License is distributed on an
  50194. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50195. * KIND, either express or implied. See the License for the
  50196. * specific language governing permissions and limitations
  50197. * under the License.
  50198. */
  50199. /**
  50200. * AUTO-GENERATED FILE. DO NOT MODIFY.
  50201. */
  50202. /*
  50203. * Licensed to the Apache Software Foundation (ASF) under one
  50204. * or more contributor license agreements. See the NOTICE file
  50205. * distributed with this work for additional information
  50206. * regarding copyright ownership. The ASF licenses this file
  50207. * to you under the Apache License, Version 2.0 (the
  50208. * "License"); you may not use this file except in compliance
  50209. * with the License. You may obtain a copy of the License at
  50210. *
  50211. * http://www.apache.org/licenses/LICENSE-2.0
  50212. *
  50213. * Unless required by applicable law or agreed to in writing,
  50214. * software distributed under the License is distributed on an
  50215. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50216. * KIND, either express or implied. See the License for the
  50217. * specific language governing permissions and limitations
  50218. * under the License.
  50219. */
  50220. function installScrollableLegendAction(registers) {
  50221. /**
  50222. * @event legendScroll
  50223. * @type {Object}
  50224. * @property {string} type 'legendScroll'
  50225. * @property {string} scrollDataIndex
  50226. */
  50227. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  50228. var scrollDataIndex = payload.scrollDataIndex;
  50229. scrollDataIndex != null && ecModel.eachComponent({
  50230. mainType: 'legend',
  50231. subType: 'scroll',
  50232. query: payload
  50233. }, function (legendModel) {
  50234. legendModel.setScrollDataIndex(scrollDataIndex);
  50235. });
  50236. });
  50237. }
  50238. function install$i(registers) {
  50239. use(install$h);
  50240. registers.registerComponentModel(ScrollableLegendModel);
  50241. registers.registerComponentView(ScrollableLegendView);
  50242. installScrollableLegendAction(registers);
  50243. }
  50244. function install$j(registers) {
  50245. use(install$h);
  50246. use(install$i);
  50247. }
  50248. var InsideZoomModel =
  50249. /** @class */
  50250. function (_super) {
  50251. __extends(InsideZoomModel, _super);
  50252. function InsideZoomModel() {
  50253. var _this = _super !== null && _super.apply(this, arguments) || this;
  50254. _this.type = InsideZoomModel.type;
  50255. return _this;
  50256. }
  50257. InsideZoomModel.type = 'dataZoom.inside';
  50258. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  50259. disabled: false,
  50260. zoomLock: false,
  50261. zoomOnMouseWheel: true,
  50262. moveOnMouseMove: true,
  50263. moveOnMouseWheel: false,
  50264. preventDefaultMouseMove: true
  50265. });
  50266. return InsideZoomModel;
  50267. }(DataZoomModel);
  50268. var RoamController =
  50269. /** @class */
  50270. function (_super) {
  50271. __extends(RoamController, _super);
  50272. function RoamController(zr) {
  50273. var _this = _super.call(this) || this;
  50274. _this._zr = zr; // Avoid two roamController bind the same handler
  50275. var mousedownHandler = bind(_this._mousedownHandler, _this);
  50276. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  50277. var mouseupHandler = bind(_this._mouseupHandler, _this);
  50278. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  50279. var pinchHandler = bind(_this._pinchHandler, _this);
  50280. /**
  50281. * Notice: only enable needed types. For example, if 'zoom'
  50282. * is not needed, 'zoom' should not be enabled, otherwise
  50283. * default mousewheel behaviour (scroll page) will be disabled.
  50284. */
  50285. _this.enable = function (controlType, opt) {
  50286. // Disable previous first
  50287. this.disable();
  50288. this._opt = defaults(clone(opt) || {}, {
  50289. zoomOnMouseWheel: true,
  50290. moveOnMouseMove: true,
  50291. // By default, wheel do not trigger move.
  50292. moveOnMouseWheel: false,
  50293. preventDefaultMouseMove: true
  50294. });
  50295. if (controlType == null) {
  50296. controlType = true;
  50297. }
  50298. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  50299. zr.on('mousedown', mousedownHandler);
  50300. zr.on('mousemove', mousemoveHandler);
  50301. zr.on('mouseup', mouseupHandler);
  50302. }
  50303. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  50304. zr.on('mousewheel', mousewheelHandler);
  50305. zr.on('pinch', pinchHandler);
  50306. }
  50307. };
  50308. _this.disable = function () {
  50309. zr.off('mousedown', mousedownHandler);
  50310. zr.off('mousemove', mousemoveHandler);
  50311. zr.off('mouseup', mouseupHandler);
  50312. zr.off('mousewheel', mousewheelHandler);
  50313. zr.off('pinch', pinchHandler);
  50314. };
  50315. return _this;
  50316. }
  50317. RoamController.prototype.isDragging = function () {
  50318. return this._dragging;
  50319. };
  50320. RoamController.prototype.isPinching = function () {
  50321. return this._pinching;
  50322. };
  50323. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  50324. this.pointerChecker = pointerChecker;
  50325. };
  50326. RoamController.prototype.dispose = function () {
  50327. this.disable();
  50328. };
  50329. RoamController.prototype._mousedownHandler = function (e) {
  50330. if (isMiddleOrRightButtonOnMouseUpDown(e) || e.target && e.target.draggable) {
  50331. return;
  50332. }
  50333. var x = e.offsetX;
  50334. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  50335. // Mouse can be out of target when mouse moving.
  50336. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  50337. this._x = x;
  50338. this._y = y;
  50339. this._dragging = true;
  50340. }
  50341. };
  50342. RoamController.prototype._mousemoveHandler = function (e) {
  50343. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  50344. return;
  50345. }
  50346. var x = e.offsetX;
  50347. var y = e.offsetY;
  50348. var oldX = this._x;
  50349. var oldY = this._y;
  50350. var dx = x - oldX;
  50351. var dy = y - oldY;
  50352. this._x = x;
  50353. this._y = y;
  50354. this._opt.preventDefaultMouseMove && stop(e.event);
  50355. trigger$1(this, 'pan', 'moveOnMouseMove', e, {
  50356. dx: dx,
  50357. dy: dy,
  50358. oldX: oldX,
  50359. oldY: oldY,
  50360. newX: x,
  50361. newY: y,
  50362. isAvailableBehavior: null
  50363. });
  50364. };
  50365. RoamController.prototype._mouseupHandler = function (e) {
  50366. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  50367. this._dragging = false;
  50368. }
  50369. };
  50370. RoamController.prototype._mousewheelHandler = function (e) {
  50371. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  50372. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  50373. var wheelDelta = e.wheelDelta;
  50374. var absWheelDeltaDelta = Math.abs(wheelDelta);
  50375. var originX = e.offsetX;
  50376. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  50377. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  50378. return;
  50379. } // If both `shouldZoom` and `shouldMove` is true, trigger
  50380. // their event both, and the final behavior is determined
  50381. // by event listener themselves.
  50382. if (shouldZoom) {
  50383. // Convenience:
  50384. // Mac and VM Windows on Mac: scroll up: zoom out.
  50385. // Windows: scroll up: zoom in.
  50386. // FIXME: Should do more test in different environment.
  50387. // wheelDelta is too complicated in difference nvironment
  50388. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  50389. // although it has been normallized by zrender.
  50390. // wheelDelta of mouse wheel is bigger than touch pad.
  50391. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  50392. var scale = wheelDelta > 0 ? factor : 1 / factor;
  50393. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  50394. scale: scale,
  50395. originX: originX,
  50396. originY: originY,
  50397. isAvailableBehavior: null
  50398. });
  50399. }
  50400. if (shouldMove) {
  50401. // FIXME: Should do more test in different environment.
  50402. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  50403. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  50404. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  50405. scrollDelta: scrollDelta,
  50406. originX: originX,
  50407. originY: originY,
  50408. isAvailableBehavior: null
  50409. });
  50410. }
  50411. };
  50412. RoamController.prototype._pinchHandler = function (e) {
  50413. if (isTaken(this._zr, 'globalPan')) {
  50414. return;
  50415. }
  50416. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  50417. checkPointerAndTrigger(this, 'zoom', null, e, {
  50418. scale: scale,
  50419. originX: e.pinchX,
  50420. originY: e.pinchY,
  50421. isAvailableBehavior: null
  50422. });
  50423. };
  50424. return RoamController;
  50425. }(Eventful);
  50426. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  50427. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  50428. // When mouse is out of roamController rect,
  50429. // default befavoius should not be be disabled, otherwise
  50430. // page sliding is disabled, contrary to expectation.
  50431. stop(e.event);
  50432. trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent);
  50433. }
  50434. }
  50435. function trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent) {
  50436. // Also provide behavior checker for event listener, for some case that
  50437. // multiple components share one listener.
  50438. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  50439. controller.trigger(eventName, contollerEvent);
  50440. } // settings: {
  50441. // zoomOnMouseWheel
  50442. // moveOnMouseMove
  50443. // moveOnMouseWheel
  50444. // }
  50445. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  50446. function isAvailableBehavior(behaviorToCheck, e, settings) {
  50447. var setting = settings[behaviorToCheck];
  50448. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  50449. }
  50450. var inner$f = makeInner();
  50451. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  50452. inner$f(api).coordSysRecordMap.each(function (coordSysRecord) {
  50453. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  50454. if (dzInfo) {
  50455. dzInfo.getRange = getRange;
  50456. }
  50457. });
  50458. }
  50459. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  50460. var coordSysRecordMap = inner$f(api).coordSysRecordMap;
  50461. var coordSysKeyArr = coordSysRecordMap.keys();
  50462. for (var i = 0; i < coordSysKeyArr.length; i++) {
  50463. var coordSysKey = coordSysKeyArr[i];
  50464. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  50465. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  50466. if (dataZoomInfoMap) {
  50467. var dzUid = dataZoomModel.uid;
  50468. var dzInfo = dataZoomInfoMap.get(dzUid);
  50469. if (dzInfo) {
  50470. dataZoomInfoMap.removeKey(dzUid);
  50471. if (!dataZoomInfoMap.keys().length) {
  50472. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  50473. }
  50474. }
  50475. }
  50476. }
  50477. }
  50478. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  50479. if (coordSysRecord) {
  50480. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  50481. var controller = coordSysRecord.controller;
  50482. controller && controller.dispose();
  50483. }
  50484. }
  50485. function createCoordSysRecord(api, coordSysModel) {
  50486. // These init props will never change after record created.
  50487. var coordSysRecord = {
  50488. model: coordSysModel,
  50489. containsPoint: curry(containsPoint, coordSysModel),
  50490. dispatchAction: curry(dispatchAction, api),
  50491. dataZoomInfoMap: null,
  50492. controller: null
  50493. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  50494. // because coordSysRecord not completed yet.
  50495. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  50496. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  50497. controller.on(eventName, function (event) {
  50498. var batch = [];
  50499. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  50500. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  50501. // moveOnMouseWheel, ...) enabled.
  50502. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  50503. return;
  50504. }
  50505. var method = (dzInfo.getRange || {})[eventName];
  50506. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  50507. !dzInfo.model.get('disabled', true) && range && batch.push({
  50508. dataZoomId: dzInfo.model.id,
  50509. start: range[0],
  50510. end: range[1]
  50511. });
  50512. });
  50513. batch.length && coordSysRecord.dispatchAction(batch);
  50514. });
  50515. });
  50516. return coordSysRecord;
  50517. }
  50518. /**
  50519. * This action will be throttled.
  50520. */
  50521. function dispatchAction(api, batch) {
  50522. api.dispatchAction({
  50523. type: 'dataZoom',
  50524. animation: {
  50525. easing: 'cubicOut',
  50526. duration: 100
  50527. },
  50528. batch: batch
  50529. });
  50530. }
  50531. function containsPoint(coordSysModel, e, x, y) {
  50532. return coordSysModel.coordinateSystem.containPoint([x, y]);
  50533. }
  50534. /**
  50535. * Merge roamController settings when multiple dataZooms share one roamController.
  50536. */
  50537. function mergeControllerParams(dataZoomInfoMap) {
  50538. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  50539. // as string, it is probably revert to reserved word by compress tool. See #7411.
  50540. var prefix = 'type_';
  50541. var typePriority = {
  50542. 'type_true': 2,
  50543. 'type_move': 1,
  50544. 'type_false': 0,
  50545. 'type_undefined': -1
  50546. };
  50547. var preventDefaultMouseMove = true;
  50548. dataZoomInfoMap.each(function (dataZoomInfo) {
  50549. var dataZoomModel = dataZoomInfo.model;
  50550. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  50551. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  50552. controlType = oneType;
  50553. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  50554. // users may be confused why it does not work when multiple insideZooms exist.
  50555. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  50556. });
  50557. return {
  50558. controlType: controlType,
  50559. opt: {
  50560. // RoamController will enable all of these functionalities,
  50561. // and the final behavior is determined by its event listener
  50562. // provided by each inside zoom.
  50563. zoomOnMouseWheel: true,
  50564. moveOnMouseMove: true,
  50565. moveOnMouseWheel: true,
  50566. preventDefaultMouseMove: !!preventDefaultMouseMove
  50567. }
  50568. };
  50569. }
  50570. function installDataZoomRoamProcessor(registers) {
  50571. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  50572. var apiInner = inner$f(api);
  50573. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  50574. coordSysRecordMap.each(function (coordSysRecord) {
  50575. // `coordSysRecordMap` always exists (becuase it hold the `roam controller`, which should
  50576. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  50577. coordSysRecord.dataZoomInfoMap = null;
  50578. });
  50579. ecModel.eachComponent({
  50580. mainType: 'dataZoom',
  50581. subType: 'inside'
  50582. }, function (dataZoomModel) {
  50583. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  50584. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  50585. var coordSysUid = dzCoordSysInfo.model.uid;
  50586. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  50587. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  50588. dataZoomInfoMap.set(dataZoomModel.uid, {
  50589. dzReferCoordSysInfo: dzCoordSysInfo,
  50590. model: dataZoomModel,
  50591. getRange: null
  50592. });
  50593. });
  50594. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  50595. // (2) Clear coord sys if not refered by any dataZoom.
  50596. coordSysRecordMap.each(function (coordSysRecord) {
  50597. var controller = coordSysRecord.controller;
  50598. var firstDzInfo;
  50599. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  50600. if (dataZoomInfoMap) {
  50601. var firstDzKey = dataZoomInfoMap.keys()[0];
  50602. if (firstDzKey != null) {
  50603. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  50604. }
  50605. }
  50606. if (!firstDzInfo) {
  50607. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  50608. return;
  50609. }
  50610. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  50611. controller.enable(controllerParams.controlType, controllerParams.opt);
  50612. controller.setPointerChecker(coordSysRecord.containsPoint);
  50613. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  50614. });
  50615. });
  50616. }
  50617. var InsideZoomView =
  50618. /** @class */
  50619. function (_super) {
  50620. __extends(InsideZoomView, _super);
  50621. function InsideZoomView() {
  50622. var _this = _super !== null && _super.apply(this, arguments) || this;
  50623. _this.type = 'dataZoom.inside';
  50624. return _this;
  50625. }
  50626. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  50627. _super.prototype.render.apply(this, arguments);
  50628. if (dataZoomModel.noTarget()) {
  50629. this._clear();
  50630. return;
  50631. } // Hence the `throttle` util ensures to preserve command order,
  50632. // here simply updating range all the time will not cause missing
  50633. // any of the the roam change.
  50634. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  50635. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  50636. pan: bind(getRangeHandlers.pan, this),
  50637. zoom: bind(getRangeHandlers.zoom, this),
  50638. scrollMove: bind(getRangeHandlers.scrollMove, this)
  50639. });
  50640. };
  50641. InsideZoomView.prototype.dispose = function () {
  50642. this._clear();
  50643. _super.prototype.dispose.apply(this, arguments);
  50644. };
  50645. InsideZoomView.prototype._clear = function () {
  50646. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  50647. this.range = null;
  50648. };
  50649. InsideZoomView.type = 'dataZoom.inside';
  50650. return InsideZoomView;
  50651. }(DataZoomView);
  50652. var getRangeHandlers = {
  50653. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  50654. var lastRange = this.range;
  50655. var range = lastRange.slice(); // Calculate transform by the first axis.
  50656. var axisModel = coordSysInfo.axisModels[0];
  50657. if (!axisModel) {
  50658. return;
  50659. }
  50660. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  50661. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  50662. var scale = Math.max(1 / e.scale, 0);
  50663. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  50664. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  50665. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  50666. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  50667. this.range = range;
  50668. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  50669. return range;
  50670. }
  50671. },
  50672. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  50673. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  50674. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  50675. }),
  50676. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  50677. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  50678. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  50679. })
  50680. };
  50681. function makeMover(getPercentDelta) {
  50682. return function (coordSysInfo, coordSysMainType, controller, e) {
  50683. var lastRange = this.range;
  50684. var range = lastRange.slice(); // Calculate transform by the first axis.
  50685. var axisModel = coordSysInfo.axisModels[0];
  50686. if (!axisModel) {
  50687. return;
  50688. }
  50689. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  50690. sliderMove(percentDelta, range, [0, 100], 'all');
  50691. this.range = range;
  50692. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  50693. return range;
  50694. }
  50695. };
  50696. }
  50697. var getDirectionInfo = {
  50698. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  50699. var axis = axisModel.axis;
  50700. var ret = {};
  50701. var rect = coordSysInfo.model.coordinateSystem.getRect();
  50702. oldPoint = oldPoint || [0, 0];
  50703. if (axis.dim === 'x') {
  50704. ret.pixel = newPoint[0] - oldPoint[0];
  50705. ret.pixelLength = rect.width;
  50706. ret.pixelStart = rect.x;
  50707. ret.signal = axis.inverse ? 1 : -1;
  50708. } else {
  50709. // axis.dim === 'y'
  50710. ret.pixel = newPoint[1] - oldPoint[1];
  50711. ret.pixelLength = rect.height;
  50712. ret.pixelStart = rect.y;
  50713. ret.signal = axis.inverse ? -1 : 1;
  50714. }
  50715. return ret;
  50716. },
  50717. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  50718. var axis = axisModel.axis;
  50719. var ret = {};
  50720. var polar = coordSysInfo.model.coordinateSystem;
  50721. var radiusExtent = polar.getRadiusAxis().getExtent();
  50722. var angleExtent = polar.getAngleAxis().getExtent();
  50723. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  50724. newPoint = polar.pointToCoord(newPoint);
  50725. if (axisModel.mainType === 'radiusAxis') {
  50726. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  50727. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  50728. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  50729. ret.pixelStart = radiusExtent[0];
  50730. ret.signal = axis.inverse ? 1 : -1;
  50731. } else {
  50732. // 'angleAxis'
  50733. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  50734. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  50735. ret.pixelLength = angleExtent[1] - angleExtent[0];
  50736. ret.pixelStart = angleExtent[0];
  50737. ret.signal = axis.inverse ? -1 : 1;
  50738. }
  50739. return ret;
  50740. },
  50741. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  50742. var axis = axisModel.axis;
  50743. var rect = coordSysInfo.model.coordinateSystem.getRect();
  50744. var ret = {};
  50745. oldPoint = oldPoint || [0, 0];
  50746. if (axis.orient === 'horizontal') {
  50747. ret.pixel = newPoint[0] - oldPoint[0];
  50748. ret.pixelLength = rect.width;
  50749. ret.pixelStart = rect.x;
  50750. ret.signal = axis.inverse ? 1 : -1;
  50751. } else {
  50752. // 'vertical'
  50753. ret.pixel = newPoint[1] - oldPoint[1];
  50754. ret.pixelLength = rect.height;
  50755. ret.pixelStart = rect.y;
  50756. ret.signal = axis.inverse ? -1 : 1;
  50757. }
  50758. return ret;
  50759. }
  50760. };
  50761. function install$k(registers) {
  50762. installCommon(registers);
  50763. registers.registerComponentModel(InsideZoomModel);
  50764. registers.registerComponentView(InsideZoomView);
  50765. installDataZoomRoamProcessor(registers);
  50766. }
  50767. var SliderZoomModel =
  50768. /** @class */
  50769. function (_super) {
  50770. __extends(SliderZoomModel, _super);
  50771. function SliderZoomModel() {
  50772. var _this = _super !== null && _super.apply(this, arguments) || this;
  50773. _this.type = SliderZoomModel.type;
  50774. return _this;
  50775. }
  50776. SliderZoomModel.type = 'dataZoom.slider';
  50777. SliderZoomModel.layoutMode = 'box';
  50778. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  50779. show: true,
  50780. // deault value can only be drived in view stage.
  50781. right: 'ph',
  50782. top: 'ph',
  50783. width: 'ph',
  50784. height: 'ph',
  50785. left: null,
  50786. bottom: null,
  50787. borderColor: '#d2dbee',
  50788. borderRadius: 3,
  50789. backgroundColor: 'rgba(47,69,84,0)',
  50790. // dataBackgroundColor: '#ddd',
  50791. dataBackground: {
  50792. lineStyle: {
  50793. color: '#d2dbee',
  50794. width: 0.5
  50795. },
  50796. areaStyle: {
  50797. color: '#d2dbee',
  50798. opacity: 0.2
  50799. }
  50800. },
  50801. selectedDataBackground: {
  50802. lineStyle: {
  50803. color: '#8fb0f7',
  50804. width: 0.5
  50805. },
  50806. areaStyle: {
  50807. color: '#8fb0f7',
  50808. opacity: 0.2
  50809. }
  50810. },
  50811. // Color of selected window.
  50812. fillerColor: 'rgba(135,175,274,0.2)',
  50813. 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',
  50814. // Percent of the slider height
  50815. handleSize: '100%',
  50816. handleStyle: {
  50817. color: '#fff',
  50818. borderColor: '#ACB8D1'
  50819. },
  50820. moveHandleSize: 7,
  50821. 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',
  50822. moveHandleStyle: {
  50823. color: '#D2DBEE',
  50824. opacity: 0.7
  50825. },
  50826. showDetail: true,
  50827. showDataShadow: 'auto',
  50828. realtime: true,
  50829. zoomLock: false,
  50830. textStyle: {
  50831. color: '#6E7079'
  50832. },
  50833. brushSelect: true,
  50834. brushStyle: {
  50835. color: 'rgba(135,175,274,0.15)'
  50836. },
  50837. emphasis: {
  50838. handleStyle: {
  50839. borderColor: '#8FB0F7'
  50840. },
  50841. moveHandleStyle: {
  50842. color: '#8FB0F7'
  50843. }
  50844. }
  50845. });
  50846. return SliderZoomModel;
  50847. }(DataZoomModel);
  50848. var Rect$1 = Rect; // Constants
  50849. var DEFAULT_LOCATION_EDGE_GAP = 7;
  50850. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  50851. var DEFAULT_FILLER_SIZE = 30;
  50852. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  50853. var HORIZONTAL = 'horizontal';
  50854. var VERTICAL = 'vertical';
  50855. var LABEL_GAP = 5;
  50856. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  50857. var REALTIME_ANIMATION_CONFIG = {
  50858. easing: 'cubicOut',
  50859. duration: 100
  50860. };
  50861. var SliderZoomView =
  50862. /** @class */
  50863. function (_super) {
  50864. __extends(SliderZoomView, _super);
  50865. function SliderZoomView() {
  50866. var _this = _super !== null && _super.apply(this, arguments) || this;
  50867. _this.type = SliderZoomView.type;
  50868. _this._displayables = {};
  50869. return _this;
  50870. }
  50871. SliderZoomView.prototype.init = function (ecModel, api) {
  50872. this.api = api; // A unique handler for each dataZoom component
  50873. this._onBrush = bind(this._onBrush, this);
  50874. this._onBrushEnd = bind(this._onBrushEnd, this);
  50875. };
  50876. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  50877. _super.prototype.render.apply(this, arguments);
  50878. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  50879. this._orient = dataZoomModel.getOrient();
  50880. if (dataZoomModel.get('show') === false) {
  50881. this.group.removeAll();
  50882. return;
  50883. }
  50884. if (dataZoomModel.noTarget()) {
  50885. this._clear();
  50886. this.group.removeAll();
  50887. return;
  50888. } // Notice: this._resetInterval() should not be executed when payload.type
  50889. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  50890. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  50891. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  50892. this._buildView();
  50893. }
  50894. this._updateView();
  50895. };
  50896. SliderZoomView.prototype.dispose = function () {
  50897. this._clear();
  50898. _super.prototype.dispose.apply(this, arguments);
  50899. };
  50900. SliderZoomView.prototype._clear = function () {
  50901. clear(this, '_dispatchZoomAction');
  50902. var zr = this.api.getZr();
  50903. zr.off('mousemove', this._onBrush);
  50904. zr.off('mouseup', this._onBrushEnd);
  50905. };
  50906. SliderZoomView.prototype._buildView = function () {
  50907. var thisGroup = this.group;
  50908. thisGroup.removeAll();
  50909. this._brushing = false;
  50910. this._displayables.brushRect = null;
  50911. this._resetLocation();
  50912. this._resetInterval();
  50913. var barGroup = this._displayables.sliderGroup = new Group();
  50914. this._renderBackground();
  50915. this._renderHandle();
  50916. this._renderDataShadow();
  50917. thisGroup.add(barGroup);
  50918. this._positionGroup();
  50919. };
  50920. SliderZoomView.prototype._resetLocation = function () {
  50921. var dataZoomModel = this.dataZoomModel;
  50922. var api = this.api;
  50923. var showMoveHandle = dataZoomModel.get('brushSelect');
  50924. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  50925. // auto-adapt according to target grid.
  50926. var coordRect = this._findCoordRect();
  50927. var ecSize = {
  50928. width: api.getWidth(),
  50929. height: api.getHeight()
  50930. }; // Default align by coordinate system rect.
  50931. var positionInfo = this._orient === HORIZONTAL ? {
  50932. // Why using 'right', because right should be used in vertical,
  50933. // and it is better to be consistent for dealing with position param merge.
  50934. right: ecSize.width - coordRect.x - coordRect.width,
  50935. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  50936. width: coordRect.width,
  50937. height: DEFAULT_FILLER_SIZE
  50938. } : {
  50939. right: DEFAULT_LOCATION_EDGE_GAP,
  50940. top: coordRect.y,
  50941. width: DEFAULT_FILLER_SIZE,
  50942. height: coordRect.height
  50943. }; // Do not write back to option and replace value 'ph', because
  50944. // the 'ph' value should be recalculated when resize.
  50945. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  50946. each(['right', 'top', 'width', 'height'], function (name) {
  50947. if (layoutParams[name] === 'ph') {
  50948. layoutParams[name] = positionInfo[name];
  50949. }
  50950. });
  50951. var layoutRect = getLayoutRect(layoutParams, ecSize);
  50952. this._location = {
  50953. x: layoutRect.x,
  50954. y: layoutRect.y
  50955. };
  50956. this._size = [layoutRect.width, layoutRect.height];
  50957. this._orient === VERTICAL && this._size.reverse();
  50958. };
  50959. SliderZoomView.prototype._positionGroup = function () {
  50960. var thisGroup = this.group;
  50961. var location = this._location;
  50962. var orient = this._orient; // Just use the first axis to determine mapping.
  50963. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  50964. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  50965. var sliderGroup = this._displayables.sliderGroup;
  50966. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  50967. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  50968. scaleY: otherAxisInverse ? 1 : -1,
  50969. scaleX: 1
  50970. } : orient === HORIZONTAL && inverse ? {
  50971. scaleY: otherAxisInverse ? 1 : -1,
  50972. scaleX: -1
  50973. } : orient === VERTICAL && !inverse ? {
  50974. scaleY: otherAxisInverse ? -1 : 1,
  50975. scaleX: 1,
  50976. rotation: Math.PI / 2
  50977. } // Dont use Math.PI, considering shadow direction.
  50978. : {
  50979. scaleY: otherAxisInverse ? -1 : 1,
  50980. scaleX: -1,
  50981. rotation: Math.PI / 2
  50982. }); // Position barGroup
  50983. var rect = thisGroup.getBoundingRect([sliderGroup]);
  50984. thisGroup.x = location.x - rect.x;
  50985. thisGroup.y = location.y - rect.y;
  50986. thisGroup.markRedraw();
  50987. };
  50988. SliderZoomView.prototype._getViewExtent = function () {
  50989. return [0, this._size[0]];
  50990. };
  50991. SliderZoomView.prototype._renderBackground = function () {
  50992. var dataZoomModel = this.dataZoomModel;
  50993. var size = this._size;
  50994. var barGroup = this._displayables.sliderGroup;
  50995. var brushSelect = dataZoomModel.get('brushSelect');
  50996. barGroup.add(new Rect$1({
  50997. silent: true,
  50998. shape: {
  50999. x: 0,
  51000. y: 0,
  51001. width: size[0],
  51002. height: size[1]
  51003. },
  51004. style: {
  51005. fill: dataZoomModel.get('backgroundColor')
  51006. },
  51007. z2: -40
  51008. })); // Click panel, over shadow, below handles.
  51009. var clickPanel = new Rect$1({
  51010. shape: {
  51011. x: 0,
  51012. y: 0,
  51013. width: size[0],
  51014. height: size[1]
  51015. },
  51016. style: {
  51017. fill: 'transparent'
  51018. },
  51019. z2: 0,
  51020. onclick: bind(this._onClickPanel, this)
  51021. });
  51022. var zr = this.api.getZr();
  51023. if (brushSelect) {
  51024. clickPanel.on('mousedown', this._onBrushStart, this);
  51025. clickPanel.cursor = 'crosshair';
  51026. zr.on('mousemove', this._onBrush);
  51027. zr.on('mouseup', this._onBrushEnd);
  51028. } else {
  51029. zr.off('mousemove', this._onBrush);
  51030. zr.off('mouseup', this._onBrushEnd);
  51031. }
  51032. barGroup.add(clickPanel);
  51033. };
  51034. SliderZoomView.prototype._renderDataShadow = function () {
  51035. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  51036. this._displayables.dataShadowSegs = [];
  51037. if (!info) {
  51038. return;
  51039. }
  51040. var size = this._size;
  51041. var seriesModel = info.series;
  51042. var data = seriesModel.getRawData();
  51043. var otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() // @see candlestick
  51044. : info.otherDim;
  51045. if (otherDim == null) {
  51046. return;
  51047. }
  51048. var otherDataExtent = data.getDataExtent(otherDim); // Nice extent.
  51049. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  51050. otherDataExtent = [otherDataExtent[0] - otherOffset, otherDataExtent[1] + otherOffset];
  51051. var otherShadowExtent = [0, size[1]];
  51052. var thisShadowExtent = [0, size[0]];
  51053. var areaPoints = [[size[0], 0], [0, 0]];
  51054. var linePoints = [];
  51055. var step = thisShadowExtent[1] / (data.count() - 1);
  51056. var thisCoord = 0; // Optimize for large data shadow
  51057. var stride = Math.round(data.count() / size[0]);
  51058. var lastIsEmpty;
  51059. data.each([otherDim], function (value, index) {
  51060. if (stride > 0 && index % stride) {
  51061. thisCoord += step;
  51062. return;
  51063. } // FIXME
  51064. // Should consider axis.min/axis.max when drawing dataShadow.
  51065. // FIXME
  51066. // 应该使用统一的空判断?还是在list里进行空判断?
  51067. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  51068. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent, otherShadowExtent, true); // Attempt to draw data shadow precisely when there are empty value.
  51069. if (isEmpty && !lastIsEmpty && index) {
  51070. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  51071. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  51072. } else if (!isEmpty && lastIsEmpty) {
  51073. areaPoints.push([thisCoord, 0]);
  51074. linePoints.push([thisCoord, 0]);
  51075. }
  51076. areaPoints.push([thisCoord, otherCoord]);
  51077. linePoints.push([thisCoord, otherCoord]);
  51078. thisCoord += step;
  51079. lastIsEmpty = isEmpty;
  51080. });
  51081. var dataZoomModel = this.dataZoomModel;
  51082. function createDataShadowGroup(isSelectedArea) {
  51083. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  51084. var group = new Group();
  51085. var polygon = new Polygon({
  51086. shape: {
  51087. points: areaPoints
  51088. },
  51089. segmentIgnoreThreshold: 1,
  51090. style: model.getModel('areaStyle').getAreaStyle(),
  51091. silent: true,
  51092. z2: -20
  51093. });
  51094. var polyline = new Polyline({
  51095. shape: {
  51096. points: linePoints
  51097. },
  51098. segmentIgnoreThreshold: 1,
  51099. style: model.getModel('lineStyle').getLineStyle(),
  51100. silent: true,
  51101. z2: -19
  51102. });
  51103. group.add(polygon);
  51104. group.add(polyline);
  51105. return group;
  51106. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  51107. for (var i = 0; i < 3; i++) {
  51108. var group = createDataShadowGroup(i === 1);
  51109. this._displayables.sliderGroup.add(group);
  51110. this._displayables.dataShadowSegs.push(group);
  51111. }
  51112. };
  51113. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  51114. var dataZoomModel = this.dataZoomModel;
  51115. var showDataShadow = dataZoomModel.get('showDataShadow');
  51116. if (showDataShadow === false) {
  51117. return;
  51118. } // Find a representative series.
  51119. var result;
  51120. var ecModel = this.ecModel;
  51121. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  51122. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  51123. each(seriesModels, function (seriesModel) {
  51124. if (result) {
  51125. return;
  51126. }
  51127. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  51128. return;
  51129. }
  51130. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  51131. var otherDim = getOtherDim(axisDim);
  51132. var otherAxisInverse;
  51133. var coordSys = seriesModel.coordinateSystem;
  51134. if (otherDim != null && coordSys.getOtherAxis) {
  51135. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  51136. }
  51137. otherDim = seriesModel.getData().mapDimension(otherDim);
  51138. result = {
  51139. thisAxis: thisAxis,
  51140. series: seriesModel,
  51141. thisDim: axisDim,
  51142. otherDim: otherDim,
  51143. otherAxisInverse: otherAxisInverse
  51144. };
  51145. }, this);
  51146. }, this);
  51147. return result;
  51148. };
  51149. SliderZoomView.prototype._renderHandle = function () {
  51150. var thisGroup = this.group;
  51151. var displayables = this._displayables;
  51152. var handles = displayables.handles = [null, null];
  51153. var handleLabels = displayables.handleLabels = [null, null];
  51154. var sliderGroup = this._displayables.sliderGroup;
  51155. var size = this._size;
  51156. var dataZoomModel = this.dataZoomModel;
  51157. var api = this.api;
  51158. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  51159. var brushSelect = dataZoomModel.get('brushSelect');
  51160. var filler = displayables.filler = new Rect$1({
  51161. silent: brushSelect,
  51162. style: {
  51163. fill: dataZoomModel.get('fillerColor')
  51164. },
  51165. textConfig: {
  51166. position: 'inside'
  51167. }
  51168. });
  51169. sliderGroup.add(filler); // Frame border.
  51170. sliderGroup.add(new Rect$1({
  51171. silent: true,
  51172. subPixelOptimize: true,
  51173. shape: {
  51174. x: 0,
  51175. y: 0,
  51176. width: size[0],
  51177. height: size[1],
  51178. r: borderRadius
  51179. },
  51180. style: {
  51181. stroke: dataZoomModel.get('dataBackgroundColor') // deprecated option
  51182. || dataZoomModel.get('borderColor'),
  51183. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  51184. fill: 'rgba(0,0,0,0)'
  51185. }
  51186. })); // Left and right handle to resize
  51187. each([0, 1], function (handleIndex) {
  51188. var iconStr = dataZoomModel.get('handleIcon');
  51189. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  51190. // Compatitable with the old icon parsers. Which can use a path string without path://
  51191. iconStr = 'path://' + iconStr;
  51192. if ("development" !== 'production') {
  51193. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  51194. }
  51195. }
  51196. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  51197. path.attr({
  51198. cursor: getCursor(this._orient),
  51199. draggable: true,
  51200. drift: bind(this._onDragMove, this, handleIndex),
  51201. ondragend: bind(this._onDragEnd, this),
  51202. onmouseover: bind(this._showDataInfo, this, true),
  51203. onmouseout: bind(this._showDataInfo, this, false),
  51204. z2: 5
  51205. });
  51206. var bRect = path.getBoundingRect();
  51207. var handleSize = dataZoomModel.get('handleSize');
  51208. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  51209. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  51210. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  51211. path.style.strokeNoScale = true;
  51212. path.rectHover = true;
  51213. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  51214. enableHoverEmphasis(path);
  51215. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  51216. // Compatitable with previous version
  51217. if (handleColor != null) {
  51218. path.style.fill = handleColor;
  51219. }
  51220. sliderGroup.add(handles[handleIndex] = path);
  51221. var textStyleModel = dataZoomModel.getModel('textStyle');
  51222. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  51223. silent: true,
  51224. invisible: true,
  51225. style: {
  51226. x: 0,
  51227. y: 0,
  51228. text: '',
  51229. verticalAlign: 'middle',
  51230. align: 'center',
  51231. fill: textStyleModel.getTextColor(),
  51232. font: textStyleModel.getFont()
  51233. },
  51234. z2: 10
  51235. }));
  51236. }, this); // Handle to move. Only visible when brushSelect is set true.
  51237. var actualMoveZone = filler;
  51238. if (brushSelect) {
  51239. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  51240. var moveHandle_1 = displayables.moveHandle = new Rect({
  51241. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  51242. silent: true,
  51243. shape: {
  51244. r: [0, 0, 2, 2],
  51245. y: size[1] - 0.5,
  51246. height: moveHandleHeight
  51247. }
  51248. });
  51249. var iconSize = moveHandleHeight * 0.8;
  51250. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  51251. moveHandleIcon.silent = true;
  51252. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  51253. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  51254. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  51255. actualMoveZone = displayables.moveZone = new Rect({
  51256. invisible: true,
  51257. shape: {
  51258. y: size[1] - moveZoneExpandSize,
  51259. height: moveHandleHeight + moveZoneExpandSize
  51260. }
  51261. });
  51262. actualMoveZone.on('mouseover', function () {
  51263. api.enterEmphasis(moveHandle_1);
  51264. }).on('mouseout', function () {
  51265. api.leaveEmphasis(moveHandle_1);
  51266. });
  51267. sliderGroup.add(moveHandle_1);
  51268. sliderGroup.add(moveHandleIcon);
  51269. sliderGroup.add(actualMoveZone);
  51270. }
  51271. actualMoveZone.attr({
  51272. draggable: true,
  51273. cursor: getCursor(this._orient),
  51274. drift: bind(this._onDragMove, this, 'all'),
  51275. ondragstart: bind(this._showDataInfo, this, true),
  51276. ondragend: bind(this._onDragEnd, this),
  51277. onmouseover: bind(this._showDataInfo, this, true),
  51278. onmouseout: bind(this._showDataInfo, this, false)
  51279. });
  51280. };
  51281. SliderZoomView.prototype._resetInterval = function () {
  51282. var range = this._range = this.dataZoomModel.getPercentRange();
  51283. var viewExtent = this._getViewExtent();
  51284. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  51285. };
  51286. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  51287. var dataZoomModel = this.dataZoomModel;
  51288. var handleEnds = this._handleEnds;
  51289. var viewExtend = this._getViewExtent();
  51290. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  51291. var percentExtent = [0, 100];
  51292. 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);
  51293. var lastRange = this._range;
  51294. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  51295. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  51296. };
  51297. SliderZoomView.prototype._updateView = function (nonRealtime) {
  51298. var displaybles = this._displayables;
  51299. var handleEnds = this._handleEnds;
  51300. var handleInterval = asc(handleEnds.slice());
  51301. var size = this._size;
  51302. each([0, 1], function (handleIndex) {
  51303. // Handles
  51304. var handle = displaybles.handles[handleIndex];
  51305. var handleHeight = this._handleHeight;
  51306. handle.attr({
  51307. scaleX: handleHeight / 2,
  51308. scaleY: handleHeight / 2,
  51309. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  51310. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  51311. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  51312. y: size[1] / 2 - handleHeight / 2
  51313. });
  51314. }, this); // Filler
  51315. displaybles.filler.setShape({
  51316. x: handleInterval[0],
  51317. y: 0,
  51318. width: handleInterval[1] - handleInterval[0],
  51319. height: size[1]
  51320. });
  51321. var viewExtent = {
  51322. x: handleInterval[0],
  51323. width: handleInterval[1] - handleInterval[0]
  51324. }; // Move handle
  51325. if (displaybles.moveHandle) {
  51326. displaybles.moveHandle.setShape(viewExtent);
  51327. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  51328. displaybles.moveZone.getBoundingRect();
  51329. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  51330. } // update clip path of shadow.
  51331. var dataShadowSegs = displaybles.dataShadowSegs;
  51332. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  51333. for (var i = 0; i < dataShadowSegs.length; i++) {
  51334. var segGroup = dataShadowSegs[i];
  51335. var clipPath = segGroup.getClipPath();
  51336. if (!clipPath) {
  51337. clipPath = new Rect();
  51338. segGroup.setClipPath(clipPath);
  51339. }
  51340. clipPath.setShape({
  51341. x: segIntervals[i],
  51342. y: 0,
  51343. width: segIntervals[i + 1] - segIntervals[i],
  51344. height: size[1]
  51345. });
  51346. }
  51347. this._updateDataInfo(nonRealtime);
  51348. };
  51349. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  51350. var dataZoomModel = this.dataZoomModel;
  51351. var displaybles = this._displayables;
  51352. var handleLabels = displaybles.handleLabels;
  51353. var orient = this._orient;
  51354. var labelTexts = ['', '']; // FIXME
  51355. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  51356. if (dataZoomModel.get('showDetail')) {
  51357. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  51358. if (axisProxy) {
  51359. var axis = axisProxy.getAxisModel().axis;
  51360. var range = this._range;
  51361. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  51362. ? axisProxy.calculateDataWindow({
  51363. start: range[0],
  51364. end: range[1]
  51365. }).valueWindow : axisProxy.getDataValueWindow();
  51366. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  51367. }
  51368. }
  51369. var orderedHandleEnds = asc(this._handleEnds.slice());
  51370. setLabel.call(this, 0);
  51371. setLabel.call(this, 1);
  51372. function setLabel(handleIndex) {
  51373. // Label
  51374. // Text should not transform by barGroup.
  51375. // Ignore handlers transform
  51376. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  51377. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  51378. var offset = this._handleWidth / 2 + LABEL_GAP;
  51379. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  51380. handleLabels[handleIndex].setStyle({
  51381. x: textPoint[0],
  51382. y: textPoint[1],
  51383. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  51384. align: orient === HORIZONTAL ? direction : 'center',
  51385. text: labelTexts[handleIndex]
  51386. });
  51387. }
  51388. };
  51389. SliderZoomView.prototype._formatLabel = function (value, axis) {
  51390. var dataZoomModel = this.dataZoomModel;
  51391. var labelFormatter = dataZoomModel.get('labelFormatter');
  51392. var labelPrecision = dataZoomModel.get('labelPrecision');
  51393. if (labelPrecision == null || labelPrecision === 'auto') {
  51394. labelPrecision = axis.getPixelPrecision();
  51395. }
  51396. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  51397. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  51398. value: Math.round(value)
  51399. }) // param of toFixed should less then 20.
  51400. : value.toFixed(Math.min(labelPrecision, 20));
  51401. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  51402. };
  51403. /**
  51404. * @param showOrHide true: show, false: hide
  51405. */
  51406. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  51407. // Always show when drgging.
  51408. showOrHide = this._dragging || showOrHide;
  51409. var displayables = this._displayables;
  51410. var handleLabels = displayables.handleLabels;
  51411. handleLabels[0].attr('invisible', !showOrHide);
  51412. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  51413. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  51414. };
  51415. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  51416. this._dragging = true; // For mobile device, prevent screen slider on the button.
  51417. stop(event.event); // Transform dx, dy to bar coordination.
  51418. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  51419. var vertex = applyTransform$1([dx, dy], barTransform, true);
  51420. var changed = this._updateInterval(handleIndex, vertex[0]);
  51421. var realtime = this.dataZoomModel.get('realtime');
  51422. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  51423. // which cause bad visual effect when progressive enabled.
  51424. changed && realtime && this._dispatchZoomAction(true);
  51425. };
  51426. SliderZoomView.prototype._onDragEnd = function () {
  51427. this._dragging = false;
  51428. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  51429. // drag end will cause the whole view rerender, which is unnecessary.
  51430. var realtime = this.dataZoomModel.get('realtime');
  51431. !realtime && this._dispatchZoomAction(false);
  51432. };
  51433. SliderZoomView.prototype._onClickPanel = function (e) {
  51434. var size = this._size;
  51435. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  51436. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  51437. return;
  51438. }
  51439. var handleEnds = this._handleEnds;
  51440. var center = (handleEnds[0] + handleEnds[1]) / 2;
  51441. var changed = this._updateInterval('all', localPoint[0] - center);
  51442. this._updateView();
  51443. changed && this._dispatchZoomAction(false);
  51444. };
  51445. SliderZoomView.prototype._onBrushStart = function (e) {
  51446. var x = e.offsetX;
  51447. var y = e.offsetY;
  51448. this._brushStart = new Point(x, y);
  51449. this._brushing = true;
  51450. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  51451. };
  51452. SliderZoomView.prototype._onBrushEnd = function (e) {
  51453. if (!this._brushing) {
  51454. return;
  51455. }
  51456. var brushRect = this._displayables.brushRect;
  51457. this._brushing = false;
  51458. if (!brushRect) {
  51459. return;
  51460. }
  51461. brushRect.attr('ignore', true);
  51462. var brushShape = brushRect.shape;
  51463. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  51464. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  51465. // Will treat it as a click
  51466. return;
  51467. }
  51468. var viewExtend = this._getViewExtent();
  51469. var percentExtent = [0, 100];
  51470. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  51471. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  51472. this._updateView();
  51473. this._dispatchZoomAction(false);
  51474. };
  51475. SliderZoomView.prototype._onBrush = function (e) {
  51476. if (this._brushing) {
  51477. // For mobile device, prevent screen slider on the button.
  51478. stop(e.event);
  51479. this._updateBrushRect(e.offsetX, e.offsetY);
  51480. }
  51481. };
  51482. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  51483. var displayables = this._displayables;
  51484. var dataZoomModel = this.dataZoomModel;
  51485. var brushRect = displayables.brushRect;
  51486. if (!brushRect) {
  51487. brushRect = displayables.brushRect = new Rect$1({
  51488. silent: true,
  51489. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  51490. });
  51491. displayables.sliderGroup.add(brushRect);
  51492. }
  51493. brushRect.attr('ignore', false);
  51494. var brushStart = this._brushStart;
  51495. var sliderGroup = this._displayables.sliderGroup;
  51496. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  51497. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  51498. var size = this._size;
  51499. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  51500. brushRect.setShape({
  51501. x: startPoint[0],
  51502. y: 0,
  51503. width: endPoint[0] - startPoint[0],
  51504. height: size[1]
  51505. });
  51506. };
  51507. /**
  51508. * This action will be throttled.
  51509. */
  51510. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  51511. var range = this._range;
  51512. this.api.dispatchAction({
  51513. type: 'dataZoom',
  51514. from: this.uid,
  51515. dataZoomId: this.dataZoomModel.id,
  51516. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  51517. start: range[0],
  51518. end: range[1]
  51519. });
  51520. };
  51521. SliderZoomView.prototype._findCoordRect = function () {
  51522. // Find the grid coresponding to the first axis referred by dataZoom.
  51523. var rect;
  51524. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  51525. if (!rect && coordSysInfoList.length) {
  51526. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  51527. rect = coordSys.getRect && coordSys.getRect();
  51528. }
  51529. if (!rect) {
  51530. var width = this.api.getWidth();
  51531. var height = this.api.getHeight();
  51532. rect = {
  51533. x: width * 0.2,
  51534. y: height * 0.2,
  51535. width: width * 0.6,
  51536. height: height * 0.6
  51537. };
  51538. }
  51539. return rect;
  51540. };
  51541. SliderZoomView.type = 'dataZoom.slider';
  51542. return SliderZoomView;
  51543. }(DataZoomView);
  51544. function getOtherDim(thisDim) {
  51545. // FIXME
  51546. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  51547. var map = {
  51548. x: 'y',
  51549. y: 'x',
  51550. radius: 'angle',
  51551. angle: 'radius'
  51552. };
  51553. return map[thisDim];
  51554. }
  51555. function getCursor(orient) {
  51556. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  51557. }
  51558. function install$l(registers) {
  51559. registers.registerComponentModel(SliderZoomModel);
  51560. registers.registerComponentView(SliderZoomView);
  51561. installCommon(registers);
  51562. }
  51563. function install$m(registers) {
  51564. use(install$k);
  51565. use(install$l); // Do not install './dataZoomSelect',
  51566. // since it only work for toolbox dataZoom.
  51567. }
  51568. var DEFAULT_OPTION = {
  51569. label: {
  51570. enabled: true
  51571. },
  51572. decal: {
  51573. show: false
  51574. }
  51575. };
  51576. var inner$g = makeInner();
  51577. var decalPaletteScope = {};
  51578. function ariaVisual(ecModel, api) {
  51579. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  51580. if (!ariaModel.get('enabled')) {
  51581. return;
  51582. }
  51583. var defaultOption = clone(DEFAULT_OPTION);
  51584. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  51585. merge(ariaModel.option, defaultOption, false);
  51586. setDecal();
  51587. setLabel();
  51588. function setDecal() {
  51589. var decalModel = ariaModel.getModel('decal');
  51590. var useDecal = decalModel.get('show');
  51591. if (useDecal) {
  51592. // Each type of series use one scope.
  51593. // Pie and funnel are using diferrent scopes
  51594. var paletteScopeGroupByType_1 = createHashMap();
  51595. ecModel.eachSeries(function (seriesModel) {
  51596. if (!seriesModel.useColorPaletteOnData) {
  51597. return;
  51598. }
  51599. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  51600. if (!decalScope) {
  51601. decalScope = {};
  51602. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  51603. }
  51604. inner$g(seriesModel).scope = decalScope;
  51605. });
  51606. ecModel.eachRawSeries(function (seriesModel) {
  51607. if (ecModel.isSeriesFiltered(seriesModel)) {
  51608. return;
  51609. }
  51610. if (typeof seriesModel.enableAriaDecal === 'function') {
  51611. // Let series define how to use decal palette on data
  51612. seriesModel.enableAriaDecal();
  51613. return;
  51614. }
  51615. var data = seriesModel.getData();
  51616. if (seriesModel.useColorPaletteOnData) {
  51617. var dataAll_1 = seriesModel.getRawData();
  51618. var idxMap_1 = {};
  51619. var decalScope_1 = inner$g(seriesModel).scope;
  51620. data.each(function (idx) {
  51621. var rawIdx = data.getRawIndex(idx);
  51622. idxMap_1[rawIdx] = idx;
  51623. });
  51624. var dataCount_1 = dataAll_1.count();
  51625. dataAll_1.each(function (rawIdx) {
  51626. var idx = idxMap_1[rawIdx];
  51627. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  51628. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  51629. var specifiedDecal = data.getItemVisual(idx, 'decal');
  51630. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  51631. });
  51632. } else {
  51633. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  51634. var specifiedDecal = data.getVisual('decal');
  51635. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  51636. }
  51637. function mergeDecal(specifiedDecal, paletteDecal) {
  51638. // Merge decal from palette to decal from itemStyle.
  51639. // User do not need to specify all of the decal props.
  51640. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  51641. resultDecal.dirty = true;
  51642. return resultDecal;
  51643. }
  51644. });
  51645. }
  51646. }
  51647. function setLabel() {
  51648. var labelLocale = ecModel.getLocaleModel().get('aria');
  51649. var labelModel = ariaModel.getModel('label');
  51650. labelModel.option = defaults(labelModel.option, labelLocale);
  51651. if (!labelModel.get('enabled')) {
  51652. return;
  51653. }
  51654. var dom = api.getZr().dom;
  51655. if (labelModel.get('description')) {
  51656. dom.setAttribute('aria-label', labelModel.get('description'));
  51657. return;
  51658. }
  51659. var seriesCnt = ecModel.getSeriesCount();
  51660. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  51661. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  51662. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  51663. var ariaLabel;
  51664. if (seriesCnt < 1) {
  51665. // No series, no aria label
  51666. return;
  51667. } else {
  51668. var title = getTitle();
  51669. if (title) {
  51670. var withTitle = labelModel.get(['general', 'withTitle']);
  51671. ariaLabel = replace(withTitle, {
  51672. title: title
  51673. });
  51674. } else {
  51675. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  51676. }
  51677. var seriesLabels_1 = [];
  51678. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  51679. ariaLabel += replace(prefix, {
  51680. seriesCount: seriesCnt
  51681. });
  51682. ecModel.eachSeries(function (seriesModel, idx) {
  51683. if (idx < displaySeriesCnt) {
  51684. var seriesLabel = void 0;
  51685. var seriesName = seriesModel.get('name');
  51686. var withName = seriesName ? 'withName' : 'withoutName';
  51687. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  51688. seriesLabel = replace(seriesLabel, {
  51689. seriesId: seriesModel.seriesIndex,
  51690. seriesName: seriesModel.get('name'),
  51691. seriesType: getSeriesTypeName(seriesModel.subType)
  51692. });
  51693. var data = seriesModel.getData();
  51694. if (data.count() > maxDataCnt) {
  51695. // Show part of data
  51696. var partialLabel = labelModel.get(['data', 'partialData']);
  51697. seriesLabel += replace(partialLabel, {
  51698. displayCnt: maxDataCnt
  51699. });
  51700. } else {
  51701. seriesLabel += labelModel.get(['data', 'allData']);
  51702. }
  51703. var dataLabels = [];
  51704. for (var i = 0; i < data.count(); i++) {
  51705. if (i < maxDataCnt) {
  51706. var name_1 = data.getName(i);
  51707. var value = retrieveRawValue(data, i);
  51708. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  51709. dataLabels.push(replace(dataLabel, {
  51710. name: name_1,
  51711. value: value
  51712. }));
  51713. }
  51714. }
  51715. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  51716. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  51717. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  51718. seriesLabels_1.push(seriesLabel);
  51719. }
  51720. });
  51721. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  51722. var middleSeparator = separatorModel.get('middle');
  51723. var endSeparator = separatorModel.get('end');
  51724. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  51725. dom.setAttribute('aria-label', ariaLabel);
  51726. }
  51727. }
  51728. function replace(str, keyValues) {
  51729. if (typeof str !== 'string') {
  51730. return str;
  51731. }
  51732. var result = str;
  51733. each(keyValues, function (value, key) {
  51734. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  51735. });
  51736. return result;
  51737. }
  51738. function getTitle() {
  51739. var title = ecModel.get('title');
  51740. if (title && title.length) {
  51741. title = title[0];
  51742. }
  51743. return title && title.text;
  51744. }
  51745. function getSeriesTypeName(type) {
  51746. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  51747. }
  51748. }
  51749. function ariaPreprocessor(option) {
  51750. if (!option || !option.aria) {
  51751. return;
  51752. }
  51753. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  51754. if (aria.show != null) {
  51755. aria.enabled = aria.show;
  51756. }
  51757. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  51758. each(['description', 'general', 'series', 'data'], function (name) {
  51759. if (aria[name] != null) {
  51760. aria.label[name] = aria[name];
  51761. }
  51762. });
  51763. }
  51764. function install$n(registers) {
  51765. registers.registerPreprocessor(ariaPreprocessor);
  51766. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  51767. }
  51768. var DatasetModel =
  51769. /** @class */
  51770. function (_super) {
  51771. __extends(DatasetModel, _super);
  51772. function DatasetModel() {
  51773. var _this = _super !== null && _super.apply(this, arguments) || this;
  51774. _this.type = 'dataset';
  51775. return _this;
  51776. }
  51777. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  51778. _super.prototype.init.call(this, option, parentModel, ecModel);
  51779. this._sourceManager = new SourceManager(this);
  51780. disableTransformOptionMerge(this);
  51781. };
  51782. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  51783. _super.prototype.mergeOption.call(this, newOption, ecModel);
  51784. disableTransformOptionMerge(this);
  51785. };
  51786. DatasetModel.prototype.optionUpdated = function () {
  51787. this._sourceManager.dirty();
  51788. };
  51789. DatasetModel.prototype.getSourceManager = function () {
  51790. return this._sourceManager;
  51791. };
  51792. DatasetModel.type = 'dataset';
  51793. DatasetModel.defaultOption = {
  51794. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  51795. };
  51796. return DatasetModel;
  51797. }(ComponentModel);
  51798. var DatasetView =
  51799. /** @class */
  51800. function (_super) {
  51801. __extends(DatasetView, _super);
  51802. function DatasetView() {
  51803. var _this = _super !== null && _super.apply(this, arguments) || this;
  51804. _this.type = 'dataset';
  51805. return _this;
  51806. }
  51807. DatasetView.type = 'dataset';
  51808. return DatasetView;
  51809. }(ComponentView);
  51810. function install$o(registers) {
  51811. registers.registerComponentModel(DatasetModel);
  51812. registers.registerComponentView(DatasetView);
  51813. }
  51814. use([install$1]);
  51815. use([install]);
  51816. use([install$2, install$3, install$4, install$6]);
  51817. use([install$9, install$c, install$7, install$j, install$8, install$d, install$e, install$f, install$g, install$m, install$b, install$n, install$o]);
  51818. exports.Axis = Axis;
  51819. exports.ChartView = ChartView;
  51820. exports.ComponentModel = ComponentModel;
  51821. exports.ComponentView = ComponentView;
  51822. exports.List = List;
  51823. exports.Model = Model;
  51824. exports.PRIORITY = PRIORITY;
  51825. exports.SeriesModel = SeriesModel;
  51826. exports.color = color;
  51827. exports.connect = connect;
  51828. exports.dataTool = dataTool;
  51829. exports.dependencies = dependencies;
  51830. exports.disConnect = disConnect;
  51831. exports.disconnect = disconnect;
  51832. exports.dispose = dispose$1;
  51833. exports.env = env;
  51834. exports.extendChartView = extendChartView;
  51835. exports.extendComponentModel = extendComponentModel;
  51836. exports.extendComponentView = extendComponentView;
  51837. exports.extendSeriesModel = extendSeriesModel;
  51838. exports.format = format$1;
  51839. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  51840. exports.getInstanceByDom = getInstanceByDom;
  51841. exports.getInstanceById = getInstanceById;
  51842. exports.getMap = getMap;
  51843. exports.graphic = graphic$1;
  51844. exports.helper = helper;
  51845. exports.init = init$1;
  51846. exports.innerDrawElementOnCanvas = brushSingle;
  51847. exports.matrix = matrix;
  51848. exports.number = number;
  51849. exports.parseGeoJSON = parseGeoJSON;
  51850. exports.parseGeoJson = parseGeoJSON;
  51851. exports.registerAction = registerAction;
  51852. exports.registerCoordinateSystem = registerCoordinateSystem;
  51853. exports.registerLayout = registerLayout;
  51854. exports.registerLoading = registerLoading;
  51855. exports.registerLocale = registerLocale;
  51856. exports.registerMap = registerMap;
  51857. exports.registerPostInit = registerPostInit;
  51858. exports.registerPostUpdate = registerPostUpdate;
  51859. exports.registerPreprocessor = registerPreprocessor;
  51860. exports.registerProcessor = registerProcessor;
  51861. exports.registerTheme = registerTheme;
  51862. exports.registerTransform = registerTransform;
  51863. exports.registerVisual = registerVisual;
  51864. exports.setCanvasCreator = setCanvasCreator;
  51865. exports.throttle = throttle;
  51866. exports.time = time;
  51867. exports.use = use;
  51868. exports.util = util$1;
  51869. exports.vector = vector;
  51870. exports.version = version$1;
  51871. exports.zrUtil = util;
  51872. exports.zrender = zrender;
  51873. Object.defineProperty(exports, '__esModule', { value: true });
  51874. })));
  51875. //# sourceMappingURL=echarts.common.js.map