echarts.simple.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. (function (global, factory) {
  20. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  21. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  22. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  23. }(this, (function (exports) { 'use strict';
  24. /*! *****************************************************************************
  25. Copyright (c) Microsoft Corporation.
  26. Permission to use, copy, modify, and/or distribute this software for any
  27. purpose with or without fee is hereby granted.
  28. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  30. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  31. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  33. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34. PERFORMANCE OF THIS SOFTWARE.
  35. ***************************************************************************** */
  36. /* global Reflect, Promise */
  37. var extendStatics = function(d, b) {
  38. extendStatics = Object.setPrototypeOf ||
  39. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  40. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  41. return extendStatics(d, b);
  42. };
  43. function __extends(d, b) {
  44. if (typeof b !== "function" && b !== null)
  45. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  46. extendStatics(d, b);
  47. function __() { this.constructor = d; }
  48. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  49. }
  50. var Browser = (function () {
  51. function Browser() {
  52. this.firefox = false;
  53. this.ie = false;
  54. this.edge = false;
  55. this.newEdge = false;
  56. this.weChat = false;
  57. }
  58. return Browser;
  59. }());
  60. var Env = (function () {
  61. function Env() {
  62. this.browser = new Browser();
  63. this.node = false;
  64. this.wxa = false;
  65. this.worker = false;
  66. this.svgSupported = false;
  67. this.touchEventsSupported = false;
  68. this.pointerEventsSupported = false;
  69. this.domSupported = false;
  70. this.transformSupported = false;
  71. this.transform3dSupported = false;
  72. this.hasGlobalWindow = typeof window !== 'undefined';
  73. }
  74. return Env;
  75. }());
  76. var env = new Env();
  77. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  78. env.wxa = true;
  79. env.touchEventsSupported = true;
  80. }
  81. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  82. env.worker = true;
  83. }
  84. else if (typeof navigator === 'undefined'
  85. || navigator.userAgent.indexOf('Node.js') === 0) {
  86. env.node = true;
  87. env.svgSupported = true;
  88. }
  89. else {
  90. detect(navigator.userAgent, env);
  91. }
  92. function detect(ua, env) {
  93. var browser = env.browser;
  94. var firefox = ua.match(/Firefox\/([\d.]+)/);
  95. var ie = ua.match(/MSIE\s([\d.]+)/)
  96. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  97. var edge = ua.match(/Edge?\/([\d.]+)/);
  98. var weChat = (/micromessenger/i).test(ua);
  99. if (firefox) {
  100. browser.firefox = true;
  101. browser.version = firefox[1];
  102. }
  103. if (ie) {
  104. browser.ie = true;
  105. browser.version = ie[1];
  106. }
  107. if (edge) {
  108. browser.edge = true;
  109. browser.version = edge[1];
  110. browser.newEdge = +edge[1].split('.')[0] > 18;
  111. }
  112. if (weChat) {
  113. browser.weChat = true;
  114. }
  115. env.svgSupported = typeof SVGRect !== 'undefined';
  116. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  117. env.pointerEventsSupported = 'onpointerdown' in window
  118. && (browser.edge || (browser.ie && +browser.version >= 11));
  119. env.domSupported = typeof document !== 'undefined';
  120. var style = document.documentElement.style;
  121. env.transform3dSupported = ((browser.ie && 'transition' in style)
  122. || browser.edge
  123. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  124. || 'MozPerspective' in style)
  125. && !('OTransition' in style);
  126. env.transformSupported = env.transform3dSupported
  127. || (browser.ie && +browser.version >= 9);
  128. }
  129. var DEFAULT_FONT_SIZE = 12;
  130. var DEFAULT_FONT_FAMILY = 'sans-serif';
  131. var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  132. var OFFSET = 20;
  133. var SCALE = 100;
  134. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  135. function getTextWidthMap(mapStr) {
  136. var map = {};
  137. if (typeof JSON === 'undefined') {
  138. return map;
  139. }
  140. for (var i = 0; i < mapStr.length; i++) {
  141. var char = String.fromCharCode(i + 32);
  142. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  143. map[char] = size;
  144. }
  145. return map;
  146. }
  147. var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  148. var platformApi = {
  149. createCanvas: function () {
  150. return typeof document !== 'undefined'
  151. && document.createElement('canvas');
  152. },
  153. measureText: (function () {
  154. var _ctx;
  155. var _cachedFont;
  156. return function (text, font) {
  157. if (!_ctx) {
  158. var canvas = platformApi.createCanvas();
  159. _ctx = canvas && canvas.getContext('2d');
  160. }
  161. if (_ctx) {
  162. if (_cachedFont !== font) {
  163. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  164. }
  165. return _ctx.measureText(text);
  166. }
  167. else {
  168. text = text || '';
  169. font = font || DEFAULT_FONT;
  170. var res = /((?:\d+)?\.?\d*)px/.exec(font);
  171. var fontSize = res && +res[1] || DEFAULT_FONT_SIZE;
  172. var width = 0;
  173. if (font.indexOf('mono') >= 0) {
  174. width = fontSize * text.length;
  175. }
  176. else {
  177. for (var i = 0; i < text.length; i++) {
  178. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  179. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  180. }
  181. }
  182. return { width: width };
  183. }
  184. };
  185. })(),
  186. loadImage: function (src, onload, onerror) {
  187. var image = new Image();
  188. image.onload = onload;
  189. image.onerror = onerror;
  190. image.src = src;
  191. return image;
  192. }
  193. };
  194. function setPlatformAPI(newPlatformApis) {
  195. for (var key in platformApi) {
  196. if (newPlatformApis[key]) {
  197. platformApi[key] = newPlatformApis[key];
  198. }
  199. }
  200. }
  201. var BUILTIN_OBJECT = reduce([
  202. 'Function',
  203. 'RegExp',
  204. 'Date',
  205. 'Error',
  206. 'CanvasGradient',
  207. 'CanvasPattern',
  208. 'Image',
  209. 'Canvas'
  210. ], function (obj, val) {
  211. obj['[object ' + val + ']'] = true;
  212. return obj;
  213. }, {});
  214. var TYPED_ARRAY = reduce([
  215. 'Int8',
  216. 'Uint8',
  217. 'Uint8Clamped',
  218. 'Int16',
  219. 'Uint16',
  220. 'Int32',
  221. 'Uint32',
  222. 'Float32',
  223. 'Float64'
  224. ], function (obj, val) {
  225. obj['[object ' + val + 'Array]'] = true;
  226. return obj;
  227. }, {});
  228. var objToString = Object.prototype.toString;
  229. var arrayProto = Array.prototype;
  230. var nativeForEach = arrayProto.forEach;
  231. var nativeFilter = arrayProto.filter;
  232. var nativeSlice = arrayProto.slice;
  233. var nativeMap = arrayProto.map;
  234. var ctorFunction = function () { }.constructor;
  235. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  236. var protoKey = '__proto__';
  237. var idStart = 0x0907;
  238. function guid() {
  239. return idStart++;
  240. }
  241. function logError() {
  242. var args = [];
  243. for (var _i = 0; _i < arguments.length; _i++) {
  244. args[_i] = arguments[_i];
  245. }
  246. if (typeof console !== 'undefined') {
  247. console.error.apply(console, args);
  248. }
  249. }
  250. function clone(source) {
  251. if (source == null || typeof source !== 'object') {
  252. return source;
  253. }
  254. var result = source;
  255. var typeStr = objToString.call(source);
  256. if (typeStr === '[object Array]') {
  257. if (!isPrimitive(source)) {
  258. result = [];
  259. for (var i = 0, len = source.length; i < len; i++) {
  260. result[i] = clone(source[i]);
  261. }
  262. }
  263. }
  264. else if (TYPED_ARRAY[typeStr]) {
  265. if (!isPrimitive(source)) {
  266. var Ctor = source.constructor;
  267. if (Ctor.from) {
  268. result = Ctor.from(source);
  269. }
  270. else {
  271. result = new Ctor(source.length);
  272. for (var i = 0, len = source.length; i < len; i++) {
  273. result[i] = source[i];
  274. }
  275. }
  276. }
  277. }
  278. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  279. result = {};
  280. for (var key in source) {
  281. if (source.hasOwnProperty(key) && key !== protoKey) {
  282. result[key] = clone(source[key]);
  283. }
  284. }
  285. }
  286. return result;
  287. }
  288. function merge(target, source, overwrite) {
  289. if (!isObject(source) || !isObject(target)) {
  290. return overwrite ? clone(source) : target;
  291. }
  292. for (var key in source) {
  293. if (source.hasOwnProperty(key) && key !== protoKey) {
  294. var targetProp = target[key];
  295. var sourceProp = source[key];
  296. if (isObject(sourceProp)
  297. && isObject(targetProp)
  298. && !isArray(sourceProp)
  299. && !isArray(targetProp)
  300. && !isDom(sourceProp)
  301. && !isDom(targetProp)
  302. && !isBuiltInObject(sourceProp)
  303. && !isBuiltInObject(targetProp)
  304. && !isPrimitive(sourceProp)
  305. && !isPrimitive(targetProp)) {
  306. merge(targetProp, sourceProp, overwrite);
  307. }
  308. else if (overwrite || !(key in target)) {
  309. target[key] = clone(source[key]);
  310. }
  311. }
  312. }
  313. return target;
  314. }
  315. function mergeAll(targetAndSources, overwrite) {
  316. var result = targetAndSources[0];
  317. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  318. result = merge(result, targetAndSources[i], overwrite);
  319. }
  320. return result;
  321. }
  322. function extend(target, source) {
  323. if (Object.assign) {
  324. Object.assign(target, source);
  325. }
  326. else {
  327. for (var key in source) {
  328. if (source.hasOwnProperty(key) && key !== protoKey) {
  329. target[key] = source[key];
  330. }
  331. }
  332. }
  333. return target;
  334. }
  335. function defaults(target, source, overlay) {
  336. var keysArr = keys(source);
  337. for (var i = 0; i < keysArr.length; i++) {
  338. var key = keysArr[i];
  339. if ((overlay ? source[key] != null : target[key] == null)) {
  340. target[key] = source[key];
  341. }
  342. }
  343. return target;
  344. }
  345. var createCanvas = platformApi.createCanvas;
  346. function indexOf(array, value) {
  347. if (array) {
  348. if (array.indexOf) {
  349. return array.indexOf(value);
  350. }
  351. for (var i = 0, len = array.length; i < len; i++) {
  352. if (array[i] === value) {
  353. return i;
  354. }
  355. }
  356. }
  357. return -1;
  358. }
  359. function inherits(clazz, baseClazz) {
  360. var clazzPrototype = clazz.prototype;
  361. function F() { }
  362. F.prototype = baseClazz.prototype;
  363. clazz.prototype = new F();
  364. for (var prop in clazzPrototype) {
  365. if (clazzPrototype.hasOwnProperty(prop)) {
  366. clazz.prototype[prop] = clazzPrototype[prop];
  367. }
  368. }
  369. clazz.prototype.constructor = clazz;
  370. clazz.superClass = baseClazz;
  371. }
  372. function mixin(target, source, override) {
  373. target = 'prototype' in target ? target.prototype : target;
  374. source = 'prototype' in source ? source.prototype : source;
  375. if (Object.getOwnPropertyNames) {
  376. var keyList = Object.getOwnPropertyNames(source);
  377. for (var i = 0; i < keyList.length; i++) {
  378. var key = keyList[i];
  379. if (key !== 'constructor') {
  380. if ((override ? source[key] != null : target[key] == null)) {
  381. target[key] = source[key];
  382. }
  383. }
  384. }
  385. }
  386. else {
  387. defaults(target, source, override);
  388. }
  389. }
  390. function isArrayLike(data) {
  391. if (!data) {
  392. return false;
  393. }
  394. if (typeof data === 'string') {
  395. return false;
  396. }
  397. return typeof data.length === 'number';
  398. }
  399. function each(arr, cb, context) {
  400. if (!(arr && cb)) {
  401. return;
  402. }
  403. if (arr.forEach && arr.forEach === nativeForEach) {
  404. arr.forEach(cb, context);
  405. }
  406. else if (arr.length === +arr.length) {
  407. for (var i = 0, len = arr.length; i < len; i++) {
  408. cb.call(context, arr[i], i, arr);
  409. }
  410. }
  411. else {
  412. for (var key in arr) {
  413. if (arr.hasOwnProperty(key)) {
  414. cb.call(context, arr[key], key, arr);
  415. }
  416. }
  417. }
  418. }
  419. function map(arr, cb, context) {
  420. if (!arr) {
  421. return [];
  422. }
  423. if (!cb) {
  424. return slice(arr);
  425. }
  426. if (arr.map && arr.map === nativeMap) {
  427. return arr.map(cb, context);
  428. }
  429. else {
  430. var result = [];
  431. for (var i = 0, len = arr.length; i < len; i++) {
  432. result.push(cb.call(context, arr[i], i, arr));
  433. }
  434. return result;
  435. }
  436. }
  437. function reduce(arr, cb, memo, context) {
  438. if (!(arr && cb)) {
  439. return;
  440. }
  441. for (var i = 0, len = arr.length; i < len; i++) {
  442. memo = cb.call(context, memo, arr[i], i, arr);
  443. }
  444. return memo;
  445. }
  446. function filter(arr, cb, context) {
  447. if (!arr) {
  448. return [];
  449. }
  450. if (!cb) {
  451. return slice(arr);
  452. }
  453. if (arr.filter && arr.filter === nativeFilter) {
  454. return arr.filter(cb, context);
  455. }
  456. else {
  457. var result = [];
  458. for (var i = 0, len = arr.length; i < len; i++) {
  459. if (cb.call(context, arr[i], i, arr)) {
  460. result.push(arr[i]);
  461. }
  462. }
  463. return result;
  464. }
  465. }
  466. function find(arr, cb, context) {
  467. if (!(arr && cb)) {
  468. return;
  469. }
  470. for (var i = 0, len = arr.length; i < len; i++) {
  471. if (cb.call(context, arr[i], i, arr)) {
  472. return arr[i];
  473. }
  474. }
  475. }
  476. function keys(obj) {
  477. if (!obj) {
  478. return [];
  479. }
  480. if (Object.keys) {
  481. return Object.keys(obj);
  482. }
  483. var keyList = [];
  484. for (var key in obj) {
  485. if (obj.hasOwnProperty(key)) {
  486. keyList.push(key);
  487. }
  488. }
  489. return keyList;
  490. }
  491. function bindPolyfill(func, context) {
  492. var args = [];
  493. for (var _i = 2; _i < arguments.length; _i++) {
  494. args[_i - 2] = arguments[_i];
  495. }
  496. return function () {
  497. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  498. };
  499. }
  500. var bind = (protoFunction && isFunction(protoFunction.bind))
  501. ? protoFunction.call.bind(protoFunction.bind)
  502. : bindPolyfill;
  503. function curry(func) {
  504. var args = [];
  505. for (var _i = 1; _i < arguments.length; _i++) {
  506. args[_i - 1] = arguments[_i];
  507. }
  508. return function () {
  509. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  510. };
  511. }
  512. function isArray(value) {
  513. if (Array.isArray) {
  514. return Array.isArray(value);
  515. }
  516. return objToString.call(value) === '[object Array]';
  517. }
  518. function isFunction(value) {
  519. return typeof value === 'function';
  520. }
  521. function isString(value) {
  522. return typeof value === 'string';
  523. }
  524. function isStringSafe(value) {
  525. return objToString.call(value) === '[object String]';
  526. }
  527. function isNumber(value) {
  528. return typeof value === 'number';
  529. }
  530. function isObject(value) {
  531. var type = typeof value;
  532. return type === 'function' || (!!value && type === 'object');
  533. }
  534. function isBuiltInObject(value) {
  535. return !!BUILTIN_OBJECT[objToString.call(value)];
  536. }
  537. function isTypedArray(value) {
  538. return !!TYPED_ARRAY[objToString.call(value)];
  539. }
  540. function isDom(value) {
  541. return typeof value === 'object'
  542. && typeof value.nodeType === 'number'
  543. && typeof value.ownerDocument === 'object';
  544. }
  545. function isGradientObject(value) {
  546. return value.colorStops != null;
  547. }
  548. function isImagePatternObject(value) {
  549. return value.image != null;
  550. }
  551. function isRegExp(value) {
  552. return objToString.call(value) === '[object RegExp]';
  553. }
  554. function eqNaN(value) {
  555. return value !== value;
  556. }
  557. function retrieve() {
  558. var args = [];
  559. for (var _i = 0; _i < arguments.length; _i++) {
  560. args[_i] = arguments[_i];
  561. }
  562. for (var i = 0, len = args.length; i < len; i++) {
  563. if (args[i] != null) {
  564. return args[i];
  565. }
  566. }
  567. }
  568. function retrieve2(value0, value1) {
  569. return value0 != null
  570. ? value0
  571. : value1;
  572. }
  573. function retrieve3(value0, value1, value2) {
  574. return value0 != null
  575. ? value0
  576. : value1 != null
  577. ? value1
  578. : value2;
  579. }
  580. function slice(arr) {
  581. var args = [];
  582. for (var _i = 1; _i < arguments.length; _i++) {
  583. args[_i - 1] = arguments[_i];
  584. }
  585. return nativeSlice.apply(arr, args);
  586. }
  587. function normalizeCssArray(val) {
  588. if (typeof (val) === 'number') {
  589. return [val, val, val, val];
  590. }
  591. var len = val.length;
  592. if (len === 2) {
  593. return [val[0], val[1], val[0], val[1]];
  594. }
  595. else if (len === 3) {
  596. return [val[0], val[1], val[2], val[1]];
  597. }
  598. return val;
  599. }
  600. function assert(condition, message) {
  601. if (!condition) {
  602. throw new Error(message);
  603. }
  604. }
  605. function trim(str) {
  606. if (str == null) {
  607. return null;
  608. }
  609. else if (typeof str.trim === 'function') {
  610. return str.trim();
  611. }
  612. else {
  613. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  614. }
  615. }
  616. var primitiveKey = '__ec_primitive__';
  617. function setAsPrimitive(obj) {
  618. obj[primitiveKey] = true;
  619. }
  620. function isPrimitive(obj) {
  621. return obj[primitiveKey];
  622. }
  623. var MapPolyfill = (function () {
  624. function MapPolyfill() {
  625. this.data = {};
  626. }
  627. MapPolyfill.prototype["delete"] = function (key) {
  628. var existed = this.has(key);
  629. if (existed) {
  630. delete this.data[key];
  631. }
  632. return existed;
  633. };
  634. MapPolyfill.prototype.has = function (key) {
  635. return this.data.hasOwnProperty(key);
  636. };
  637. MapPolyfill.prototype.get = function (key) {
  638. return this.data[key];
  639. };
  640. MapPolyfill.prototype.set = function (key, value) {
  641. this.data[key] = value;
  642. return this;
  643. };
  644. MapPolyfill.prototype.keys = function () {
  645. return keys(this.data);
  646. };
  647. MapPolyfill.prototype.forEach = function (callback) {
  648. var data = this.data;
  649. for (var key in data) {
  650. if (data.hasOwnProperty(key)) {
  651. callback(data[key], key);
  652. }
  653. }
  654. };
  655. return MapPolyfill;
  656. }());
  657. var isNativeMapSupported = typeof Map === 'function';
  658. function maybeNativeMap() {
  659. return (isNativeMapSupported ? new Map() : new MapPolyfill());
  660. }
  661. var HashMap = (function () {
  662. function HashMap(obj) {
  663. var isArr = isArray(obj);
  664. this.data = maybeNativeMap();
  665. var thisMap = this;
  666. (obj instanceof HashMap)
  667. ? obj.each(visit)
  668. : (obj && each(obj, visit));
  669. function visit(value, key) {
  670. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  671. }
  672. }
  673. HashMap.prototype.hasKey = function (key) {
  674. return this.data.has(key);
  675. };
  676. HashMap.prototype.get = function (key) {
  677. return this.data.get(key);
  678. };
  679. HashMap.prototype.set = function (key, value) {
  680. this.data.set(key, value);
  681. return value;
  682. };
  683. HashMap.prototype.each = function (cb, context) {
  684. this.data.forEach(function (value, key) {
  685. cb.call(context, value, key);
  686. });
  687. };
  688. HashMap.prototype.keys = function () {
  689. var keys = this.data.keys();
  690. return isNativeMapSupported
  691. ? Array.from(keys)
  692. : keys;
  693. };
  694. HashMap.prototype.removeKey = function (key) {
  695. this.data["delete"](key);
  696. };
  697. return HashMap;
  698. }());
  699. function createHashMap(obj) {
  700. return new HashMap(obj);
  701. }
  702. function concatArray(a, b) {
  703. var newArray = new a.constructor(a.length + b.length);
  704. for (var i = 0; i < a.length; i++) {
  705. newArray[i] = a[i];
  706. }
  707. var offset = a.length;
  708. for (var i = 0; i < b.length; i++) {
  709. newArray[i + offset] = b[i];
  710. }
  711. return newArray;
  712. }
  713. function createObject(proto, properties) {
  714. var obj;
  715. if (Object.create) {
  716. obj = Object.create(proto);
  717. }
  718. else {
  719. var StyleCtor = function () { };
  720. StyleCtor.prototype = proto;
  721. obj = new StyleCtor();
  722. }
  723. if (properties) {
  724. extend(obj, properties);
  725. }
  726. return obj;
  727. }
  728. function disableUserSelect(dom) {
  729. var domStyle = dom.style;
  730. domStyle.webkitUserSelect = 'none';
  731. domStyle.userSelect = 'none';
  732. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  733. domStyle['-webkit-touch-callout'] = 'none';
  734. }
  735. function hasOwn(own, prop) {
  736. return own.hasOwnProperty(prop);
  737. }
  738. function noop() { }
  739. var RADIAN_TO_DEGREE = 180 / Math.PI;
  740. var util = /*#__PURE__*/Object.freeze({
  741. __proto__: null,
  742. guid: guid,
  743. logError: logError,
  744. clone: clone,
  745. merge: merge,
  746. mergeAll: mergeAll,
  747. extend: extend,
  748. defaults: defaults,
  749. createCanvas: createCanvas,
  750. indexOf: indexOf,
  751. inherits: inherits,
  752. mixin: mixin,
  753. isArrayLike: isArrayLike,
  754. each: each,
  755. map: map,
  756. reduce: reduce,
  757. filter: filter,
  758. find: find,
  759. keys: keys,
  760. bind: bind,
  761. curry: curry,
  762. isArray: isArray,
  763. isFunction: isFunction,
  764. isString: isString,
  765. isStringSafe: isStringSafe,
  766. isNumber: isNumber,
  767. isObject: isObject,
  768. isBuiltInObject: isBuiltInObject,
  769. isTypedArray: isTypedArray,
  770. isDom: isDom,
  771. isGradientObject: isGradientObject,
  772. isImagePatternObject: isImagePatternObject,
  773. isRegExp: isRegExp,
  774. eqNaN: eqNaN,
  775. retrieve: retrieve,
  776. retrieve2: retrieve2,
  777. retrieve3: retrieve3,
  778. slice: slice,
  779. normalizeCssArray: normalizeCssArray,
  780. assert: assert,
  781. trim: trim,
  782. setAsPrimitive: setAsPrimitive,
  783. isPrimitive: isPrimitive,
  784. HashMap: HashMap,
  785. createHashMap: createHashMap,
  786. concatArray: concatArray,
  787. createObject: createObject,
  788. disableUserSelect: disableUserSelect,
  789. hasOwn: hasOwn,
  790. noop: noop,
  791. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE
  792. });
  793. function create(x, y) {
  794. if (x == null) {
  795. x = 0;
  796. }
  797. if (y == null) {
  798. y = 0;
  799. }
  800. return [x, y];
  801. }
  802. function copy(out, v) {
  803. out[0] = v[0];
  804. out[1] = v[1];
  805. return out;
  806. }
  807. function clone$1(v) {
  808. return [v[0], v[1]];
  809. }
  810. function set(out, a, b) {
  811. out[0] = a;
  812. out[1] = b;
  813. return out;
  814. }
  815. function add(out, v1, v2) {
  816. out[0] = v1[0] + v2[0];
  817. out[1] = v1[1] + v2[1];
  818. return out;
  819. }
  820. function scaleAndAdd(out, v1, v2, a) {
  821. out[0] = v1[0] + v2[0] * a;
  822. out[1] = v1[1] + v2[1] * a;
  823. return out;
  824. }
  825. function sub(out, v1, v2) {
  826. out[0] = v1[0] - v2[0];
  827. out[1] = v1[1] - v2[1];
  828. return out;
  829. }
  830. function len(v) {
  831. return Math.sqrt(lenSquare(v));
  832. }
  833. var length = len;
  834. function lenSquare(v) {
  835. return v[0] * v[0] + v[1] * v[1];
  836. }
  837. var lengthSquare = lenSquare;
  838. function mul(out, v1, v2) {
  839. out[0] = v1[0] * v2[0];
  840. out[1] = v1[1] * v2[1];
  841. return out;
  842. }
  843. function div(out, v1, v2) {
  844. out[0] = v1[0] / v2[0];
  845. out[1] = v1[1] / v2[1];
  846. return out;
  847. }
  848. function dot(v1, v2) {
  849. return v1[0] * v2[0] + v1[1] * v2[1];
  850. }
  851. function scale(out, v, s) {
  852. out[0] = v[0] * s;
  853. out[1] = v[1] * s;
  854. return out;
  855. }
  856. function normalize(out, v) {
  857. var d = len(v);
  858. if (d === 0) {
  859. out[0] = 0;
  860. out[1] = 0;
  861. }
  862. else {
  863. out[0] = v[0] / d;
  864. out[1] = v[1] / d;
  865. }
  866. return out;
  867. }
  868. function distance(v1, v2) {
  869. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  870. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  871. }
  872. var dist = distance;
  873. function distanceSquare(v1, v2) {
  874. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  875. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  876. }
  877. var distSquare = distanceSquare;
  878. function negate(out, v) {
  879. out[0] = -v[0];
  880. out[1] = -v[1];
  881. return out;
  882. }
  883. function lerp(out, v1, v2, t) {
  884. out[0] = v1[0] + t * (v2[0] - v1[0]);
  885. out[1] = v1[1] + t * (v2[1] - v1[1]);
  886. return out;
  887. }
  888. function applyTransform(out, v, m) {
  889. var x = v[0];
  890. var y = v[1];
  891. out[0] = m[0] * x + m[2] * y + m[4];
  892. out[1] = m[1] * x + m[3] * y + m[5];
  893. return out;
  894. }
  895. function min(out, v1, v2) {
  896. out[0] = Math.min(v1[0], v2[0]);
  897. out[1] = Math.min(v1[1], v2[1]);
  898. return out;
  899. }
  900. function max(out, v1, v2) {
  901. out[0] = Math.max(v1[0], v2[0]);
  902. out[1] = Math.max(v1[1], v2[1]);
  903. return out;
  904. }
  905. var vector = /*#__PURE__*/Object.freeze({
  906. __proto__: null,
  907. create: create,
  908. copy: copy,
  909. clone: clone$1,
  910. set: set,
  911. add: add,
  912. scaleAndAdd: scaleAndAdd,
  913. sub: sub,
  914. len: len,
  915. length: length,
  916. lenSquare: lenSquare,
  917. lengthSquare: lengthSquare,
  918. mul: mul,
  919. div: div,
  920. dot: dot,
  921. scale: scale,
  922. normalize: normalize,
  923. distance: distance,
  924. dist: dist,
  925. distanceSquare: distanceSquare,
  926. distSquare: distSquare,
  927. negate: negate,
  928. lerp: lerp,
  929. applyTransform: applyTransform,
  930. min: min,
  931. max: max
  932. });
  933. var Param = (function () {
  934. function Param(target, e) {
  935. this.target = target;
  936. this.topTarget = e && e.topTarget;
  937. }
  938. return Param;
  939. }());
  940. var Draggable = (function () {
  941. function Draggable(handler) {
  942. this.handler = handler;
  943. handler.on('mousedown', this._dragStart, this);
  944. handler.on('mousemove', this._drag, this);
  945. handler.on('mouseup', this._dragEnd, this);
  946. }
  947. Draggable.prototype._dragStart = function (e) {
  948. var draggingTarget = e.target;
  949. while (draggingTarget && !draggingTarget.draggable) {
  950. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  951. }
  952. if (draggingTarget) {
  953. this._draggingTarget = draggingTarget;
  954. draggingTarget.dragging = true;
  955. this._x = e.offsetX;
  956. this._y = e.offsetY;
  957. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  958. }
  959. };
  960. Draggable.prototype._drag = function (e) {
  961. var draggingTarget = this._draggingTarget;
  962. if (draggingTarget) {
  963. var x = e.offsetX;
  964. var y = e.offsetY;
  965. var dx = x - this._x;
  966. var dy = y - this._y;
  967. this._x = x;
  968. this._y = y;
  969. draggingTarget.drift(dx, dy, e);
  970. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  971. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  972. var lastDropTarget = this._dropTarget;
  973. this._dropTarget = dropTarget;
  974. if (draggingTarget !== dropTarget) {
  975. if (lastDropTarget && dropTarget !== lastDropTarget) {
  976. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  977. }
  978. if (dropTarget && dropTarget !== lastDropTarget) {
  979. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  980. }
  981. }
  982. }
  983. };
  984. Draggable.prototype._dragEnd = function (e) {
  985. var draggingTarget = this._draggingTarget;
  986. if (draggingTarget) {
  987. draggingTarget.dragging = false;
  988. }
  989. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  990. if (this._dropTarget) {
  991. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  992. }
  993. this._draggingTarget = null;
  994. this._dropTarget = null;
  995. };
  996. return Draggable;
  997. }());
  998. var Eventful = (function () {
  999. function Eventful(eventProcessors) {
  1000. if (eventProcessors) {
  1001. this._$eventProcessor = eventProcessors;
  1002. }
  1003. }
  1004. Eventful.prototype.on = function (event, query, handler, context) {
  1005. if (!this._$handlers) {
  1006. this._$handlers = {};
  1007. }
  1008. var _h = this._$handlers;
  1009. if (typeof query === 'function') {
  1010. context = handler;
  1011. handler = query;
  1012. query = null;
  1013. }
  1014. if (!handler || !event) {
  1015. return this;
  1016. }
  1017. var eventProcessor = this._$eventProcessor;
  1018. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1019. query = eventProcessor.normalizeQuery(query);
  1020. }
  1021. if (!_h[event]) {
  1022. _h[event] = [];
  1023. }
  1024. for (var i = 0; i < _h[event].length; i++) {
  1025. if (_h[event][i].h === handler) {
  1026. return this;
  1027. }
  1028. }
  1029. var wrap = {
  1030. h: handler,
  1031. query: query,
  1032. ctx: (context || this),
  1033. callAtLast: handler.zrEventfulCallAtLast
  1034. };
  1035. var lastIndex = _h[event].length - 1;
  1036. var lastWrap = _h[event][lastIndex];
  1037. (lastWrap && lastWrap.callAtLast)
  1038. ? _h[event].splice(lastIndex, 0, wrap)
  1039. : _h[event].push(wrap);
  1040. return this;
  1041. };
  1042. Eventful.prototype.isSilent = function (eventName) {
  1043. var _h = this._$handlers;
  1044. return !_h || !_h[eventName] || !_h[eventName].length;
  1045. };
  1046. Eventful.prototype.off = function (eventType, handler) {
  1047. var _h = this._$handlers;
  1048. if (!_h) {
  1049. return this;
  1050. }
  1051. if (!eventType) {
  1052. this._$handlers = {};
  1053. return this;
  1054. }
  1055. if (handler) {
  1056. if (_h[eventType]) {
  1057. var newList = [];
  1058. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1059. if (_h[eventType][i].h !== handler) {
  1060. newList.push(_h[eventType][i]);
  1061. }
  1062. }
  1063. _h[eventType] = newList;
  1064. }
  1065. if (_h[eventType] && _h[eventType].length === 0) {
  1066. delete _h[eventType];
  1067. }
  1068. }
  1069. else {
  1070. delete _h[eventType];
  1071. }
  1072. return this;
  1073. };
  1074. Eventful.prototype.trigger = function (eventType) {
  1075. var args = [];
  1076. for (var _i = 1; _i < arguments.length; _i++) {
  1077. args[_i - 1] = arguments[_i];
  1078. }
  1079. if (!this._$handlers) {
  1080. return this;
  1081. }
  1082. var _h = this._$handlers[eventType];
  1083. var eventProcessor = this._$eventProcessor;
  1084. if (_h) {
  1085. var argLen = args.length;
  1086. var len = _h.length;
  1087. for (var i = 0; i < len; i++) {
  1088. var hItem = _h[i];
  1089. if (eventProcessor
  1090. && eventProcessor.filter
  1091. && hItem.query != null
  1092. && !eventProcessor.filter(eventType, hItem.query)) {
  1093. continue;
  1094. }
  1095. switch (argLen) {
  1096. case 0:
  1097. hItem.h.call(hItem.ctx);
  1098. break;
  1099. case 1:
  1100. hItem.h.call(hItem.ctx, args[0]);
  1101. break;
  1102. case 2:
  1103. hItem.h.call(hItem.ctx, args[0], args[1]);
  1104. break;
  1105. default:
  1106. hItem.h.apply(hItem.ctx, args);
  1107. break;
  1108. }
  1109. }
  1110. }
  1111. eventProcessor && eventProcessor.afterTrigger
  1112. && eventProcessor.afterTrigger(eventType);
  1113. return this;
  1114. };
  1115. Eventful.prototype.triggerWithContext = function (type) {
  1116. var args = [];
  1117. for (var _i = 1; _i < arguments.length; _i++) {
  1118. args[_i - 1] = arguments[_i];
  1119. }
  1120. if (!this._$handlers) {
  1121. return this;
  1122. }
  1123. var _h = this._$handlers[type];
  1124. var eventProcessor = this._$eventProcessor;
  1125. if (_h) {
  1126. var argLen = args.length;
  1127. var ctx = args[argLen - 1];
  1128. var len = _h.length;
  1129. for (var i = 0; i < len; i++) {
  1130. var hItem = _h[i];
  1131. if (eventProcessor
  1132. && eventProcessor.filter
  1133. && hItem.query != null
  1134. && !eventProcessor.filter(type, hItem.query)) {
  1135. continue;
  1136. }
  1137. switch (argLen) {
  1138. case 0:
  1139. hItem.h.call(ctx);
  1140. break;
  1141. case 1:
  1142. hItem.h.call(ctx, args[0]);
  1143. break;
  1144. case 2:
  1145. hItem.h.call(ctx, args[0], args[1]);
  1146. break;
  1147. default:
  1148. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1149. break;
  1150. }
  1151. }
  1152. }
  1153. eventProcessor && eventProcessor.afterTrigger
  1154. && eventProcessor.afterTrigger(type);
  1155. return this;
  1156. };
  1157. return Eventful;
  1158. }());
  1159. var LN2 = Math.log(2);
  1160. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1161. var cacheKey = rowMask + '-' + colMask;
  1162. var fullRank = rows.length;
  1163. if (detCache.hasOwnProperty(cacheKey)) {
  1164. return detCache[cacheKey];
  1165. }
  1166. if (rank === 1) {
  1167. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1168. return rows[rowStart][colStart];
  1169. }
  1170. var subRowMask = rowMask | (1 << rowStart);
  1171. var subRowStart = rowStart + 1;
  1172. while (rowMask & (1 << subRowStart)) {
  1173. subRowStart++;
  1174. }
  1175. var sum = 0;
  1176. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1177. var colTag = 1 << j;
  1178. if (!(colTag & colMask)) {
  1179. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1180. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1181. colLocalIdx++;
  1182. }
  1183. }
  1184. detCache[cacheKey] = sum;
  1185. return sum;
  1186. }
  1187. function buildTransformer(src, dest) {
  1188. var mA = [
  1189. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1190. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1191. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1192. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1193. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1194. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1195. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1196. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1197. ];
  1198. var detCache = {};
  1199. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1200. if (det === 0) {
  1201. return;
  1202. }
  1203. var vh = [];
  1204. for (var i = 0; i < 8; i++) {
  1205. for (var j = 0; j < 8; j++) {
  1206. vh[j] == null && (vh[j] = 0);
  1207. vh[j] += ((i + j) % 2 ? -1 : 1)
  1208. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1209. / det * dest[i];
  1210. }
  1211. }
  1212. return function (out, srcPointX, srcPointY) {
  1213. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1214. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1215. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1216. };
  1217. }
  1218. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1219. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1220. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1221. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1222. var markers = prepareCoordMarkers(el, saved);
  1223. var transformer = preparePointerTransformer(markers, saved, inverse);
  1224. if (transformer) {
  1225. transformer(out, inX, inY);
  1226. return true;
  1227. }
  1228. }
  1229. return false;
  1230. }
  1231. function prepareCoordMarkers(el, saved) {
  1232. var markers = saved.markers;
  1233. if (markers) {
  1234. return markers;
  1235. }
  1236. markers = saved.markers = [];
  1237. var propLR = ['left', 'right'];
  1238. var propTB = ['top', 'bottom'];
  1239. for (var i = 0; i < 4; i++) {
  1240. var marker = document.createElement('div');
  1241. var stl = marker.style;
  1242. var idxLR = i % 2;
  1243. var idxTB = (i >> 1) % 2;
  1244. stl.cssText = [
  1245. 'position: absolute',
  1246. 'visibility: hidden',
  1247. 'padding: 0',
  1248. 'margin: 0',
  1249. 'border-width: 0',
  1250. 'user-select: none',
  1251. 'width:0',
  1252. 'height:0',
  1253. propLR[idxLR] + ':0',
  1254. propTB[idxTB] + ':0',
  1255. propLR[1 - idxLR] + ':auto',
  1256. propTB[1 - idxTB] + ':auto',
  1257. ''
  1258. ].join('!important;');
  1259. el.appendChild(marker);
  1260. markers.push(marker);
  1261. }
  1262. return markers;
  1263. }
  1264. function preparePointerTransformer(markers, saved, inverse) {
  1265. var transformerName = inverse ? 'invTrans' : 'trans';
  1266. var transformer = saved[transformerName];
  1267. var oldSrcCoords = saved.srcCoords;
  1268. var srcCoords = [];
  1269. var destCoords = [];
  1270. var oldCoordTheSame = true;
  1271. for (var i = 0; i < 4; i++) {
  1272. var rect = markers[i].getBoundingClientRect();
  1273. var ii = 2 * i;
  1274. var x = rect.left;
  1275. var y = rect.top;
  1276. srcCoords.push(x, y);
  1277. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1278. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1279. }
  1280. return (oldCoordTheSame && transformer)
  1281. ? transformer
  1282. : (saved.srcCoords = srcCoords,
  1283. saved[transformerName] = inverse
  1284. ? buildTransformer(destCoords, srcCoords)
  1285. : buildTransformer(srcCoords, destCoords));
  1286. }
  1287. function isCanvasEl(el) {
  1288. return el.nodeName.toUpperCase() === 'CANVAS';
  1289. }
  1290. var replaceReg = /([&<>"'])/g;
  1291. var replaceMap = {
  1292. '&': '&amp;',
  1293. '<': '&lt;',
  1294. '>': '&gt;',
  1295. '"': '&quot;',
  1296. '\'': '&#39;'
  1297. };
  1298. function encodeHTML(source) {
  1299. return source == null
  1300. ? ''
  1301. : (source + '').replace(replaceReg, function (str, c) {
  1302. return replaceMap[c];
  1303. });
  1304. }
  1305. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1306. var _calcOut = [];
  1307. var firefoxNotSupportOffsetXY = env.browser.firefox
  1308. && +env.browser.version.split('.')[0] < 39;
  1309. function clientToLocal(el, e, out, calculate) {
  1310. out = out || {};
  1311. if (calculate) {
  1312. calculateZrXY(el, e, out);
  1313. }
  1314. else if (firefoxNotSupportOffsetXY
  1315. && e.layerX != null
  1316. && e.layerX !== e.offsetX) {
  1317. out.zrX = e.layerX;
  1318. out.zrY = e.layerY;
  1319. }
  1320. else if (e.offsetX != null) {
  1321. out.zrX = e.offsetX;
  1322. out.zrY = e.offsetY;
  1323. }
  1324. else {
  1325. calculateZrXY(el, e, out);
  1326. }
  1327. return out;
  1328. }
  1329. function calculateZrXY(el, e, out) {
  1330. if (env.domSupported && el.getBoundingClientRect) {
  1331. var ex = e.clientX;
  1332. var ey = e.clientY;
  1333. if (isCanvasEl(el)) {
  1334. var box = el.getBoundingClientRect();
  1335. out.zrX = ex - box.left;
  1336. out.zrY = ey - box.top;
  1337. return;
  1338. }
  1339. else {
  1340. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1341. out.zrX = _calcOut[0];
  1342. out.zrY = _calcOut[1];
  1343. return;
  1344. }
  1345. }
  1346. }
  1347. out.zrX = out.zrY = 0;
  1348. }
  1349. function getNativeEvent(e) {
  1350. return e
  1351. || window.event;
  1352. }
  1353. function normalizeEvent(el, e, calculate) {
  1354. e = getNativeEvent(e);
  1355. if (e.zrX != null) {
  1356. return e;
  1357. }
  1358. var eventType = e.type;
  1359. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1360. if (!isTouch) {
  1361. clientToLocal(el, e, e, calculate);
  1362. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1363. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1364. }
  1365. else {
  1366. var touch = eventType !== 'touchend'
  1367. ? e.targetTouches[0]
  1368. : e.changedTouches[0];
  1369. touch && clientToLocal(el, touch, e, calculate);
  1370. }
  1371. var button = e.button;
  1372. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1373. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1374. }
  1375. return e;
  1376. }
  1377. function getWheelDeltaMayPolyfill(e) {
  1378. var rawWheelDelta = e.wheelDelta;
  1379. if (rawWheelDelta) {
  1380. return rawWheelDelta;
  1381. }
  1382. var deltaX = e.deltaX;
  1383. var deltaY = e.deltaY;
  1384. if (deltaX == null || deltaY == null) {
  1385. return rawWheelDelta;
  1386. }
  1387. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1388. var sign = deltaY > 0 ? -1
  1389. : deltaY < 0 ? 1
  1390. : deltaX > 0 ? -1
  1391. : 1;
  1392. return 3 * delta * sign;
  1393. }
  1394. function addEventListener(el, name, handler, opt) {
  1395. el.addEventListener(name, handler, opt);
  1396. }
  1397. function removeEventListener(el, name, handler, opt) {
  1398. el.removeEventListener(name, handler, opt);
  1399. }
  1400. var stop = function (e) {
  1401. e.preventDefault();
  1402. e.stopPropagation();
  1403. e.cancelBubble = true;
  1404. };
  1405. var GestureMgr = (function () {
  1406. function GestureMgr() {
  1407. this._track = [];
  1408. }
  1409. GestureMgr.prototype.recognize = function (event, target, root) {
  1410. this._doTrack(event, target, root);
  1411. return this._recognize(event);
  1412. };
  1413. GestureMgr.prototype.clear = function () {
  1414. this._track.length = 0;
  1415. return this;
  1416. };
  1417. GestureMgr.prototype._doTrack = function (event, target, root) {
  1418. var touches = event.touches;
  1419. if (!touches) {
  1420. return;
  1421. }
  1422. var trackItem = {
  1423. points: [],
  1424. touches: [],
  1425. target: target,
  1426. event: event
  1427. };
  1428. for (var i = 0, len = touches.length; i < len; i++) {
  1429. var touch = touches[i];
  1430. var pos = clientToLocal(root, touch, {});
  1431. trackItem.points.push([pos.zrX, pos.zrY]);
  1432. trackItem.touches.push(touch);
  1433. }
  1434. this._track.push(trackItem);
  1435. };
  1436. GestureMgr.prototype._recognize = function (event) {
  1437. for (var eventName in recognizers) {
  1438. if (recognizers.hasOwnProperty(eventName)) {
  1439. var gestureInfo = recognizers[eventName](this._track, event);
  1440. if (gestureInfo) {
  1441. return gestureInfo;
  1442. }
  1443. }
  1444. }
  1445. };
  1446. return GestureMgr;
  1447. }());
  1448. function dist$1(pointPair) {
  1449. var dx = pointPair[1][0] - pointPair[0][0];
  1450. var dy = pointPair[1][1] - pointPair[0][1];
  1451. return Math.sqrt(dx * dx + dy * dy);
  1452. }
  1453. function center(pointPair) {
  1454. return [
  1455. (pointPair[0][0] + pointPair[1][0]) / 2,
  1456. (pointPair[0][1] + pointPair[1][1]) / 2
  1457. ];
  1458. }
  1459. var recognizers = {
  1460. pinch: function (tracks, event) {
  1461. var trackLen = tracks.length;
  1462. if (!trackLen) {
  1463. return;
  1464. }
  1465. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1466. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1467. if (pinchPre
  1468. && pinchPre.length > 1
  1469. && pinchEnd
  1470. && pinchEnd.length > 1) {
  1471. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1472. !isFinite(pinchScale) && (pinchScale = 1);
  1473. event.pinchScale = pinchScale;
  1474. var pinchCenter = center(pinchEnd);
  1475. event.pinchX = pinchCenter[0];
  1476. event.pinchY = pinchCenter[1];
  1477. return {
  1478. type: 'pinch',
  1479. target: tracks[0].target,
  1480. event: event
  1481. };
  1482. }
  1483. }
  1484. };
  1485. function create$1() {
  1486. return [1, 0, 0, 1, 0, 0];
  1487. }
  1488. function identity(out) {
  1489. out[0] = 1;
  1490. out[1] = 0;
  1491. out[2] = 0;
  1492. out[3] = 1;
  1493. out[4] = 0;
  1494. out[5] = 0;
  1495. return out;
  1496. }
  1497. function copy$1(out, m) {
  1498. out[0] = m[0];
  1499. out[1] = m[1];
  1500. out[2] = m[2];
  1501. out[3] = m[3];
  1502. out[4] = m[4];
  1503. out[5] = m[5];
  1504. return out;
  1505. }
  1506. function mul$1(out, m1, m2) {
  1507. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1508. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1509. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1510. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1511. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1512. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1513. out[0] = out0;
  1514. out[1] = out1;
  1515. out[2] = out2;
  1516. out[3] = out3;
  1517. out[4] = out4;
  1518. out[5] = out5;
  1519. return out;
  1520. }
  1521. function translate(out, a, v) {
  1522. out[0] = a[0];
  1523. out[1] = a[1];
  1524. out[2] = a[2];
  1525. out[3] = a[3];
  1526. out[4] = a[4] + v[0];
  1527. out[5] = a[5] + v[1];
  1528. return out;
  1529. }
  1530. function rotate(out, a, rad, pivot) {
  1531. if (pivot === void 0) { pivot = [0, 0]; }
  1532. var aa = a[0];
  1533. var ac = a[2];
  1534. var atx = a[4];
  1535. var ab = a[1];
  1536. var ad = a[3];
  1537. var aty = a[5];
  1538. var st = Math.sin(rad);
  1539. var ct = Math.cos(rad);
  1540. out[0] = aa * ct + ab * st;
  1541. out[1] = -aa * st + ab * ct;
  1542. out[2] = ac * ct + ad * st;
  1543. out[3] = -ac * st + ct * ad;
  1544. out[4] = ct * (atx - pivot[0]) + st * (aty - pivot[1]) + pivot[0];
  1545. out[5] = ct * (aty - pivot[1]) - st * (atx - pivot[0]) + pivot[1];
  1546. return out;
  1547. }
  1548. function scale$1(out, a, v) {
  1549. var vx = v[0];
  1550. var vy = v[1];
  1551. out[0] = a[0] * vx;
  1552. out[1] = a[1] * vy;
  1553. out[2] = a[2] * vx;
  1554. out[3] = a[3] * vy;
  1555. out[4] = a[4] * vx;
  1556. out[5] = a[5] * vy;
  1557. return out;
  1558. }
  1559. function invert(out, a) {
  1560. var aa = a[0];
  1561. var ac = a[2];
  1562. var atx = a[4];
  1563. var ab = a[1];
  1564. var ad = a[3];
  1565. var aty = a[5];
  1566. var det = aa * ad - ab * ac;
  1567. if (!det) {
  1568. return null;
  1569. }
  1570. det = 1.0 / det;
  1571. out[0] = ad * det;
  1572. out[1] = -ab * det;
  1573. out[2] = -ac * det;
  1574. out[3] = aa * det;
  1575. out[4] = (ac * aty - ad * atx) * det;
  1576. out[5] = (ab * atx - aa * aty) * det;
  1577. return out;
  1578. }
  1579. function clone$2(a) {
  1580. var b = create$1();
  1581. copy$1(b, a);
  1582. return b;
  1583. }
  1584. var matrix = /*#__PURE__*/Object.freeze({
  1585. __proto__: null,
  1586. create: create$1,
  1587. identity: identity,
  1588. copy: copy$1,
  1589. mul: mul$1,
  1590. translate: translate,
  1591. rotate: rotate,
  1592. scale: scale$1,
  1593. invert: invert,
  1594. clone: clone$2
  1595. });
  1596. var Point = (function () {
  1597. function Point(x, y) {
  1598. this.x = x || 0;
  1599. this.y = y || 0;
  1600. }
  1601. Point.prototype.copy = function (other) {
  1602. this.x = other.x;
  1603. this.y = other.y;
  1604. return this;
  1605. };
  1606. Point.prototype.clone = function () {
  1607. return new Point(this.x, this.y);
  1608. };
  1609. Point.prototype.set = function (x, y) {
  1610. this.x = x;
  1611. this.y = y;
  1612. return this;
  1613. };
  1614. Point.prototype.equal = function (other) {
  1615. return other.x === this.x && other.y === this.y;
  1616. };
  1617. Point.prototype.add = function (other) {
  1618. this.x += other.x;
  1619. this.y += other.y;
  1620. return this;
  1621. };
  1622. Point.prototype.scale = function (scalar) {
  1623. this.x *= scalar;
  1624. this.y *= scalar;
  1625. };
  1626. Point.prototype.scaleAndAdd = function (other, scalar) {
  1627. this.x += other.x * scalar;
  1628. this.y += other.y * scalar;
  1629. };
  1630. Point.prototype.sub = function (other) {
  1631. this.x -= other.x;
  1632. this.y -= other.y;
  1633. return this;
  1634. };
  1635. Point.prototype.dot = function (other) {
  1636. return this.x * other.x + this.y * other.y;
  1637. };
  1638. Point.prototype.len = function () {
  1639. return Math.sqrt(this.x * this.x + this.y * this.y);
  1640. };
  1641. Point.prototype.lenSquare = function () {
  1642. return this.x * this.x + this.y * this.y;
  1643. };
  1644. Point.prototype.normalize = function () {
  1645. var len = this.len();
  1646. this.x /= len;
  1647. this.y /= len;
  1648. return this;
  1649. };
  1650. Point.prototype.distance = function (other) {
  1651. var dx = this.x - other.x;
  1652. var dy = this.y - other.y;
  1653. return Math.sqrt(dx * dx + dy * dy);
  1654. };
  1655. Point.prototype.distanceSquare = function (other) {
  1656. var dx = this.x - other.x;
  1657. var dy = this.y - other.y;
  1658. return dx * dx + dy * dy;
  1659. };
  1660. Point.prototype.negate = function () {
  1661. this.x = -this.x;
  1662. this.y = -this.y;
  1663. return this;
  1664. };
  1665. Point.prototype.transform = function (m) {
  1666. if (!m) {
  1667. return;
  1668. }
  1669. var x = this.x;
  1670. var y = this.y;
  1671. this.x = m[0] * x + m[2] * y + m[4];
  1672. this.y = m[1] * x + m[3] * y + m[5];
  1673. return this;
  1674. };
  1675. Point.prototype.toArray = function (out) {
  1676. out[0] = this.x;
  1677. out[1] = this.y;
  1678. return out;
  1679. };
  1680. Point.prototype.fromArray = function (input) {
  1681. this.x = input[0];
  1682. this.y = input[1];
  1683. };
  1684. Point.set = function (p, x, y) {
  1685. p.x = x;
  1686. p.y = y;
  1687. };
  1688. Point.copy = function (p, p2) {
  1689. p.x = p2.x;
  1690. p.y = p2.y;
  1691. };
  1692. Point.len = function (p) {
  1693. return Math.sqrt(p.x * p.x + p.y * p.y);
  1694. };
  1695. Point.lenSquare = function (p) {
  1696. return p.x * p.x + p.y * p.y;
  1697. };
  1698. Point.dot = function (p0, p1) {
  1699. return p0.x * p1.x + p0.y * p1.y;
  1700. };
  1701. Point.add = function (out, p0, p1) {
  1702. out.x = p0.x + p1.x;
  1703. out.y = p0.y + p1.y;
  1704. };
  1705. Point.sub = function (out, p0, p1) {
  1706. out.x = p0.x - p1.x;
  1707. out.y = p0.y - p1.y;
  1708. };
  1709. Point.scale = function (out, p0, scalar) {
  1710. out.x = p0.x * scalar;
  1711. out.y = p0.y * scalar;
  1712. };
  1713. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  1714. out.x = p0.x + p1.x * scalar;
  1715. out.y = p0.y + p1.y * scalar;
  1716. };
  1717. Point.lerp = function (out, p0, p1, t) {
  1718. var onet = 1 - t;
  1719. out.x = onet * p0.x + t * p1.x;
  1720. out.y = onet * p0.y + t * p1.y;
  1721. };
  1722. return Point;
  1723. }());
  1724. var mathMin = Math.min;
  1725. var mathMax = Math.max;
  1726. var lt = new Point();
  1727. var rb = new Point();
  1728. var lb = new Point();
  1729. var rt = new Point();
  1730. var minTv = new Point();
  1731. var maxTv = new Point();
  1732. var BoundingRect = (function () {
  1733. function BoundingRect(x, y, width, height) {
  1734. if (width < 0) {
  1735. x = x + width;
  1736. width = -width;
  1737. }
  1738. if (height < 0) {
  1739. y = y + height;
  1740. height = -height;
  1741. }
  1742. this.x = x;
  1743. this.y = y;
  1744. this.width = width;
  1745. this.height = height;
  1746. }
  1747. BoundingRect.prototype.union = function (other) {
  1748. var x = mathMin(other.x, this.x);
  1749. var y = mathMin(other.y, this.y);
  1750. if (isFinite(this.x) && isFinite(this.width)) {
  1751. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  1752. }
  1753. else {
  1754. this.width = other.width;
  1755. }
  1756. if (isFinite(this.y) && isFinite(this.height)) {
  1757. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  1758. }
  1759. else {
  1760. this.height = other.height;
  1761. }
  1762. this.x = x;
  1763. this.y = y;
  1764. };
  1765. BoundingRect.prototype.applyTransform = function (m) {
  1766. BoundingRect.applyTransform(this, this, m);
  1767. };
  1768. BoundingRect.prototype.calculateTransform = function (b) {
  1769. var a = this;
  1770. var sx = b.width / a.width;
  1771. var sy = b.height / a.height;
  1772. var m = create$1();
  1773. translate(m, m, [-a.x, -a.y]);
  1774. scale$1(m, m, [sx, sy]);
  1775. translate(m, m, [b.x, b.y]);
  1776. return m;
  1777. };
  1778. BoundingRect.prototype.intersect = function (b, mtv) {
  1779. if (!b) {
  1780. return false;
  1781. }
  1782. if (!(b instanceof BoundingRect)) {
  1783. b = BoundingRect.create(b);
  1784. }
  1785. var a = this;
  1786. var ax0 = a.x;
  1787. var ax1 = a.x + a.width;
  1788. var ay0 = a.y;
  1789. var ay1 = a.y + a.height;
  1790. var bx0 = b.x;
  1791. var bx1 = b.x + b.width;
  1792. var by0 = b.y;
  1793. var by1 = b.y + b.height;
  1794. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  1795. if (mtv) {
  1796. var dMin = Infinity;
  1797. var dMax = 0;
  1798. var d0 = Math.abs(ax1 - bx0);
  1799. var d1 = Math.abs(bx1 - ax0);
  1800. var d2 = Math.abs(ay1 - by0);
  1801. var d3 = Math.abs(by1 - ay0);
  1802. var dx = Math.min(d0, d1);
  1803. var dy = Math.min(d2, d3);
  1804. if (ax1 < bx0 || bx1 < ax0) {
  1805. if (dx > dMax) {
  1806. dMax = dx;
  1807. if (d0 < d1) {
  1808. Point.set(maxTv, -d0, 0);
  1809. }
  1810. else {
  1811. Point.set(maxTv, d1, 0);
  1812. }
  1813. }
  1814. }
  1815. else {
  1816. if (dx < dMin) {
  1817. dMin = dx;
  1818. if (d0 < d1) {
  1819. Point.set(minTv, d0, 0);
  1820. }
  1821. else {
  1822. Point.set(minTv, -d1, 0);
  1823. }
  1824. }
  1825. }
  1826. if (ay1 < by0 || by1 < ay0) {
  1827. if (dy > dMax) {
  1828. dMax = dy;
  1829. if (d2 < d3) {
  1830. Point.set(maxTv, 0, -d2);
  1831. }
  1832. else {
  1833. Point.set(maxTv, 0, d3);
  1834. }
  1835. }
  1836. }
  1837. else {
  1838. if (dx < dMin) {
  1839. dMin = dx;
  1840. if (d2 < d3) {
  1841. Point.set(minTv, 0, d2);
  1842. }
  1843. else {
  1844. Point.set(minTv, 0, -d3);
  1845. }
  1846. }
  1847. }
  1848. }
  1849. if (mtv) {
  1850. Point.copy(mtv, overlap ? minTv : maxTv);
  1851. }
  1852. return overlap;
  1853. };
  1854. BoundingRect.prototype.contain = function (x, y) {
  1855. var rect = this;
  1856. return x >= rect.x
  1857. && x <= (rect.x + rect.width)
  1858. && y >= rect.y
  1859. && y <= (rect.y + rect.height);
  1860. };
  1861. BoundingRect.prototype.clone = function () {
  1862. return new BoundingRect(this.x, this.y, this.width, this.height);
  1863. };
  1864. BoundingRect.prototype.copy = function (other) {
  1865. BoundingRect.copy(this, other);
  1866. };
  1867. BoundingRect.prototype.plain = function () {
  1868. return {
  1869. x: this.x,
  1870. y: this.y,
  1871. width: this.width,
  1872. height: this.height
  1873. };
  1874. };
  1875. BoundingRect.prototype.isFinite = function () {
  1876. return isFinite(this.x)
  1877. && isFinite(this.y)
  1878. && isFinite(this.width)
  1879. && isFinite(this.height);
  1880. };
  1881. BoundingRect.prototype.isZero = function () {
  1882. return this.width === 0 || this.height === 0;
  1883. };
  1884. BoundingRect.create = function (rect) {
  1885. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  1886. };
  1887. BoundingRect.copy = function (target, source) {
  1888. target.x = source.x;
  1889. target.y = source.y;
  1890. target.width = source.width;
  1891. target.height = source.height;
  1892. };
  1893. BoundingRect.applyTransform = function (target, source, m) {
  1894. if (!m) {
  1895. if (target !== source) {
  1896. BoundingRect.copy(target, source);
  1897. }
  1898. return;
  1899. }
  1900. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  1901. var sx = m[0];
  1902. var sy = m[3];
  1903. var tx = m[4];
  1904. var ty = m[5];
  1905. target.x = source.x * sx + tx;
  1906. target.y = source.y * sy + ty;
  1907. target.width = source.width * sx;
  1908. target.height = source.height * sy;
  1909. if (target.width < 0) {
  1910. target.x += target.width;
  1911. target.width = -target.width;
  1912. }
  1913. if (target.height < 0) {
  1914. target.y += target.height;
  1915. target.height = -target.height;
  1916. }
  1917. return;
  1918. }
  1919. lt.x = lb.x = source.x;
  1920. lt.y = rt.y = source.y;
  1921. rb.x = rt.x = source.x + source.width;
  1922. rb.y = lb.y = source.y + source.height;
  1923. lt.transform(m);
  1924. rt.transform(m);
  1925. rb.transform(m);
  1926. lb.transform(m);
  1927. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  1928. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  1929. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  1930. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  1931. target.width = maxX - target.x;
  1932. target.height = maxY - target.y;
  1933. };
  1934. return BoundingRect;
  1935. }());
  1936. var SILENT = 'silent';
  1937. function makeEventPacket(eveType, targetInfo, event) {
  1938. return {
  1939. type: eveType,
  1940. event: event,
  1941. target: targetInfo.target,
  1942. topTarget: targetInfo.topTarget,
  1943. cancelBubble: false,
  1944. offsetX: event.zrX,
  1945. offsetY: event.zrY,
  1946. gestureEvent: event.gestureEvent,
  1947. pinchX: event.pinchX,
  1948. pinchY: event.pinchY,
  1949. pinchScale: event.pinchScale,
  1950. wheelDelta: event.zrDelta,
  1951. zrByTouch: event.zrByTouch,
  1952. which: event.which,
  1953. stop: stopEvent
  1954. };
  1955. }
  1956. function stopEvent() {
  1957. stop(this.event);
  1958. }
  1959. var EmptyProxy = (function (_super) {
  1960. __extends(EmptyProxy, _super);
  1961. function EmptyProxy() {
  1962. var _this = _super !== null && _super.apply(this, arguments) || this;
  1963. _this.handler = null;
  1964. return _this;
  1965. }
  1966. EmptyProxy.prototype.dispose = function () { };
  1967. EmptyProxy.prototype.setCursor = function () { };
  1968. return EmptyProxy;
  1969. }(Eventful));
  1970. var HoveredResult = (function () {
  1971. function HoveredResult(x, y) {
  1972. this.x = x;
  1973. this.y = y;
  1974. }
  1975. return HoveredResult;
  1976. }());
  1977. var handlerNames = [
  1978. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1979. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1980. ];
  1981. var tmpRect = new BoundingRect(0, 0, 0, 0);
  1982. var Handler = (function (_super) {
  1983. __extends(Handler, _super);
  1984. function Handler(storage, painter, proxy, painterRoot, pointerSize) {
  1985. var _this = _super.call(this) || this;
  1986. _this._hovered = new HoveredResult(0, 0);
  1987. _this.storage = storage;
  1988. _this.painter = painter;
  1989. _this.painterRoot = painterRoot;
  1990. _this._pointerSize = pointerSize;
  1991. proxy = proxy || new EmptyProxy();
  1992. _this.proxy = null;
  1993. _this.setHandlerProxy(proxy);
  1994. _this._draggingMgr = new Draggable(_this);
  1995. return _this;
  1996. }
  1997. Handler.prototype.setHandlerProxy = function (proxy) {
  1998. if (this.proxy) {
  1999. this.proxy.dispose();
  2000. }
  2001. if (proxy) {
  2002. each(handlerNames, function (name) {
  2003. proxy.on && proxy.on(name, this[name], this);
  2004. }, this);
  2005. proxy.handler = this;
  2006. }
  2007. this.proxy = proxy;
  2008. };
  2009. Handler.prototype.mousemove = function (event) {
  2010. var x = event.zrX;
  2011. var y = event.zrY;
  2012. var isOutside = isOutsideBoundary(this, x, y);
  2013. var lastHovered = this._hovered;
  2014. var lastHoveredTarget = lastHovered.target;
  2015. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2016. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2017. lastHoveredTarget = lastHovered.target;
  2018. }
  2019. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  2020. var hoveredTarget = hovered.target;
  2021. var proxy = this.proxy;
  2022. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2023. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2024. this.dispatchToElement(lastHovered, 'mouseout', event);
  2025. }
  2026. this.dispatchToElement(hovered, 'mousemove', event);
  2027. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2028. this.dispatchToElement(hovered, 'mouseover', event);
  2029. }
  2030. };
  2031. Handler.prototype.mouseout = function (event) {
  2032. var eventControl = event.zrEventControl;
  2033. if (eventControl !== 'only_globalout') {
  2034. this.dispatchToElement(this._hovered, 'mouseout', event);
  2035. }
  2036. if (eventControl !== 'no_globalout') {
  2037. this.trigger('globalout', { type: 'globalout', event: event });
  2038. }
  2039. };
  2040. Handler.prototype.resize = function () {
  2041. this._hovered = new HoveredResult(0, 0);
  2042. };
  2043. Handler.prototype.dispatch = function (eventName, eventArgs) {
  2044. var handler = this[eventName];
  2045. handler && handler.call(this, eventArgs);
  2046. };
  2047. Handler.prototype.dispose = function () {
  2048. this.proxy.dispose();
  2049. this.storage = null;
  2050. this.proxy = null;
  2051. this.painter = null;
  2052. };
  2053. Handler.prototype.setCursorStyle = function (cursorStyle) {
  2054. var proxy = this.proxy;
  2055. proxy.setCursor && proxy.setCursor(cursorStyle);
  2056. };
  2057. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  2058. targetInfo = targetInfo || {};
  2059. var el = targetInfo.target;
  2060. if (el && el.silent) {
  2061. return;
  2062. }
  2063. var eventKey = ('on' + eventName);
  2064. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2065. while (el) {
  2066. el[eventKey]
  2067. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  2068. el.trigger(eventName, eventPacket);
  2069. el = el.__hostTarget ? el.__hostTarget : el.parent;
  2070. if (eventPacket.cancelBubble) {
  2071. break;
  2072. }
  2073. }
  2074. if (!eventPacket.cancelBubble) {
  2075. this.trigger(eventName, eventPacket);
  2076. if (this.painter && this.painter.eachOtherLayer) {
  2077. this.painter.eachOtherLayer(function (layer) {
  2078. if (typeof (layer[eventKey]) === 'function') {
  2079. layer[eventKey].call(layer, eventPacket);
  2080. }
  2081. if (layer.trigger) {
  2082. layer.trigger(eventName, eventPacket);
  2083. }
  2084. });
  2085. }
  2086. }
  2087. };
  2088. Handler.prototype.findHover = function (x, y, exclude) {
  2089. var list = this.storage.getDisplayList();
  2090. var out = new HoveredResult(x, y);
  2091. setHoverTarget(list, out, x, y, exclude);
  2092. if (this._pointerSize && !out.target) {
  2093. var candidates = [];
  2094. var pointerSize = this._pointerSize;
  2095. var targetSizeHalf = pointerSize / 2;
  2096. var pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  2097. for (var i = list.length - 1; i >= 0; i--) {
  2098. var el = list[i];
  2099. if (el !== exclude
  2100. && !el.ignore
  2101. && !el.ignoreCoarsePointer
  2102. && (!el.parent || !el.parent.ignoreCoarsePointer)) {
  2103. tmpRect.copy(el.getBoundingRect());
  2104. if (el.transform) {
  2105. tmpRect.applyTransform(el.transform);
  2106. }
  2107. if (tmpRect.intersect(pointerRect)) {
  2108. candidates.push(el);
  2109. }
  2110. }
  2111. }
  2112. if (candidates.length) {
  2113. var rStep = 4;
  2114. var thetaStep = Math.PI / 12;
  2115. var PI2 = Math.PI * 2;
  2116. for (var r = 0; r < targetSizeHalf; r += rStep) {
  2117. for (var theta = 0; theta < PI2; theta += thetaStep) {
  2118. var x1 = x + r * Math.cos(theta);
  2119. var y1 = y + r * Math.sin(theta);
  2120. setHoverTarget(candidates, out, x1, y1, exclude);
  2121. if (out.target) {
  2122. return out;
  2123. }
  2124. }
  2125. }
  2126. }
  2127. }
  2128. return out;
  2129. };
  2130. Handler.prototype.processGesture = function (event, stage) {
  2131. if (!this._gestureMgr) {
  2132. this._gestureMgr = new GestureMgr();
  2133. }
  2134. var gestureMgr = this._gestureMgr;
  2135. stage === 'start' && gestureMgr.clear();
  2136. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2137. stage === 'end' && gestureMgr.clear();
  2138. if (gestureInfo) {
  2139. var type = gestureInfo.type;
  2140. event.gestureEvent = type;
  2141. var res = new HoveredResult();
  2142. res.target = gestureInfo.target;
  2143. this.dispatchToElement(res, type, gestureInfo.event);
  2144. }
  2145. };
  2146. return Handler;
  2147. }(Eventful));
  2148. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2149. Handler.prototype[name] = function (event) {
  2150. var x = event.zrX;
  2151. var y = event.zrY;
  2152. var isOutside = isOutsideBoundary(this, x, y);
  2153. var hovered;
  2154. var hoveredTarget;
  2155. if (name !== 'mouseup' || !isOutside) {
  2156. hovered = this.findHover(x, y);
  2157. hoveredTarget = hovered.target;
  2158. }
  2159. if (name === 'mousedown') {
  2160. this._downEl = hoveredTarget;
  2161. this._downPoint = [event.zrX, event.zrY];
  2162. this._upEl = hoveredTarget;
  2163. }
  2164. else if (name === 'mouseup') {
  2165. this._upEl = hoveredTarget;
  2166. }
  2167. else if (name === 'click') {
  2168. if (this._downEl !== this._upEl
  2169. || !this._downPoint
  2170. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2171. return;
  2172. }
  2173. this._downPoint = null;
  2174. }
  2175. this.dispatchToElement(hovered, name, event);
  2176. };
  2177. });
  2178. function isHover(displayable, x, y) {
  2179. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2180. var el = displayable;
  2181. var isSilent = void 0;
  2182. var ignoreClip = false;
  2183. while (el) {
  2184. if (el.ignoreClip) {
  2185. ignoreClip = true;
  2186. }
  2187. if (!ignoreClip) {
  2188. var clipPath = el.getClipPath();
  2189. if (clipPath && !clipPath.contain(x, y)) {
  2190. return false;
  2191. }
  2192. }
  2193. if (el.silent) {
  2194. isSilent = true;
  2195. }
  2196. var hostEl = el.__hostTarget;
  2197. el = hostEl ? hostEl : el.parent;
  2198. }
  2199. return isSilent ? SILENT : true;
  2200. }
  2201. return false;
  2202. }
  2203. function setHoverTarget(list, out, x, y, exclude) {
  2204. for (var i = list.length - 1; i >= 0; i--) {
  2205. var el = list[i];
  2206. var hoverCheckResult = void 0;
  2207. if (el !== exclude
  2208. && !el.ignore
  2209. && (hoverCheckResult = isHover(el, x, y))) {
  2210. !out.topTarget && (out.topTarget = el);
  2211. if (hoverCheckResult !== SILENT) {
  2212. out.target = el;
  2213. break;
  2214. }
  2215. }
  2216. }
  2217. }
  2218. function isOutsideBoundary(handlerInstance, x, y) {
  2219. var painter = handlerInstance.painter;
  2220. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2221. }
  2222. var DEFAULT_MIN_MERGE = 32;
  2223. var DEFAULT_MIN_GALLOPING = 7;
  2224. function minRunLength(n) {
  2225. var r = 0;
  2226. while (n >= DEFAULT_MIN_MERGE) {
  2227. r |= n & 1;
  2228. n >>= 1;
  2229. }
  2230. return n + r;
  2231. }
  2232. function makeAscendingRun(array, lo, hi, compare) {
  2233. var runHi = lo + 1;
  2234. if (runHi === hi) {
  2235. return 1;
  2236. }
  2237. if (compare(array[runHi++], array[lo]) < 0) {
  2238. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  2239. runHi++;
  2240. }
  2241. reverseRun(array, lo, runHi);
  2242. }
  2243. else {
  2244. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  2245. runHi++;
  2246. }
  2247. }
  2248. return runHi - lo;
  2249. }
  2250. function reverseRun(array, lo, hi) {
  2251. hi--;
  2252. while (lo < hi) {
  2253. var t = array[lo];
  2254. array[lo++] = array[hi];
  2255. array[hi--] = t;
  2256. }
  2257. }
  2258. function binaryInsertionSort(array, lo, hi, start, compare) {
  2259. if (start === lo) {
  2260. start++;
  2261. }
  2262. for (; start < hi; start++) {
  2263. var pivot = array[start];
  2264. var left = lo;
  2265. var right = start;
  2266. var mid;
  2267. while (left < right) {
  2268. mid = left + right >>> 1;
  2269. if (compare(pivot, array[mid]) < 0) {
  2270. right = mid;
  2271. }
  2272. else {
  2273. left = mid + 1;
  2274. }
  2275. }
  2276. var n = start - left;
  2277. switch (n) {
  2278. case 3:
  2279. array[left + 3] = array[left + 2];
  2280. case 2:
  2281. array[left + 2] = array[left + 1];
  2282. case 1:
  2283. array[left + 1] = array[left];
  2284. break;
  2285. default:
  2286. while (n > 0) {
  2287. array[left + n] = array[left + n - 1];
  2288. n--;
  2289. }
  2290. }
  2291. array[left] = pivot;
  2292. }
  2293. }
  2294. function gallopLeft(value, array, start, length, hint, compare) {
  2295. var lastOffset = 0;
  2296. var maxOffset = 0;
  2297. var offset = 1;
  2298. if (compare(value, array[start + hint]) > 0) {
  2299. maxOffset = length - hint;
  2300. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  2301. lastOffset = offset;
  2302. offset = (offset << 1) + 1;
  2303. if (offset <= 0) {
  2304. offset = maxOffset;
  2305. }
  2306. }
  2307. if (offset > maxOffset) {
  2308. offset = maxOffset;
  2309. }
  2310. lastOffset += hint;
  2311. offset += hint;
  2312. }
  2313. else {
  2314. maxOffset = hint + 1;
  2315. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  2316. lastOffset = offset;
  2317. offset = (offset << 1) + 1;
  2318. if (offset <= 0) {
  2319. offset = maxOffset;
  2320. }
  2321. }
  2322. if (offset > maxOffset) {
  2323. offset = maxOffset;
  2324. }
  2325. var tmp = lastOffset;
  2326. lastOffset = hint - offset;
  2327. offset = hint - tmp;
  2328. }
  2329. lastOffset++;
  2330. while (lastOffset < offset) {
  2331. var m = lastOffset + (offset - lastOffset >>> 1);
  2332. if (compare(value, array[start + m]) > 0) {
  2333. lastOffset = m + 1;
  2334. }
  2335. else {
  2336. offset = m;
  2337. }
  2338. }
  2339. return offset;
  2340. }
  2341. function gallopRight(value, array, start, length, hint, compare) {
  2342. var lastOffset = 0;
  2343. var maxOffset = 0;
  2344. var offset = 1;
  2345. if (compare(value, array[start + hint]) < 0) {
  2346. maxOffset = hint + 1;
  2347. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  2348. lastOffset = offset;
  2349. offset = (offset << 1) + 1;
  2350. if (offset <= 0) {
  2351. offset = maxOffset;
  2352. }
  2353. }
  2354. if (offset > maxOffset) {
  2355. offset = maxOffset;
  2356. }
  2357. var tmp = lastOffset;
  2358. lastOffset = hint - offset;
  2359. offset = hint - tmp;
  2360. }
  2361. else {
  2362. maxOffset = length - hint;
  2363. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  2364. lastOffset = offset;
  2365. offset = (offset << 1) + 1;
  2366. if (offset <= 0) {
  2367. offset = maxOffset;
  2368. }
  2369. }
  2370. if (offset > maxOffset) {
  2371. offset = maxOffset;
  2372. }
  2373. lastOffset += hint;
  2374. offset += hint;
  2375. }
  2376. lastOffset++;
  2377. while (lastOffset < offset) {
  2378. var m = lastOffset + (offset - lastOffset >>> 1);
  2379. if (compare(value, array[start + m]) < 0) {
  2380. offset = m;
  2381. }
  2382. else {
  2383. lastOffset = m + 1;
  2384. }
  2385. }
  2386. return offset;
  2387. }
  2388. function TimSort(array, compare) {
  2389. var minGallop = DEFAULT_MIN_GALLOPING;
  2390. var runStart;
  2391. var runLength;
  2392. var stackSize = 0;
  2393. var tmp = [];
  2394. runStart = [];
  2395. runLength = [];
  2396. function pushRun(_runStart, _runLength) {
  2397. runStart[stackSize] = _runStart;
  2398. runLength[stackSize] = _runLength;
  2399. stackSize += 1;
  2400. }
  2401. function mergeRuns() {
  2402. while (stackSize > 1) {
  2403. var n = stackSize - 2;
  2404. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  2405. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  2406. if (runLength[n - 1] < runLength[n + 1]) {
  2407. n--;
  2408. }
  2409. }
  2410. else if (runLength[n] > runLength[n + 1]) {
  2411. break;
  2412. }
  2413. mergeAt(n);
  2414. }
  2415. }
  2416. function forceMergeRuns() {
  2417. while (stackSize > 1) {
  2418. var n = stackSize - 2;
  2419. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  2420. n--;
  2421. }
  2422. mergeAt(n);
  2423. }
  2424. }
  2425. function mergeAt(i) {
  2426. var start1 = runStart[i];
  2427. var length1 = runLength[i];
  2428. var start2 = runStart[i + 1];
  2429. var length2 = runLength[i + 1];
  2430. runLength[i] = length1 + length2;
  2431. if (i === stackSize - 3) {
  2432. runStart[i + 1] = runStart[i + 2];
  2433. runLength[i + 1] = runLength[i + 2];
  2434. }
  2435. stackSize--;
  2436. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  2437. start1 += k;
  2438. length1 -= k;
  2439. if (length1 === 0) {
  2440. return;
  2441. }
  2442. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  2443. if (length2 === 0) {
  2444. return;
  2445. }
  2446. if (length1 <= length2) {
  2447. mergeLow(start1, length1, start2, length2);
  2448. }
  2449. else {
  2450. mergeHigh(start1, length1, start2, length2);
  2451. }
  2452. }
  2453. function mergeLow(start1, length1, start2, length2) {
  2454. var i = 0;
  2455. for (i = 0; i < length1; i++) {
  2456. tmp[i] = array[start1 + i];
  2457. }
  2458. var cursor1 = 0;
  2459. var cursor2 = start2;
  2460. var dest = start1;
  2461. array[dest++] = array[cursor2++];
  2462. if (--length2 === 0) {
  2463. for (i = 0; i < length1; i++) {
  2464. array[dest + i] = tmp[cursor1 + i];
  2465. }
  2466. return;
  2467. }
  2468. if (length1 === 1) {
  2469. for (i = 0; i < length2; i++) {
  2470. array[dest + i] = array[cursor2 + i];
  2471. }
  2472. array[dest + length2] = tmp[cursor1];
  2473. return;
  2474. }
  2475. var _minGallop = minGallop;
  2476. var count1;
  2477. var count2;
  2478. var exit;
  2479. while (1) {
  2480. count1 = 0;
  2481. count2 = 0;
  2482. exit = false;
  2483. do {
  2484. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  2485. array[dest++] = array[cursor2++];
  2486. count2++;
  2487. count1 = 0;
  2488. if (--length2 === 0) {
  2489. exit = true;
  2490. break;
  2491. }
  2492. }
  2493. else {
  2494. array[dest++] = tmp[cursor1++];
  2495. count1++;
  2496. count2 = 0;
  2497. if (--length1 === 1) {
  2498. exit = true;
  2499. break;
  2500. }
  2501. }
  2502. } while ((count1 | count2) < _minGallop);
  2503. if (exit) {
  2504. break;
  2505. }
  2506. do {
  2507. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  2508. if (count1 !== 0) {
  2509. for (i = 0; i < count1; i++) {
  2510. array[dest + i] = tmp[cursor1 + i];
  2511. }
  2512. dest += count1;
  2513. cursor1 += count1;
  2514. length1 -= count1;
  2515. if (length1 <= 1) {
  2516. exit = true;
  2517. break;
  2518. }
  2519. }
  2520. array[dest++] = array[cursor2++];
  2521. if (--length2 === 0) {
  2522. exit = true;
  2523. break;
  2524. }
  2525. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  2526. if (count2 !== 0) {
  2527. for (i = 0; i < count2; i++) {
  2528. array[dest + i] = array[cursor2 + i];
  2529. }
  2530. dest += count2;
  2531. cursor2 += count2;
  2532. length2 -= count2;
  2533. if (length2 === 0) {
  2534. exit = true;
  2535. break;
  2536. }
  2537. }
  2538. array[dest++] = tmp[cursor1++];
  2539. if (--length1 === 1) {
  2540. exit = true;
  2541. break;
  2542. }
  2543. _minGallop--;
  2544. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2545. if (exit) {
  2546. break;
  2547. }
  2548. if (_minGallop < 0) {
  2549. _minGallop = 0;
  2550. }
  2551. _minGallop += 2;
  2552. }
  2553. minGallop = _minGallop;
  2554. minGallop < 1 && (minGallop = 1);
  2555. if (length1 === 1) {
  2556. for (i = 0; i < length2; i++) {
  2557. array[dest + i] = array[cursor2 + i];
  2558. }
  2559. array[dest + length2] = tmp[cursor1];
  2560. }
  2561. else if (length1 === 0) {
  2562. throw new Error();
  2563. }
  2564. else {
  2565. for (i = 0; i < length1; i++) {
  2566. array[dest + i] = tmp[cursor1 + i];
  2567. }
  2568. }
  2569. }
  2570. function mergeHigh(start1, length1, start2, length2) {
  2571. var i = 0;
  2572. for (i = 0; i < length2; i++) {
  2573. tmp[i] = array[start2 + i];
  2574. }
  2575. var cursor1 = start1 + length1 - 1;
  2576. var cursor2 = length2 - 1;
  2577. var dest = start2 + length2 - 1;
  2578. var customCursor = 0;
  2579. var customDest = 0;
  2580. array[dest--] = array[cursor1--];
  2581. if (--length1 === 0) {
  2582. customCursor = dest - (length2 - 1);
  2583. for (i = 0; i < length2; i++) {
  2584. array[customCursor + i] = tmp[i];
  2585. }
  2586. return;
  2587. }
  2588. if (length2 === 1) {
  2589. dest -= length1;
  2590. cursor1 -= length1;
  2591. customDest = dest + 1;
  2592. customCursor = cursor1 + 1;
  2593. for (i = length1 - 1; i >= 0; i--) {
  2594. array[customDest + i] = array[customCursor + i];
  2595. }
  2596. array[dest] = tmp[cursor2];
  2597. return;
  2598. }
  2599. var _minGallop = minGallop;
  2600. while (true) {
  2601. var count1 = 0;
  2602. var count2 = 0;
  2603. var exit = false;
  2604. do {
  2605. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2606. array[dest--] = array[cursor1--];
  2607. count1++;
  2608. count2 = 0;
  2609. if (--length1 === 0) {
  2610. exit = true;
  2611. break;
  2612. }
  2613. }
  2614. else {
  2615. array[dest--] = tmp[cursor2--];
  2616. count2++;
  2617. count1 = 0;
  2618. if (--length2 === 1) {
  2619. exit = true;
  2620. break;
  2621. }
  2622. }
  2623. } while ((count1 | count2) < _minGallop);
  2624. if (exit) {
  2625. break;
  2626. }
  2627. do {
  2628. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2629. if (count1 !== 0) {
  2630. dest -= count1;
  2631. cursor1 -= count1;
  2632. length1 -= count1;
  2633. customDest = dest + 1;
  2634. customCursor = cursor1 + 1;
  2635. for (i = count1 - 1; i >= 0; i--) {
  2636. array[customDest + i] = array[customCursor + i];
  2637. }
  2638. if (length1 === 0) {
  2639. exit = true;
  2640. break;
  2641. }
  2642. }
  2643. array[dest--] = tmp[cursor2--];
  2644. if (--length2 === 1) {
  2645. exit = true;
  2646. break;
  2647. }
  2648. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2649. if (count2 !== 0) {
  2650. dest -= count2;
  2651. cursor2 -= count2;
  2652. length2 -= count2;
  2653. customDest = dest + 1;
  2654. customCursor = cursor2 + 1;
  2655. for (i = 0; i < count2; i++) {
  2656. array[customDest + i] = tmp[customCursor + i];
  2657. }
  2658. if (length2 <= 1) {
  2659. exit = true;
  2660. break;
  2661. }
  2662. }
  2663. array[dest--] = array[cursor1--];
  2664. if (--length1 === 0) {
  2665. exit = true;
  2666. break;
  2667. }
  2668. _minGallop--;
  2669. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2670. if (exit) {
  2671. break;
  2672. }
  2673. if (_minGallop < 0) {
  2674. _minGallop = 0;
  2675. }
  2676. _minGallop += 2;
  2677. }
  2678. minGallop = _minGallop;
  2679. if (minGallop < 1) {
  2680. minGallop = 1;
  2681. }
  2682. if (length2 === 1) {
  2683. dest -= length1;
  2684. cursor1 -= length1;
  2685. customDest = dest + 1;
  2686. customCursor = cursor1 + 1;
  2687. for (i = length1 - 1; i >= 0; i--) {
  2688. array[customDest + i] = array[customCursor + i];
  2689. }
  2690. array[dest] = tmp[cursor2];
  2691. }
  2692. else if (length2 === 0) {
  2693. throw new Error();
  2694. }
  2695. else {
  2696. customCursor = dest - (length2 - 1);
  2697. for (i = 0; i < length2; i++) {
  2698. array[customCursor + i] = tmp[i];
  2699. }
  2700. }
  2701. }
  2702. return {
  2703. mergeRuns: mergeRuns,
  2704. forceMergeRuns: forceMergeRuns,
  2705. pushRun: pushRun
  2706. };
  2707. }
  2708. function sort(array, compare, lo, hi) {
  2709. if (!lo) {
  2710. lo = 0;
  2711. }
  2712. if (!hi) {
  2713. hi = array.length;
  2714. }
  2715. var remaining = hi - lo;
  2716. if (remaining < 2) {
  2717. return;
  2718. }
  2719. var runLength = 0;
  2720. if (remaining < DEFAULT_MIN_MERGE) {
  2721. runLength = makeAscendingRun(array, lo, hi, compare);
  2722. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2723. return;
  2724. }
  2725. var ts = TimSort(array, compare);
  2726. var minRun = minRunLength(remaining);
  2727. do {
  2728. runLength = makeAscendingRun(array, lo, hi, compare);
  2729. if (runLength < minRun) {
  2730. var force = remaining;
  2731. if (force > minRun) {
  2732. force = minRun;
  2733. }
  2734. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2735. runLength = force;
  2736. }
  2737. ts.pushRun(lo, runLength);
  2738. ts.mergeRuns();
  2739. remaining -= runLength;
  2740. lo += runLength;
  2741. } while (remaining !== 0);
  2742. ts.forceMergeRuns();
  2743. }
  2744. var REDRAW_BIT = 1;
  2745. var STYLE_CHANGED_BIT = 2;
  2746. var SHAPE_CHANGED_BIT = 4;
  2747. var invalidZErrorLogged = false;
  2748. function logInvalidZError() {
  2749. if (invalidZErrorLogged) {
  2750. return;
  2751. }
  2752. invalidZErrorLogged = true;
  2753. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2754. }
  2755. function shapeCompareFunc(a, b) {
  2756. if (a.zlevel === b.zlevel) {
  2757. if (a.z === b.z) {
  2758. return a.z2 - b.z2;
  2759. }
  2760. return a.z - b.z;
  2761. }
  2762. return a.zlevel - b.zlevel;
  2763. }
  2764. var Storage = (function () {
  2765. function Storage() {
  2766. this._roots = [];
  2767. this._displayList = [];
  2768. this._displayListLen = 0;
  2769. this.displayableSortFunc = shapeCompareFunc;
  2770. }
  2771. Storage.prototype.traverse = function (cb, context) {
  2772. for (var i = 0; i < this._roots.length; i++) {
  2773. this._roots[i].traverse(cb, context);
  2774. }
  2775. };
  2776. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2777. includeIgnore = includeIgnore || false;
  2778. var displayList = this._displayList;
  2779. if (update || !displayList.length) {
  2780. this.updateDisplayList(includeIgnore);
  2781. }
  2782. return displayList;
  2783. };
  2784. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2785. this._displayListLen = 0;
  2786. var roots = this._roots;
  2787. var displayList = this._displayList;
  2788. for (var i = 0, len = roots.length; i < len; i++) {
  2789. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2790. }
  2791. displayList.length = this._displayListLen;
  2792. sort(displayList, shapeCompareFunc);
  2793. };
  2794. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2795. if (el.ignore && !includeIgnore) {
  2796. return;
  2797. }
  2798. el.beforeUpdate();
  2799. el.update();
  2800. el.afterUpdate();
  2801. var userSetClipPath = el.getClipPath();
  2802. if (el.ignoreClip) {
  2803. clipPaths = null;
  2804. }
  2805. else if (userSetClipPath) {
  2806. if (clipPaths) {
  2807. clipPaths = clipPaths.slice();
  2808. }
  2809. else {
  2810. clipPaths = [];
  2811. }
  2812. var currentClipPath = userSetClipPath;
  2813. var parentClipPath = el;
  2814. while (currentClipPath) {
  2815. currentClipPath.parent = parentClipPath;
  2816. currentClipPath.updateTransform();
  2817. clipPaths.push(currentClipPath);
  2818. parentClipPath = currentClipPath;
  2819. currentClipPath = currentClipPath.getClipPath();
  2820. }
  2821. }
  2822. if (el.childrenRef) {
  2823. var children = el.childrenRef();
  2824. for (var i = 0; i < children.length; i++) {
  2825. var child = children[i];
  2826. if (el.__dirty) {
  2827. child.__dirty |= REDRAW_BIT;
  2828. }
  2829. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2830. }
  2831. el.__dirty = 0;
  2832. }
  2833. else {
  2834. var disp = el;
  2835. if (clipPaths && clipPaths.length) {
  2836. disp.__clipPaths = clipPaths;
  2837. }
  2838. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2839. disp.__clipPaths = [];
  2840. }
  2841. if (isNaN(disp.z)) {
  2842. logInvalidZError();
  2843. disp.z = 0;
  2844. }
  2845. if (isNaN(disp.z2)) {
  2846. logInvalidZError();
  2847. disp.z2 = 0;
  2848. }
  2849. if (isNaN(disp.zlevel)) {
  2850. logInvalidZError();
  2851. disp.zlevel = 0;
  2852. }
  2853. this._displayList[this._displayListLen++] = disp;
  2854. }
  2855. var decalEl = el.getDecalElement && el.getDecalElement();
  2856. if (decalEl) {
  2857. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2858. }
  2859. var textGuide = el.getTextGuideLine();
  2860. if (textGuide) {
  2861. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2862. }
  2863. var textEl = el.getTextContent();
  2864. if (textEl) {
  2865. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2866. }
  2867. };
  2868. Storage.prototype.addRoot = function (el) {
  2869. if (el.__zr && el.__zr.storage === this) {
  2870. return;
  2871. }
  2872. this._roots.push(el);
  2873. };
  2874. Storage.prototype.delRoot = function (el) {
  2875. if (el instanceof Array) {
  2876. for (var i = 0, l = el.length; i < l; i++) {
  2877. this.delRoot(el[i]);
  2878. }
  2879. return;
  2880. }
  2881. var idx = indexOf(this._roots, el);
  2882. if (idx >= 0) {
  2883. this._roots.splice(idx, 1);
  2884. }
  2885. };
  2886. Storage.prototype.delAllRoots = function () {
  2887. this._roots = [];
  2888. this._displayList = [];
  2889. this._displayListLen = 0;
  2890. return;
  2891. };
  2892. Storage.prototype.getRoots = function () {
  2893. return this._roots;
  2894. };
  2895. Storage.prototype.dispose = function () {
  2896. this._displayList = null;
  2897. this._roots = null;
  2898. };
  2899. return Storage;
  2900. }());
  2901. var requestAnimationFrame;
  2902. requestAnimationFrame = (env.hasGlobalWindow
  2903. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2904. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2905. || window.mozRequestAnimationFrame
  2906. || window.webkitRequestAnimationFrame)) || function (func) {
  2907. return setTimeout(func, 16);
  2908. };
  2909. var requestAnimationFrame$1 = requestAnimationFrame;
  2910. var easingFuncs = {
  2911. linear: function (k) {
  2912. return k;
  2913. },
  2914. quadraticIn: function (k) {
  2915. return k * k;
  2916. },
  2917. quadraticOut: function (k) {
  2918. return k * (2 - k);
  2919. },
  2920. quadraticInOut: function (k) {
  2921. if ((k *= 2) < 1) {
  2922. return 0.5 * k * k;
  2923. }
  2924. return -0.5 * (--k * (k - 2) - 1);
  2925. },
  2926. cubicIn: function (k) {
  2927. return k * k * k;
  2928. },
  2929. cubicOut: function (k) {
  2930. return --k * k * k + 1;
  2931. },
  2932. cubicInOut: function (k) {
  2933. if ((k *= 2) < 1) {
  2934. return 0.5 * k * k * k;
  2935. }
  2936. return 0.5 * ((k -= 2) * k * k + 2);
  2937. },
  2938. quarticIn: function (k) {
  2939. return k * k * k * k;
  2940. },
  2941. quarticOut: function (k) {
  2942. return 1 - (--k * k * k * k);
  2943. },
  2944. quarticInOut: function (k) {
  2945. if ((k *= 2) < 1) {
  2946. return 0.5 * k * k * k * k;
  2947. }
  2948. return -0.5 * ((k -= 2) * k * k * k - 2);
  2949. },
  2950. quinticIn: function (k) {
  2951. return k * k * k * k * k;
  2952. },
  2953. quinticOut: function (k) {
  2954. return --k * k * k * k * k + 1;
  2955. },
  2956. quinticInOut: function (k) {
  2957. if ((k *= 2) < 1) {
  2958. return 0.5 * k * k * k * k * k;
  2959. }
  2960. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2961. },
  2962. sinusoidalIn: function (k) {
  2963. return 1 - Math.cos(k * Math.PI / 2);
  2964. },
  2965. sinusoidalOut: function (k) {
  2966. return Math.sin(k * Math.PI / 2);
  2967. },
  2968. sinusoidalInOut: function (k) {
  2969. return 0.5 * (1 - Math.cos(Math.PI * k));
  2970. },
  2971. exponentialIn: function (k) {
  2972. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2973. },
  2974. exponentialOut: function (k) {
  2975. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2976. },
  2977. exponentialInOut: function (k) {
  2978. if (k === 0) {
  2979. return 0;
  2980. }
  2981. if (k === 1) {
  2982. return 1;
  2983. }
  2984. if ((k *= 2) < 1) {
  2985. return 0.5 * Math.pow(1024, k - 1);
  2986. }
  2987. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2988. },
  2989. circularIn: function (k) {
  2990. return 1 - Math.sqrt(1 - k * k);
  2991. },
  2992. circularOut: function (k) {
  2993. return Math.sqrt(1 - (--k * k));
  2994. },
  2995. circularInOut: function (k) {
  2996. if ((k *= 2) < 1) {
  2997. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2998. }
  2999. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3000. },
  3001. elasticIn: function (k) {
  3002. var s;
  3003. var a = 0.1;
  3004. var p = 0.4;
  3005. if (k === 0) {
  3006. return 0;
  3007. }
  3008. if (k === 1) {
  3009. return 1;
  3010. }
  3011. if (!a || a < 1) {
  3012. a = 1;
  3013. s = p / 4;
  3014. }
  3015. else {
  3016. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3017. }
  3018. return -(a * Math.pow(2, 10 * (k -= 1))
  3019. * Math.sin((k - s) * (2 * Math.PI) / p));
  3020. },
  3021. elasticOut: function (k) {
  3022. var s;
  3023. var a = 0.1;
  3024. var p = 0.4;
  3025. if (k === 0) {
  3026. return 0;
  3027. }
  3028. if (k === 1) {
  3029. return 1;
  3030. }
  3031. if (!a || a < 1) {
  3032. a = 1;
  3033. s = p / 4;
  3034. }
  3035. else {
  3036. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3037. }
  3038. return (a * Math.pow(2, -10 * k)
  3039. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3040. },
  3041. elasticInOut: function (k) {
  3042. var s;
  3043. var a = 0.1;
  3044. var p = 0.4;
  3045. if (k === 0) {
  3046. return 0;
  3047. }
  3048. if (k === 1) {
  3049. return 1;
  3050. }
  3051. if (!a || a < 1) {
  3052. a = 1;
  3053. s = p / 4;
  3054. }
  3055. else {
  3056. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3057. }
  3058. if ((k *= 2) < 1) {
  3059. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3060. * Math.sin((k - s) * (2 * Math.PI) / p));
  3061. }
  3062. return a * Math.pow(2, -10 * (k -= 1))
  3063. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3064. },
  3065. backIn: function (k) {
  3066. var s = 1.70158;
  3067. return k * k * ((s + 1) * k - s);
  3068. },
  3069. backOut: function (k) {
  3070. var s = 1.70158;
  3071. return --k * k * ((s + 1) * k + s) + 1;
  3072. },
  3073. backInOut: function (k) {
  3074. var s = 1.70158 * 1.525;
  3075. if ((k *= 2) < 1) {
  3076. return 0.5 * (k * k * ((s + 1) * k - s));
  3077. }
  3078. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3079. },
  3080. bounceIn: function (k) {
  3081. return 1 - easingFuncs.bounceOut(1 - k);
  3082. },
  3083. bounceOut: function (k) {
  3084. if (k < (1 / 2.75)) {
  3085. return 7.5625 * k * k;
  3086. }
  3087. else if (k < (2 / 2.75)) {
  3088. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3089. }
  3090. else if (k < (2.5 / 2.75)) {
  3091. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3092. }
  3093. else {
  3094. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3095. }
  3096. },
  3097. bounceInOut: function (k) {
  3098. if (k < 0.5) {
  3099. return easingFuncs.bounceIn(k * 2) * 0.5;
  3100. }
  3101. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3102. }
  3103. };
  3104. var mathPow = Math.pow;
  3105. var mathSqrt = Math.sqrt;
  3106. var EPSILON = 1e-8;
  3107. var EPSILON_NUMERIC = 1e-4;
  3108. var THREE_SQRT = mathSqrt(3);
  3109. var ONE_THIRD = 1 / 3;
  3110. var _v0 = create();
  3111. var _v1 = create();
  3112. var _v2 = create();
  3113. function isAroundZero(val) {
  3114. return val > -EPSILON && val < EPSILON;
  3115. }
  3116. function isNotAroundZero(val) {
  3117. return val > EPSILON || val < -EPSILON;
  3118. }
  3119. function cubicAt(p0, p1, p2, p3, t) {
  3120. var onet = 1 - t;
  3121. return onet * onet * (onet * p0 + 3 * t * p1)
  3122. + t * t * (t * p3 + 3 * onet * p2);
  3123. }
  3124. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  3125. var onet = 1 - t;
  3126. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  3127. + (p3 - p2) * t * t);
  3128. }
  3129. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  3130. var a = p3 + 3 * (p1 - p2) - p0;
  3131. var b = 3 * (p2 - p1 * 2 + p0);
  3132. var c = 3 * (p1 - p0);
  3133. var d = p0 - val;
  3134. var A = b * b - 3 * a * c;
  3135. var B = b * c - 9 * a * d;
  3136. var C = c * c - 3 * b * d;
  3137. var n = 0;
  3138. if (isAroundZero(A) && isAroundZero(B)) {
  3139. if (isAroundZero(b)) {
  3140. roots[0] = 0;
  3141. }
  3142. else {
  3143. var t1 = -c / b;
  3144. if (t1 >= 0 && t1 <= 1) {
  3145. roots[n++] = t1;
  3146. }
  3147. }
  3148. }
  3149. else {
  3150. var disc = B * B - 4 * A * C;
  3151. if (isAroundZero(disc)) {
  3152. var K = B / A;
  3153. var t1 = -b / a + K;
  3154. var t2 = -K / 2;
  3155. if (t1 >= 0 && t1 <= 1) {
  3156. roots[n++] = t1;
  3157. }
  3158. if (t2 >= 0 && t2 <= 1) {
  3159. roots[n++] = t2;
  3160. }
  3161. }
  3162. else if (disc > 0) {
  3163. var discSqrt = mathSqrt(disc);
  3164. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  3165. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  3166. if (Y1 < 0) {
  3167. Y1 = -mathPow(-Y1, ONE_THIRD);
  3168. }
  3169. else {
  3170. Y1 = mathPow(Y1, ONE_THIRD);
  3171. }
  3172. if (Y2 < 0) {
  3173. Y2 = -mathPow(-Y2, ONE_THIRD);
  3174. }
  3175. else {
  3176. Y2 = mathPow(Y2, ONE_THIRD);
  3177. }
  3178. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  3179. if (t1 >= 0 && t1 <= 1) {
  3180. roots[n++] = t1;
  3181. }
  3182. }
  3183. else {
  3184. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  3185. var theta = Math.acos(T) / 3;
  3186. var ASqrt = mathSqrt(A);
  3187. var tmp = Math.cos(theta);
  3188. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  3189. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  3190. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  3191. if (t1 >= 0 && t1 <= 1) {
  3192. roots[n++] = t1;
  3193. }
  3194. if (t2 >= 0 && t2 <= 1) {
  3195. roots[n++] = t2;
  3196. }
  3197. if (t3 >= 0 && t3 <= 1) {
  3198. roots[n++] = t3;
  3199. }
  3200. }
  3201. }
  3202. return n;
  3203. }
  3204. function cubicExtrema(p0, p1, p2, p3, extrema) {
  3205. var b = 6 * p2 - 12 * p1 + 6 * p0;
  3206. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  3207. var c = 3 * p1 - 3 * p0;
  3208. var n = 0;
  3209. if (isAroundZero(a)) {
  3210. if (isNotAroundZero(b)) {
  3211. var t1 = -c / b;
  3212. if (t1 >= 0 && t1 <= 1) {
  3213. extrema[n++] = t1;
  3214. }
  3215. }
  3216. }
  3217. else {
  3218. var disc = b * b - 4 * a * c;
  3219. if (isAroundZero(disc)) {
  3220. extrema[0] = -b / (2 * a);
  3221. }
  3222. else if (disc > 0) {
  3223. var discSqrt = mathSqrt(disc);
  3224. var t1 = (-b + discSqrt) / (2 * a);
  3225. var t2 = (-b - discSqrt) / (2 * a);
  3226. if (t1 >= 0 && t1 <= 1) {
  3227. extrema[n++] = t1;
  3228. }
  3229. if (t2 >= 0 && t2 <= 1) {
  3230. extrema[n++] = t2;
  3231. }
  3232. }
  3233. }
  3234. return n;
  3235. }
  3236. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  3237. var p01 = (p1 - p0) * t + p0;
  3238. var p12 = (p2 - p1) * t + p1;
  3239. var p23 = (p3 - p2) * t + p2;
  3240. var p012 = (p12 - p01) * t + p01;
  3241. var p123 = (p23 - p12) * t + p12;
  3242. var p0123 = (p123 - p012) * t + p012;
  3243. out[0] = p0;
  3244. out[1] = p01;
  3245. out[2] = p012;
  3246. out[3] = p0123;
  3247. out[4] = p0123;
  3248. out[5] = p123;
  3249. out[6] = p23;
  3250. out[7] = p3;
  3251. }
  3252. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  3253. var t;
  3254. var interval = 0.005;
  3255. var d = Infinity;
  3256. var prev;
  3257. var next;
  3258. var d1;
  3259. var d2;
  3260. _v0[0] = x;
  3261. _v0[1] = y;
  3262. for (var _t = 0; _t < 1; _t += 0.05) {
  3263. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  3264. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  3265. d1 = distSquare(_v0, _v1);
  3266. if (d1 < d) {
  3267. t = _t;
  3268. d = d1;
  3269. }
  3270. }
  3271. d = Infinity;
  3272. for (var i = 0; i < 32; i++) {
  3273. if (interval < EPSILON_NUMERIC) {
  3274. break;
  3275. }
  3276. prev = t - interval;
  3277. next = t + interval;
  3278. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  3279. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  3280. d1 = distSquare(_v1, _v0);
  3281. if (prev >= 0 && d1 < d) {
  3282. t = prev;
  3283. d = d1;
  3284. }
  3285. else {
  3286. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  3287. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  3288. d2 = distSquare(_v2, _v0);
  3289. if (next <= 1 && d2 < d) {
  3290. t = next;
  3291. d = d2;
  3292. }
  3293. else {
  3294. interval *= 0.5;
  3295. }
  3296. }
  3297. }
  3298. if (out) {
  3299. out[0] = cubicAt(x0, x1, x2, x3, t);
  3300. out[1] = cubicAt(y0, y1, y2, y3, t);
  3301. }
  3302. return mathSqrt(d);
  3303. }
  3304. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  3305. var px = x0;
  3306. var py = y0;
  3307. var d = 0;
  3308. var step = 1 / iteration;
  3309. for (var i = 1; i <= iteration; i++) {
  3310. var t = i * step;
  3311. var x = cubicAt(x0, x1, x2, x3, t);
  3312. var y = cubicAt(y0, y1, y2, y3, t);
  3313. var dx = x - px;
  3314. var dy = y - py;
  3315. d += Math.sqrt(dx * dx + dy * dy);
  3316. px = x;
  3317. py = y;
  3318. }
  3319. return d;
  3320. }
  3321. function quadraticAt(p0, p1, p2, t) {
  3322. var onet = 1 - t;
  3323. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  3324. }
  3325. function quadraticDerivativeAt(p0, p1, p2, t) {
  3326. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  3327. }
  3328. function quadraticRootAt(p0, p1, p2, val, roots) {
  3329. var a = p0 - 2 * p1 + p2;
  3330. var b = 2 * (p1 - p0);
  3331. var c = p0 - val;
  3332. var n = 0;
  3333. if (isAroundZero(a)) {
  3334. if (isNotAroundZero(b)) {
  3335. var t1 = -c / b;
  3336. if (t1 >= 0 && t1 <= 1) {
  3337. roots[n++] = t1;
  3338. }
  3339. }
  3340. }
  3341. else {
  3342. var disc = b * b - 4 * a * c;
  3343. if (isAroundZero(disc)) {
  3344. var t1 = -b / (2 * a);
  3345. if (t1 >= 0 && t1 <= 1) {
  3346. roots[n++] = t1;
  3347. }
  3348. }
  3349. else if (disc > 0) {
  3350. var discSqrt = mathSqrt(disc);
  3351. var t1 = (-b + discSqrt) / (2 * a);
  3352. var t2 = (-b - discSqrt) / (2 * a);
  3353. if (t1 >= 0 && t1 <= 1) {
  3354. roots[n++] = t1;
  3355. }
  3356. if (t2 >= 0 && t2 <= 1) {
  3357. roots[n++] = t2;
  3358. }
  3359. }
  3360. }
  3361. return n;
  3362. }
  3363. function quadraticExtremum(p0, p1, p2) {
  3364. var divider = p0 + p2 - 2 * p1;
  3365. if (divider === 0) {
  3366. return 0.5;
  3367. }
  3368. else {
  3369. return (p0 - p1) / divider;
  3370. }
  3371. }
  3372. function quadraticSubdivide(p0, p1, p2, t, out) {
  3373. var p01 = (p1 - p0) * t + p0;
  3374. var p12 = (p2 - p1) * t + p1;
  3375. var p012 = (p12 - p01) * t + p01;
  3376. out[0] = p0;
  3377. out[1] = p01;
  3378. out[2] = p012;
  3379. out[3] = p012;
  3380. out[4] = p12;
  3381. out[5] = p2;
  3382. }
  3383. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  3384. var t;
  3385. var interval = 0.005;
  3386. var d = Infinity;
  3387. _v0[0] = x;
  3388. _v0[1] = y;
  3389. for (var _t = 0; _t < 1; _t += 0.05) {
  3390. _v1[0] = quadraticAt(x0, x1, x2, _t);
  3391. _v1[1] = quadraticAt(y0, y1, y2, _t);
  3392. var d1 = distSquare(_v0, _v1);
  3393. if (d1 < d) {
  3394. t = _t;
  3395. d = d1;
  3396. }
  3397. }
  3398. d = Infinity;
  3399. for (var i = 0; i < 32; i++) {
  3400. if (interval < EPSILON_NUMERIC) {
  3401. break;
  3402. }
  3403. var prev = t - interval;
  3404. var next = t + interval;
  3405. _v1[0] = quadraticAt(x0, x1, x2, prev);
  3406. _v1[1] = quadraticAt(y0, y1, y2, prev);
  3407. var d1 = distSquare(_v1, _v0);
  3408. if (prev >= 0 && d1 < d) {
  3409. t = prev;
  3410. d = d1;
  3411. }
  3412. else {
  3413. _v2[0] = quadraticAt(x0, x1, x2, next);
  3414. _v2[1] = quadraticAt(y0, y1, y2, next);
  3415. var d2 = distSquare(_v2, _v0);
  3416. if (next <= 1 && d2 < d) {
  3417. t = next;
  3418. d = d2;
  3419. }
  3420. else {
  3421. interval *= 0.5;
  3422. }
  3423. }
  3424. }
  3425. if (out) {
  3426. out[0] = quadraticAt(x0, x1, x2, t);
  3427. out[1] = quadraticAt(y0, y1, y2, t);
  3428. }
  3429. return mathSqrt(d);
  3430. }
  3431. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  3432. var px = x0;
  3433. var py = y0;
  3434. var d = 0;
  3435. var step = 1 / iteration;
  3436. for (var i = 1; i <= iteration; i++) {
  3437. var t = i * step;
  3438. var x = quadraticAt(x0, x1, x2, t);
  3439. var y = quadraticAt(y0, y1, y2, t);
  3440. var dx = x - px;
  3441. var dy = y - py;
  3442. d += Math.sqrt(dx * dx + dy * dy);
  3443. px = x;
  3444. py = y;
  3445. }
  3446. return d;
  3447. }
  3448. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  3449. function createCubicEasingFunc(cubicEasingStr) {
  3450. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  3451. if (cubic) {
  3452. var points = cubic[1].split(',');
  3453. var a_1 = +trim(points[0]);
  3454. var b_1 = +trim(points[1]);
  3455. var c_1 = +trim(points[2]);
  3456. var d_1 = +trim(points[3]);
  3457. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  3458. return;
  3459. }
  3460. var roots_1 = [];
  3461. return function (p) {
  3462. return p <= 0
  3463. ? 0 : p >= 1
  3464. ? 1
  3465. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  3466. };
  3467. }
  3468. }
  3469. var Clip = (function () {
  3470. function Clip(opts) {
  3471. this._inited = false;
  3472. this._startTime = 0;
  3473. this._pausedTime = 0;
  3474. this._paused = false;
  3475. this._life = opts.life || 1000;
  3476. this._delay = opts.delay || 0;
  3477. this.loop = opts.loop || false;
  3478. this.onframe = opts.onframe || noop;
  3479. this.ondestroy = opts.ondestroy || noop;
  3480. this.onrestart = opts.onrestart || noop;
  3481. opts.easing && this.setEasing(opts.easing);
  3482. }
  3483. Clip.prototype.step = function (globalTime, deltaTime) {
  3484. if (!this._inited) {
  3485. this._startTime = globalTime + this._delay;
  3486. this._inited = true;
  3487. }
  3488. if (this._paused) {
  3489. this._pausedTime += deltaTime;
  3490. return;
  3491. }
  3492. var life = this._life;
  3493. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  3494. var percent = elapsedTime / life;
  3495. if (percent < 0) {
  3496. percent = 0;
  3497. }
  3498. percent = Math.min(percent, 1);
  3499. var easingFunc = this.easingFunc;
  3500. var schedule = easingFunc ? easingFunc(percent) : percent;
  3501. this.onframe(schedule);
  3502. if (percent === 1) {
  3503. if (this.loop) {
  3504. var remainder = elapsedTime % life;
  3505. this._startTime = globalTime - remainder;
  3506. this._pausedTime = 0;
  3507. this.onrestart();
  3508. }
  3509. else {
  3510. return true;
  3511. }
  3512. }
  3513. return false;
  3514. };
  3515. Clip.prototype.pause = function () {
  3516. this._paused = true;
  3517. };
  3518. Clip.prototype.resume = function () {
  3519. this._paused = false;
  3520. };
  3521. Clip.prototype.setEasing = function (easing) {
  3522. this.easing = easing;
  3523. this.easingFunc = isFunction(easing)
  3524. ? easing
  3525. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3526. };
  3527. return Clip;
  3528. }());
  3529. var Entry = (function () {
  3530. function Entry(val) {
  3531. this.value = val;
  3532. }
  3533. return Entry;
  3534. }());
  3535. var LinkedList = (function () {
  3536. function LinkedList() {
  3537. this._len = 0;
  3538. }
  3539. LinkedList.prototype.insert = function (val) {
  3540. var entry = new Entry(val);
  3541. this.insertEntry(entry);
  3542. return entry;
  3543. };
  3544. LinkedList.prototype.insertEntry = function (entry) {
  3545. if (!this.head) {
  3546. this.head = this.tail = entry;
  3547. }
  3548. else {
  3549. this.tail.next = entry;
  3550. entry.prev = this.tail;
  3551. entry.next = null;
  3552. this.tail = entry;
  3553. }
  3554. this._len++;
  3555. };
  3556. LinkedList.prototype.remove = function (entry) {
  3557. var prev = entry.prev;
  3558. var next = entry.next;
  3559. if (prev) {
  3560. prev.next = next;
  3561. }
  3562. else {
  3563. this.head = next;
  3564. }
  3565. if (next) {
  3566. next.prev = prev;
  3567. }
  3568. else {
  3569. this.tail = prev;
  3570. }
  3571. entry.next = entry.prev = null;
  3572. this._len--;
  3573. };
  3574. LinkedList.prototype.len = function () {
  3575. return this._len;
  3576. };
  3577. LinkedList.prototype.clear = function () {
  3578. this.head = this.tail = null;
  3579. this._len = 0;
  3580. };
  3581. return LinkedList;
  3582. }());
  3583. var LRU = (function () {
  3584. function LRU(maxSize) {
  3585. this._list = new LinkedList();
  3586. this._maxSize = 10;
  3587. this._map = {};
  3588. this._maxSize = maxSize;
  3589. }
  3590. LRU.prototype.put = function (key, value) {
  3591. var list = this._list;
  3592. var map = this._map;
  3593. var removed = null;
  3594. if (map[key] == null) {
  3595. var len = list.len();
  3596. var entry = this._lastRemovedEntry;
  3597. if (len >= this._maxSize && len > 0) {
  3598. var leastUsedEntry = list.head;
  3599. list.remove(leastUsedEntry);
  3600. delete map[leastUsedEntry.key];
  3601. removed = leastUsedEntry.value;
  3602. this._lastRemovedEntry = leastUsedEntry;
  3603. }
  3604. if (entry) {
  3605. entry.value = value;
  3606. }
  3607. else {
  3608. entry = new Entry(value);
  3609. }
  3610. entry.key = key;
  3611. list.insertEntry(entry);
  3612. map[key] = entry;
  3613. }
  3614. return removed;
  3615. };
  3616. LRU.prototype.get = function (key) {
  3617. var entry = this._map[key];
  3618. var list = this._list;
  3619. if (entry != null) {
  3620. if (entry !== list.tail) {
  3621. list.remove(entry);
  3622. list.insertEntry(entry);
  3623. }
  3624. return entry.value;
  3625. }
  3626. };
  3627. LRU.prototype.clear = function () {
  3628. this._list.clear();
  3629. this._map = {};
  3630. };
  3631. LRU.prototype.len = function () {
  3632. return this._list.len();
  3633. };
  3634. return LRU;
  3635. }());
  3636. var kCSSColorTable = {
  3637. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3638. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3639. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3640. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3641. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3642. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3643. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3644. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3645. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3646. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3647. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3648. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3649. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3650. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3651. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3652. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3653. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3654. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3655. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3656. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3657. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3658. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3659. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3660. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3661. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3662. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3663. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3664. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3665. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3666. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3667. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3668. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3669. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3670. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3671. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3672. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3673. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3674. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3675. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3676. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3677. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3678. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3679. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3680. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3681. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3682. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3683. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3684. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3685. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3686. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3687. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3688. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3689. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3690. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3691. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3692. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3693. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3694. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3695. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3696. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3697. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3698. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3699. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3700. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3701. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3702. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3703. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3704. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3705. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3706. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3707. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3708. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3709. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3710. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3711. };
  3712. function clampCssByte(i) {
  3713. i = Math.round(i);
  3714. return i < 0 ? 0 : i > 255 ? 255 : i;
  3715. }
  3716. function clampCssAngle(i) {
  3717. i = Math.round(i);
  3718. return i < 0 ? 0 : i > 360 ? 360 : i;
  3719. }
  3720. function clampCssFloat(f) {
  3721. return f < 0 ? 0 : f > 1 ? 1 : f;
  3722. }
  3723. function parseCssInt(val) {
  3724. var str = val;
  3725. if (str.length && str.charAt(str.length - 1) === '%') {
  3726. return clampCssByte(parseFloat(str) / 100 * 255);
  3727. }
  3728. return clampCssByte(parseInt(str, 10));
  3729. }
  3730. function parseCssFloat(val) {
  3731. var str = val;
  3732. if (str.length && str.charAt(str.length - 1) === '%') {
  3733. return clampCssFloat(parseFloat(str) / 100);
  3734. }
  3735. return clampCssFloat(parseFloat(str));
  3736. }
  3737. function cssHueToRgb(m1, m2, h) {
  3738. if (h < 0) {
  3739. h += 1;
  3740. }
  3741. else if (h > 1) {
  3742. h -= 1;
  3743. }
  3744. if (h * 6 < 1) {
  3745. return m1 + (m2 - m1) * h * 6;
  3746. }
  3747. if (h * 2 < 1) {
  3748. return m2;
  3749. }
  3750. if (h * 3 < 2) {
  3751. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3752. }
  3753. return m1;
  3754. }
  3755. function lerpNumber(a, b, p) {
  3756. return a + (b - a) * p;
  3757. }
  3758. function setRgba(out, r, g, b, a) {
  3759. out[0] = r;
  3760. out[1] = g;
  3761. out[2] = b;
  3762. out[3] = a;
  3763. return out;
  3764. }
  3765. function copyRgba(out, a) {
  3766. out[0] = a[0];
  3767. out[1] = a[1];
  3768. out[2] = a[2];
  3769. out[3] = a[3];
  3770. return out;
  3771. }
  3772. var colorCache = new LRU(20);
  3773. var lastRemovedArr = null;
  3774. function putToCache(colorStr, rgbaArr) {
  3775. if (lastRemovedArr) {
  3776. copyRgba(lastRemovedArr, rgbaArr);
  3777. }
  3778. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3779. }
  3780. function parse(colorStr, rgbaArr) {
  3781. if (!colorStr) {
  3782. return;
  3783. }
  3784. rgbaArr = rgbaArr || [];
  3785. var cached = colorCache.get(colorStr);
  3786. if (cached) {
  3787. return copyRgba(rgbaArr, cached);
  3788. }
  3789. colorStr = colorStr + '';
  3790. var str = colorStr.replace(/ /g, '').toLowerCase();
  3791. if (str in kCSSColorTable) {
  3792. copyRgba(rgbaArr, kCSSColorTable[str]);
  3793. putToCache(colorStr, rgbaArr);
  3794. return rgbaArr;
  3795. }
  3796. var strLen = str.length;
  3797. if (str.charAt(0) === '#') {
  3798. if (strLen === 4 || strLen === 5) {
  3799. var iv = parseInt(str.slice(1, 4), 16);
  3800. if (!(iv >= 0 && iv <= 0xfff)) {
  3801. setRgba(rgbaArr, 0, 0, 0, 1);
  3802. return;
  3803. }
  3804. 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);
  3805. putToCache(colorStr, rgbaArr);
  3806. return rgbaArr;
  3807. }
  3808. else if (strLen === 7 || strLen === 9) {
  3809. var iv = parseInt(str.slice(1, 7), 16);
  3810. if (!(iv >= 0 && iv <= 0xffffff)) {
  3811. setRgba(rgbaArr, 0, 0, 0, 1);
  3812. return;
  3813. }
  3814. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3815. putToCache(colorStr, rgbaArr);
  3816. return rgbaArr;
  3817. }
  3818. return;
  3819. }
  3820. var op = str.indexOf('(');
  3821. var ep = str.indexOf(')');
  3822. if (op !== -1 && ep + 1 === strLen) {
  3823. var fname = str.substr(0, op);
  3824. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3825. var alpha = 1;
  3826. switch (fname) {
  3827. case 'rgba':
  3828. if (params.length !== 4) {
  3829. return params.length === 3
  3830. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3831. : setRgba(rgbaArr, 0, 0, 0, 1);
  3832. }
  3833. alpha = parseCssFloat(params.pop());
  3834. case 'rgb':
  3835. if (params.length >= 3) {
  3836. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), params.length === 3 ? alpha : parseCssFloat(params[3]));
  3837. putToCache(colorStr, rgbaArr);
  3838. return rgbaArr;
  3839. }
  3840. else {
  3841. setRgba(rgbaArr, 0, 0, 0, 1);
  3842. return;
  3843. }
  3844. case 'hsla':
  3845. if (params.length !== 4) {
  3846. setRgba(rgbaArr, 0, 0, 0, 1);
  3847. return;
  3848. }
  3849. params[3] = parseCssFloat(params[3]);
  3850. hsla2rgba(params, rgbaArr);
  3851. putToCache(colorStr, rgbaArr);
  3852. return rgbaArr;
  3853. case 'hsl':
  3854. if (params.length !== 3) {
  3855. setRgba(rgbaArr, 0, 0, 0, 1);
  3856. return;
  3857. }
  3858. hsla2rgba(params, rgbaArr);
  3859. putToCache(colorStr, rgbaArr);
  3860. return rgbaArr;
  3861. default:
  3862. return;
  3863. }
  3864. }
  3865. setRgba(rgbaArr, 0, 0, 0, 1);
  3866. return;
  3867. }
  3868. function hsla2rgba(hsla, rgba) {
  3869. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3870. var s = parseCssFloat(hsla[1]);
  3871. var l = parseCssFloat(hsla[2]);
  3872. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3873. var m1 = l * 2 - m2;
  3874. rgba = rgba || [];
  3875. 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);
  3876. if (hsla.length === 4) {
  3877. rgba[3] = hsla[3];
  3878. }
  3879. return rgba;
  3880. }
  3881. function rgba2hsla(rgba) {
  3882. if (!rgba) {
  3883. return;
  3884. }
  3885. var R = rgba[0] / 255;
  3886. var G = rgba[1] / 255;
  3887. var B = rgba[2] / 255;
  3888. var vMin = Math.min(R, G, B);
  3889. var vMax = Math.max(R, G, B);
  3890. var delta = vMax - vMin;
  3891. var L = (vMax + vMin) / 2;
  3892. var H;
  3893. var S;
  3894. if (delta === 0) {
  3895. H = 0;
  3896. S = 0;
  3897. }
  3898. else {
  3899. if (L < 0.5) {
  3900. S = delta / (vMax + vMin);
  3901. }
  3902. else {
  3903. S = delta / (2 - vMax - vMin);
  3904. }
  3905. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3906. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3907. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3908. if (R === vMax) {
  3909. H = deltaB - deltaG;
  3910. }
  3911. else if (G === vMax) {
  3912. H = (1 / 3) + deltaR - deltaB;
  3913. }
  3914. else if (B === vMax) {
  3915. H = (2 / 3) + deltaG - deltaR;
  3916. }
  3917. if (H < 0) {
  3918. H += 1;
  3919. }
  3920. if (H > 1) {
  3921. H -= 1;
  3922. }
  3923. }
  3924. var hsla = [H * 360, S, L];
  3925. if (rgba[3] != null) {
  3926. hsla.push(rgba[3]);
  3927. }
  3928. return hsla;
  3929. }
  3930. function lift(color, level) {
  3931. var colorArr = parse(color);
  3932. if (colorArr) {
  3933. for (var i = 0; i < 3; i++) {
  3934. if (level < 0) {
  3935. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3936. }
  3937. else {
  3938. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3939. }
  3940. if (colorArr[i] > 255) {
  3941. colorArr[i] = 255;
  3942. }
  3943. else if (colorArr[i] < 0) {
  3944. colorArr[i] = 0;
  3945. }
  3946. }
  3947. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3948. }
  3949. }
  3950. function toHex(color) {
  3951. var colorArr = parse(color);
  3952. if (colorArr) {
  3953. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3954. }
  3955. }
  3956. function fastLerp(normalizedValue, colors, out) {
  3957. if (!(colors && colors.length)
  3958. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3959. return;
  3960. }
  3961. out = out || [];
  3962. var value = normalizedValue * (colors.length - 1);
  3963. var leftIndex = Math.floor(value);
  3964. var rightIndex = Math.ceil(value);
  3965. var leftColor = colors[leftIndex];
  3966. var rightColor = colors[rightIndex];
  3967. var dv = value - leftIndex;
  3968. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3969. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3970. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3971. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3972. return out;
  3973. }
  3974. var fastMapToColor = fastLerp;
  3975. function lerp$1(normalizedValue, colors, fullOutput) {
  3976. if (!(colors && colors.length)
  3977. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3978. return;
  3979. }
  3980. var value = normalizedValue * (colors.length - 1);
  3981. var leftIndex = Math.floor(value);
  3982. var rightIndex = Math.ceil(value);
  3983. var leftColor = parse(colors[leftIndex]);
  3984. var rightColor = parse(colors[rightIndex]);
  3985. var dv = value - leftIndex;
  3986. var color = stringify([
  3987. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3988. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3989. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3990. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3991. ], 'rgba');
  3992. return fullOutput
  3993. ? {
  3994. color: color,
  3995. leftIndex: leftIndex,
  3996. rightIndex: rightIndex,
  3997. value: value
  3998. }
  3999. : color;
  4000. }
  4001. var mapToColor = lerp$1;
  4002. function modifyHSL(color, h, s, l) {
  4003. var colorArr = parse(color);
  4004. if (color) {
  4005. colorArr = rgba2hsla(colorArr);
  4006. h != null && (colorArr[0] = clampCssAngle(h));
  4007. s != null && (colorArr[1] = parseCssFloat(s));
  4008. l != null && (colorArr[2] = parseCssFloat(l));
  4009. return stringify(hsla2rgba(colorArr), 'rgba');
  4010. }
  4011. }
  4012. function modifyAlpha(color, alpha) {
  4013. var colorArr = parse(color);
  4014. if (colorArr && alpha != null) {
  4015. colorArr[3] = clampCssFloat(alpha);
  4016. return stringify(colorArr, 'rgba');
  4017. }
  4018. }
  4019. function stringify(arrColor, type) {
  4020. if (!arrColor || !arrColor.length) {
  4021. return;
  4022. }
  4023. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  4024. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  4025. colorStr += ',' + arrColor[3];
  4026. }
  4027. return type + '(' + colorStr + ')';
  4028. }
  4029. function lum(color, backgroundLum) {
  4030. var arr = parse(color);
  4031. return arr
  4032. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  4033. + (1 - arr[3]) * backgroundLum
  4034. : 0;
  4035. }
  4036. function random() {
  4037. return stringify([
  4038. Math.round(Math.random() * 255),
  4039. Math.round(Math.random() * 255),
  4040. Math.round(Math.random() * 255)
  4041. ], 'rgb');
  4042. }
  4043. var liftedColorCache = new LRU(100);
  4044. function liftColor(color) {
  4045. if (isString(color)) {
  4046. var liftedColor = liftedColorCache.get(color);
  4047. if (!liftedColor) {
  4048. liftedColor = lift(color, -0.1);
  4049. liftedColorCache.put(color, liftedColor);
  4050. }
  4051. return liftedColor;
  4052. }
  4053. else if (isGradientObject(color)) {
  4054. var ret = extend({}, color);
  4055. ret.colorStops = map(color.colorStops, function (stop) { return ({
  4056. offset: stop.offset,
  4057. color: lift(stop.color, -0.1)
  4058. }); });
  4059. return ret;
  4060. }
  4061. return color;
  4062. }
  4063. var color = /*#__PURE__*/Object.freeze({
  4064. __proto__: null,
  4065. parse: parse,
  4066. lift: lift,
  4067. toHex: toHex,
  4068. fastLerp: fastLerp,
  4069. fastMapToColor: fastMapToColor,
  4070. lerp: lerp$1,
  4071. mapToColor: mapToColor,
  4072. modifyHSL: modifyHSL,
  4073. modifyAlpha: modifyAlpha,
  4074. stringify: stringify,
  4075. lum: lum,
  4076. random: random,
  4077. liftColor: liftColor
  4078. });
  4079. function isLinearGradient(val) {
  4080. return val.type === 'linear';
  4081. }
  4082. function isRadialGradient(val) {
  4083. return val.type === 'radial';
  4084. }
  4085. var arraySlice = Array.prototype.slice;
  4086. function interpolateNumber(p0, p1, percent) {
  4087. return (p1 - p0) * percent + p0;
  4088. }
  4089. function interpolate1DArray(out, p0, p1, percent) {
  4090. var len = p0.length;
  4091. for (var i = 0; i < len; i++) {
  4092. out[i] = interpolateNumber(p0[i], p1[i], percent);
  4093. }
  4094. return out;
  4095. }
  4096. function interpolate2DArray(out, p0, p1, percent) {
  4097. var len = p0.length;
  4098. var len2 = len && p0[0].length;
  4099. for (var i = 0; i < len; i++) {
  4100. if (!out[i]) {
  4101. out[i] = [];
  4102. }
  4103. for (var j = 0; j < len2; j++) {
  4104. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  4105. }
  4106. }
  4107. return out;
  4108. }
  4109. function add1DArray(out, p0, p1, sign) {
  4110. var len = p0.length;
  4111. for (var i = 0; i < len; i++) {
  4112. out[i] = p0[i] + p1[i] * sign;
  4113. }
  4114. return out;
  4115. }
  4116. function add2DArray(out, p0, p1, sign) {
  4117. var len = p0.length;
  4118. var len2 = len && p0[0].length;
  4119. for (var i = 0; i < len; i++) {
  4120. if (!out[i]) {
  4121. out[i] = [];
  4122. }
  4123. for (var j = 0; j < len2; j++) {
  4124. out[i][j] = p0[i][j] + p1[i][j] * sign;
  4125. }
  4126. }
  4127. return out;
  4128. }
  4129. function fillColorStops(val0, val1) {
  4130. var len0 = val0.length;
  4131. var len1 = val1.length;
  4132. var shorterArr = len0 > len1 ? val1 : val0;
  4133. var shorterLen = Math.min(len0, len1);
  4134. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  4135. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  4136. shorterArr.push({
  4137. offset: last.offset,
  4138. color: last.color.slice()
  4139. });
  4140. }
  4141. }
  4142. function fillArray(val0, val1, arrDim) {
  4143. var arr0 = val0;
  4144. var arr1 = val1;
  4145. if (!arr0.push || !arr1.push) {
  4146. return;
  4147. }
  4148. var arr0Len = arr0.length;
  4149. var arr1Len = arr1.length;
  4150. if (arr0Len !== arr1Len) {
  4151. var isPreviousLarger = arr0Len > arr1Len;
  4152. if (isPreviousLarger) {
  4153. arr0.length = arr1Len;
  4154. }
  4155. else {
  4156. for (var i = arr0Len; i < arr1Len; i++) {
  4157. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  4158. }
  4159. }
  4160. }
  4161. var len2 = arr0[0] && arr0[0].length;
  4162. for (var i = 0; i < arr0.length; i++) {
  4163. if (arrDim === 1) {
  4164. if (isNaN(arr0[i])) {
  4165. arr0[i] = arr1[i];
  4166. }
  4167. }
  4168. else {
  4169. for (var j = 0; j < len2; j++) {
  4170. if (isNaN(arr0[i][j])) {
  4171. arr0[i][j] = arr1[i][j];
  4172. }
  4173. }
  4174. }
  4175. }
  4176. }
  4177. function cloneValue(value) {
  4178. if (isArrayLike(value)) {
  4179. var len = value.length;
  4180. if (isArrayLike(value[0])) {
  4181. var ret = [];
  4182. for (var i = 0; i < len; i++) {
  4183. ret.push(arraySlice.call(value[i]));
  4184. }
  4185. return ret;
  4186. }
  4187. return arraySlice.call(value);
  4188. }
  4189. return value;
  4190. }
  4191. function rgba2String(rgba) {
  4192. rgba[0] = Math.floor(rgba[0]) || 0;
  4193. rgba[1] = Math.floor(rgba[1]) || 0;
  4194. rgba[2] = Math.floor(rgba[2]) || 0;
  4195. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  4196. return 'rgba(' + rgba.join(',') + ')';
  4197. }
  4198. function guessArrayDim(value) {
  4199. return isArrayLike(value && value[0]) ? 2 : 1;
  4200. }
  4201. var VALUE_TYPE_NUMBER = 0;
  4202. var VALUE_TYPE_1D_ARRAY = 1;
  4203. var VALUE_TYPE_2D_ARRAY = 2;
  4204. var VALUE_TYPE_COLOR = 3;
  4205. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  4206. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  4207. var VALUE_TYPE_UNKOWN = 6;
  4208. function isGradientValueType(valType) {
  4209. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  4210. }
  4211. function isArrayValueType(valType) {
  4212. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  4213. }
  4214. var tmpRgba = [0, 0, 0, 0];
  4215. var Track = (function () {
  4216. function Track(propName) {
  4217. this.keyframes = [];
  4218. this.discrete = false;
  4219. this._invalid = false;
  4220. this._needsSort = false;
  4221. this._lastFr = 0;
  4222. this._lastFrP = 0;
  4223. this.propName = propName;
  4224. }
  4225. Track.prototype.isFinished = function () {
  4226. return this._finished;
  4227. };
  4228. Track.prototype.setFinished = function () {
  4229. this._finished = true;
  4230. if (this._additiveTrack) {
  4231. this._additiveTrack.setFinished();
  4232. }
  4233. };
  4234. Track.prototype.needsAnimate = function () {
  4235. return this.keyframes.length >= 1;
  4236. };
  4237. Track.prototype.getAdditiveTrack = function () {
  4238. return this._additiveTrack;
  4239. };
  4240. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  4241. this._needsSort = true;
  4242. var keyframes = this.keyframes;
  4243. var len = keyframes.length;
  4244. var discrete = false;
  4245. var valType = VALUE_TYPE_UNKOWN;
  4246. var value = rawValue;
  4247. if (isArrayLike(rawValue)) {
  4248. var arrayDim = guessArrayDim(rawValue);
  4249. valType = arrayDim;
  4250. if (arrayDim === 1 && !isNumber(rawValue[0])
  4251. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  4252. discrete = true;
  4253. }
  4254. }
  4255. else {
  4256. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  4257. valType = VALUE_TYPE_NUMBER;
  4258. }
  4259. else if (isString(rawValue)) {
  4260. if (!isNaN(+rawValue)) {
  4261. valType = VALUE_TYPE_NUMBER;
  4262. }
  4263. else {
  4264. var colorArray = parse(rawValue);
  4265. if (colorArray) {
  4266. value = colorArray;
  4267. valType = VALUE_TYPE_COLOR;
  4268. }
  4269. }
  4270. }
  4271. else if (isGradientObject(rawValue)) {
  4272. var parsedGradient = extend({}, value);
  4273. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  4274. offset: colorStop.offset,
  4275. color: parse(colorStop.color)
  4276. }); });
  4277. if (isLinearGradient(rawValue)) {
  4278. valType = VALUE_TYPE_LINEAR_GRADIENT;
  4279. }
  4280. else if (isRadialGradient(rawValue)) {
  4281. valType = VALUE_TYPE_RADIAL_GRADIENT;
  4282. }
  4283. value = parsedGradient;
  4284. }
  4285. }
  4286. if (len === 0) {
  4287. this.valType = valType;
  4288. }
  4289. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  4290. discrete = true;
  4291. }
  4292. this.discrete = this.discrete || discrete;
  4293. var kf = {
  4294. time: time,
  4295. value: value,
  4296. rawValue: rawValue,
  4297. percent: 0
  4298. };
  4299. if (easing) {
  4300. kf.easing = easing;
  4301. kf.easingFunc = isFunction(easing)
  4302. ? easing
  4303. : easingFuncs[easing] || createCubicEasingFunc(easing);
  4304. }
  4305. keyframes.push(kf);
  4306. return kf;
  4307. };
  4308. Track.prototype.prepare = function (maxTime, additiveTrack) {
  4309. var kfs = this.keyframes;
  4310. if (this._needsSort) {
  4311. kfs.sort(function (a, b) {
  4312. return a.time - b.time;
  4313. });
  4314. }
  4315. var valType = this.valType;
  4316. var kfsLen = kfs.length;
  4317. var lastKf = kfs[kfsLen - 1];
  4318. var isDiscrete = this.discrete;
  4319. var isArr = isArrayValueType(valType);
  4320. var isGradient = isGradientValueType(valType);
  4321. for (var i = 0; i < kfsLen; i++) {
  4322. var kf = kfs[i];
  4323. var value = kf.value;
  4324. var lastValue = lastKf.value;
  4325. kf.percent = kf.time / maxTime;
  4326. if (!isDiscrete) {
  4327. if (isArr && i !== kfsLen - 1) {
  4328. fillArray(value, lastValue, valType);
  4329. }
  4330. else if (isGradient) {
  4331. fillColorStops(value.colorStops, lastValue.colorStops);
  4332. }
  4333. }
  4334. }
  4335. if (!isDiscrete
  4336. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  4337. && additiveTrack
  4338. && this.needsAnimate()
  4339. && additiveTrack.needsAnimate()
  4340. && valType === additiveTrack.valType
  4341. && !additiveTrack._finished) {
  4342. this._additiveTrack = additiveTrack;
  4343. var startValue = kfs[0].value;
  4344. for (var i = 0; i < kfsLen; i++) {
  4345. if (valType === VALUE_TYPE_NUMBER) {
  4346. kfs[i].additiveValue = kfs[i].value - startValue;
  4347. }
  4348. else if (valType === VALUE_TYPE_COLOR) {
  4349. kfs[i].additiveValue =
  4350. add1DArray([], kfs[i].value, startValue, -1);
  4351. }
  4352. else if (isArrayValueType(valType)) {
  4353. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  4354. ? add1DArray([], kfs[i].value, startValue, -1)
  4355. : add2DArray([], kfs[i].value, startValue, -1);
  4356. }
  4357. }
  4358. }
  4359. };
  4360. Track.prototype.step = function (target, percent) {
  4361. if (this._finished) {
  4362. return;
  4363. }
  4364. if (this._additiveTrack && this._additiveTrack._finished) {
  4365. this._additiveTrack = null;
  4366. }
  4367. var isAdditive = this._additiveTrack != null;
  4368. var valueKey = isAdditive ? 'additiveValue' : 'value';
  4369. var valType = this.valType;
  4370. var keyframes = this.keyframes;
  4371. var kfsNum = keyframes.length;
  4372. var propName = this.propName;
  4373. var isValueColor = valType === VALUE_TYPE_COLOR;
  4374. var frameIdx;
  4375. var lastFrame = this._lastFr;
  4376. var mathMin = Math.min;
  4377. var frame;
  4378. var nextFrame;
  4379. if (kfsNum === 1) {
  4380. frame = nextFrame = keyframes[0];
  4381. }
  4382. else {
  4383. if (percent < 0) {
  4384. frameIdx = 0;
  4385. }
  4386. else if (percent < this._lastFrP) {
  4387. var start = mathMin(lastFrame + 1, kfsNum - 1);
  4388. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  4389. if (keyframes[frameIdx].percent <= percent) {
  4390. break;
  4391. }
  4392. }
  4393. frameIdx = mathMin(frameIdx, kfsNum - 2);
  4394. }
  4395. else {
  4396. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  4397. if (keyframes[frameIdx].percent > percent) {
  4398. break;
  4399. }
  4400. }
  4401. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  4402. }
  4403. nextFrame = keyframes[frameIdx + 1];
  4404. frame = keyframes[frameIdx];
  4405. }
  4406. if (!(frame && nextFrame)) {
  4407. return;
  4408. }
  4409. this._lastFr = frameIdx;
  4410. this._lastFrP = percent;
  4411. var interval = (nextFrame.percent - frame.percent);
  4412. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  4413. if (nextFrame.easingFunc) {
  4414. w = nextFrame.easingFunc(w);
  4415. }
  4416. var targetArr = isAdditive ? this._additiveValue
  4417. : (isValueColor ? tmpRgba : target[propName]);
  4418. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  4419. targetArr = this._additiveValue = [];
  4420. }
  4421. if (this.discrete) {
  4422. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  4423. }
  4424. else if (isArrayValueType(valType)) {
  4425. valType === VALUE_TYPE_1D_ARRAY
  4426. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  4427. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4428. }
  4429. else if (isGradientValueType(valType)) {
  4430. var val = frame[valueKey];
  4431. var nextVal_1 = nextFrame[valueKey];
  4432. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4433. target[propName] = {
  4434. type: isLinearGradient_1 ? 'linear' : 'radial',
  4435. x: interpolateNumber(val.x, nextVal_1.x, w),
  4436. y: interpolateNumber(val.y, nextVal_1.y, w),
  4437. colorStops: map(val.colorStops, function (colorStop, idx) {
  4438. var nextColorStop = nextVal_1.colorStops[idx];
  4439. return {
  4440. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4441. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4442. };
  4443. }),
  4444. global: nextVal_1.global
  4445. };
  4446. if (isLinearGradient_1) {
  4447. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4448. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4449. }
  4450. else {
  4451. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4452. }
  4453. }
  4454. else if (isValueColor) {
  4455. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4456. if (!isAdditive) {
  4457. target[propName] = rgba2String(targetArr);
  4458. }
  4459. }
  4460. else {
  4461. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4462. if (isAdditive) {
  4463. this._additiveValue = value;
  4464. }
  4465. else {
  4466. target[propName] = value;
  4467. }
  4468. }
  4469. if (isAdditive) {
  4470. this._addToTarget(target);
  4471. }
  4472. };
  4473. Track.prototype._addToTarget = function (target) {
  4474. var valType = this.valType;
  4475. var propName = this.propName;
  4476. var additiveValue = this._additiveValue;
  4477. if (valType === VALUE_TYPE_NUMBER) {
  4478. target[propName] = target[propName] + additiveValue;
  4479. }
  4480. else if (valType === VALUE_TYPE_COLOR) {
  4481. parse(target[propName], tmpRgba);
  4482. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4483. target[propName] = rgba2String(tmpRgba);
  4484. }
  4485. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4486. add1DArray(target[propName], target[propName], additiveValue, 1);
  4487. }
  4488. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4489. add2DArray(target[propName], target[propName], additiveValue, 1);
  4490. }
  4491. };
  4492. return Track;
  4493. }());
  4494. var Animator = (function () {
  4495. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4496. this._tracks = {};
  4497. this._trackKeys = [];
  4498. this._maxTime = 0;
  4499. this._started = 0;
  4500. this._clip = null;
  4501. this._target = target;
  4502. this._loop = loop;
  4503. if (loop && additiveTo) {
  4504. logError('Can\' use additive animation on looped animation.');
  4505. return;
  4506. }
  4507. this._additiveAnimators = additiveTo;
  4508. this._allowDiscrete = allowDiscreteAnimation;
  4509. }
  4510. Animator.prototype.getMaxTime = function () {
  4511. return this._maxTime;
  4512. };
  4513. Animator.prototype.getDelay = function () {
  4514. return this._delay;
  4515. };
  4516. Animator.prototype.getLoop = function () {
  4517. return this._loop;
  4518. };
  4519. Animator.prototype.getTarget = function () {
  4520. return this._target;
  4521. };
  4522. Animator.prototype.changeTarget = function (target) {
  4523. this._target = target;
  4524. };
  4525. Animator.prototype.when = function (time, props, easing) {
  4526. return this.whenWithKeys(time, props, keys(props), easing);
  4527. };
  4528. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4529. var tracks = this._tracks;
  4530. for (var i = 0; i < propNames.length; i++) {
  4531. var propName = propNames[i];
  4532. var track = tracks[propName];
  4533. if (!track) {
  4534. track = tracks[propName] = new Track(propName);
  4535. var initialValue = void 0;
  4536. var additiveTrack = this._getAdditiveTrack(propName);
  4537. if (additiveTrack) {
  4538. var addtiveTrackKfs = additiveTrack.keyframes;
  4539. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4540. initialValue = lastFinalKf && lastFinalKf.value;
  4541. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4542. initialValue = rgba2String(initialValue);
  4543. }
  4544. }
  4545. else {
  4546. initialValue = this._target[propName];
  4547. }
  4548. if (initialValue == null) {
  4549. continue;
  4550. }
  4551. if (time > 0) {
  4552. track.addKeyframe(0, cloneValue(initialValue), easing);
  4553. }
  4554. this._trackKeys.push(propName);
  4555. }
  4556. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4557. }
  4558. this._maxTime = Math.max(this._maxTime, time);
  4559. return this;
  4560. };
  4561. Animator.prototype.pause = function () {
  4562. this._clip.pause();
  4563. this._paused = true;
  4564. };
  4565. Animator.prototype.resume = function () {
  4566. this._clip.resume();
  4567. this._paused = false;
  4568. };
  4569. Animator.prototype.isPaused = function () {
  4570. return !!this._paused;
  4571. };
  4572. Animator.prototype.duration = function (duration) {
  4573. this._maxTime = duration;
  4574. this._force = true;
  4575. return this;
  4576. };
  4577. Animator.prototype._doneCallback = function () {
  4578. this._setTracksFinished();
  4579. this._clip = null;
  4580. var doneList = this._doneCbs;
  4581. if (doneList) {
  4582. var len = doneList.length;
  4583. for (var i = 0; i < len; i++) {
  4584. doneList[i].call(this);
  4585. }
  4586. }
  4587. };
  4588. Animator.prototype._abortedCallback = function () {
  4589. this._setTracksFinished();
  4590. var animation = this.animation;
  4591. var abortedList = this._abortedCbs;
  4592. if (animation) {
  4593. animation.removeClip(this._clip);
  4594. }
  4595. this._clip = null;
  4596. if (abortedList) {
  4597. for (var i = 0; i < abortedList.length; i++) {
  4598. abortedList[i].call(this);
  4599. }
  4600. }
  4601. };
  4602. Animator.prototype._setTracksFinished = function () {
  4603. var tracks = this._tracks;
  4604. var tracksKeys = this._trackKeys;
  4605. for (var i = 0; i < tracksKeys.length; i++) {
  4606. tracks[tracksKeys[i]].setFinished();
  4607. }
  4608. };
  4609. Animator.prototype._getAdditiveTrack = function (trackName) {
  4610. var additiveTrack;
  4611. var additiveAnimators = this._additiveAnimators;
  4612. if (additiveAnimators) {
  4613. for (var i = 0; i < additiveAnimators.length; i++) {
  4614. var track = additiveAnimators[i].getTrack(trackName);
  4615. if (track) {
  4616. additiveTrack = track;
  4617. }
  4618. }
  4619. }
  4620. return additiveTrack;
  4621. };
  4622. Animator.prototype.start = function (easing) {
  4623. if (this._started > 0) {
  4624. return;
  4625. }
  4626. this._started = 1;
  4627. var self = this;
  4628. var tracks = [];
  4629. var maxTime = this._maxTime || 0;
  4630. for (var i = 0; i < this._trackKeys.length; i++) {
  4631. var propName = this._trackKeys[i];
  4632. var track = this._tracks[propName];
  4633. var additiveTrack = this._getAdditiveTrack(propName);
  4634. var kfs = track.keyframes;
  4635. var kfsNum = kfs.length;
  4636. track.prepare(maxTime, additiveTrack);
  4637. if (track.needsAnimate()) {
  4638. if (!this._allowDiscrete && track.discrete) {
  4639. var lastKf = kfs[kfsNum - 1];
  4640. if (lastKf) {
  4641. self._target[track.propName] = lastKf.rawValue;
  4642. }
  4643. track.setFinished();
  4644. }
  4645. else {
  4646. tracks.push(track);
  4647. }
  4648. }
  4649. }
  4650. if (tracks.length || this._force) {
  4651. var clip = new Clip({
  4652. life: maxTime,
  4653. loop: this._loop,
  4654. delay: this._delay || 0,
  4655. onframe: function (percent) {
  4656. self._started = 2;
  4657. var additiveAnimators = self._additiveAnimators;
  4658. if (additiveAnimators) {
  4659. var stillHasAdditiveAnimator = false;
  4660. for (var i = 0; i < additiveAnimators.length; i++) {
  4661. if (additiveAnimators[i]._clip) {
  4662. stillHasAdditiveAnimator = true;
  4663. break;
  4664. }
  4665. }
  4666. if (!stillHasAdditiveAnimator) {
  4667. self._additiveAnimators = null;
  4668. }
  4669. }
  4670. for (var i = 0; i < tracks.length; i++) {
  4671. tracks[i].step(self._target, percent);
  4672. }
  4673. var onframeList = self._onframeCbs;
  4674. if (onframeList) {
  4675. for (var i = 0; i < onframeList.length; i++) {
  4676. onframeList[i](self._target, percent);
  4677. }
  4678. }
  4679. },
  4680. ondestroy: function () {
  4681. self._doneCallback();
  4682. }
  4683. });
  4684. this._clip = clip;
  4685. if (this.animation) {
  4686. this.animation.addClip(clip);
  4687. }
  4688. if (easing) {
  4689. clip.setEasing(easing);
  4690. }
  4691. }
  4692. else {
  4693. this._doneCallback();
  4694. }
  4695. return this;
  4696. };
  4697. Animator.prototype.stop = function (forwardToLast) {
  4698. if (!this._clip) {
  4699. return;
  4700. }
  4701. var clip = this._clip;
  4702. if (forwardToLast) {
  4703. clip.onframe(1);
  4704. }
  4705. this._abortedCallback();
  4706. };
  4707. Animator.prototype.delay = function (time) {
  4708. this._delay = time;
  4709. return this;
  4710. };
  4711. Animator.prototype.during = function (cb) {
  4712. if (cb) {
  4713. if (!this._onframeCbs) {
  4714. this._onframeCbs = [];
  4715. }
  4716. this._onframeCbs.push(cb);
  4717. }
  4718. return this;
  4719. };
  4720. Animator.prototype.done = function (cb) {
  4721. if (cb) {
  4722. if (!this._doneCbs) {
  4723. this._doneCbs = [];
  4724. }
  4725. this._doneCbs.push(cb);
  4726. }
  4727. return this;
  4728. };
  4729. Animator.prototype.aborted = function (cb) {
  4730. if (cb) {
  4731. if (!this._abortedCbs) {
  4732. this._abortedCbs = [];
  4733. }
  4734. this._abortedCbs.push(cb);
  4735. }
  4736. return this;
  4737. };
  4738. Animator.prototype.getClip = function () {
  4739. return this._clip;
  4740. };
  4741. Animator.prototype.getTrack = function (propName) {
  4742. return this._tracks[propName];
  4743. };
  4744. Animator.prototype.getTracks = function () {
  4745. var _this = this;
  4746. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4747. };
  4748. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4749. if (!propNames.length || !this._clip) {
  4750. return true;
  4751. }
  4752. var tracks = this._tracks;
  4753. var tracksKeys = this._trackKeys;
  4754. for (var i = 0; i < propNames.length; i++) {
  4755. var track = tracks[propNames[i]];
  4756. if (track && !track.isFinished()) {
  4757. if (forwardToLast) {
  4758. track.step(this._target, 1);
  4759. }
  4760. else if (this._started === 1) {
  4761. track.step(this._target, 0);
  4762. }
  4763. track.setFinished();
  4764. }
  4765. }
  4766. var allAborted = true;
  4767. for (var i = 0; i < tracksKeys.length; i++) {
  4768. if (!tracks[tracksKeys[i]].isFinished()) {
  4769. allAborted = false;
  4770. break;
  4771. }
  4772. }
  4773. if (allAborted) {
  4774. this._abortedCallback();
  4775. }
  4776. return allAborted;
  4777. };
  4778. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4779. if (!target) {
  4780. return;
  4781. }
  4782. trackKeys = trackKeys || this._trackKeys;
  4783. for (var i = 0; i < trackKeys.length; i++) {
  4784. var propName = trackKeys[i];
  4785. var track = this._tracks[propName];
  4786. if (!track || track.isFinished()) {
  4787. continue;
  4788. }
  4789. var kfs = track.keyframes;
  4790. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4791. if (kf) {
  4792. target[propName] = cloneValue(kf.rawValue);
  4793. }
  4794. }
  4795. };
  4796. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4797. trackKeys = trackKeys || keys(finalProps);
  4798. for (var i = 0; i < trackKeys.length; i++) {
  4799. var propName = trackKeys[i];
  4800. var track = this._tracks[propName];
  4801. if (!track) {
  4802. continue;
  4803. }
  4804. var kfs = track.keyframes;
  4805. if (kfs.length > 1) {
  4806. var lastKf = kfs.pop();
  4807. track.addKeyframe(lastKf.time, finalProps[propName]);
  4808. track.prepare(this._maxTime, track.getAdditiveTrack());
  4809. }
  4810. }
  4811. };
  4812. return Animator;
  4813. }());
  4814. function getTime() {
  4815. return new Date().getTime();
  4816. }
  4817. var Animation = (function (_super) {
  4818. __extends(Animation, _super);
  4819. function Animation(opts) {
  4820. var _this = _super.call(this) || this;
  4821. _this._running = false;
  4822. _this._time = 0;
  4823. _this._pausedTime = 0;
  4824. _this._pauseStart = 0;
  4825. _this._paused = false;
  4826. opts = opts || {};
  4827. _this.stage = opts.stage || {};
  4828. return _this;
  4829. }
  4830. Animation.prototype.addClip = function (clip) {
  4831. if (clip.animation) {
  4832. this.removeClip(clip);
  4833. }
  4834. if (!this._head) {
  4835. this._head = this._tail = clip;
  4836. }
  4837. else {
  4838. this._tail.next = clip;
  4839. clip.prev = this._tail;
  4840. clip.next = null;
  4841. this._tail = clip;
  4842. }
  4843. clip.animation = this;
  4844. };
  4845. Animation.prototype.addAnimator = function (animator) {
  4846. animator.animation = this;
  4847. var clip = animator.getClip();
  4848. if (clip) {
  4849. this.addClip(clip);
  4850. }
  4851. };
  4852. Animation.prototype.removeClip = function (clip) {
  4853. if (!clip.animation) {
  4854. return;
  4855. }
  4856. var prev = clip.prev;
  4857. var next = clip.next;
  4858. if (prev) {
  4859. prev.next = next;
  4860. }
  4861. else {
  4862. this._head = next;
  4863. }
  4864. if (next) {
  4865. next.prev = prev;
  4866. }
  4867. else {
  4868. this._tail = prev;
  4869. }
  4870. clip.next = clip.prev = clip.animation = null;
  4871. };
  4872. Animation.prototype.removeAnimator = function (animator) {
  4873. var clip = animator.getClip();
  4874. if (clip) {
  4875. this.removeClip(clip);
  4876. }
  4877. animator.animation = null;
  4878. };
  4879. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  4880. var time = getTime() - this._pausedTime;
  4881. var delta = time - this._time;
  4882. var clip = this._head;
  4883. while (clip) {
  4884. var nextClip = clip.next;
  4885. var finished = clip.step(time, delta);
  4886. if (finished) {
  4887. clip.ondestroy();
  4888. this.removeClip(clip);
  4889. clip = nextClip;
  4890. }
  4891. else {
  4892. clip = nextClip;
  4893. }
  4894. }
  4895. this._time = time;
  4896. if (!notTriggerFrameAndStageUpdate) {
  4897. this.trigger('frame', delta);
  4898. this.stage.update && this.stage.update();
  4899. }
  4900. };
  4901. Animation.prototype._startLoop = function () {
  4902. var self = this;
  4903. this._running = true;
  4904. function step() {
  4905. if (self._running) {
  4906. requestAnimationFrame$1(step);
  4907. !self._paused && self.update();
  4908. }
  4909. }
  4910. requestAnimationFrame$1(step);
  4911. };
  4912. Animation.prototype.start = function () {
  4913. if (this._running) {
  4914. return;
  4915. }
  4916. this._time = getTime();
  4917. this._pausedTime = 0;
  4918. this._startLoop();
  4919. };
  4920. Animation.prototype.stop = function () {
  4921. this._running = false;
  4922. };
  4923. Animation.prototype.pause = function () {
  4924. if (!this._paused) {
  4925. this._pauseStart = getTime();
  4926. this._paused = true;
  4927. }
  4928. };
  4929. Animation.prototype.resume = function () {
  4930. if (this._paused) {
  4931. this._pausedTime += getTime() - this._pauseStart;
  4932. this._paused = false;
  4933. }
  4934. };
  4935. Animation.prototype.clear = function () {
  4936. var clip = this._head;
  4937. while (clip) {
  4938. var nextClip = clip.next;
  4939. clip.prev = clip.next = clip.animation = null;
  4940. clip = nextClip;
  4941. }
  4942. this._head = this._tail = null;
  4943. };
  4944. Animation.prototype.isFinished = function () {
  4945. return this._head == null;
  4946. };
  4947. Animation.prototype.animate = function (target, options) {
  4948. options = options || {};
  4949. this.start();
  4950. var animator = new Animator(target, options.loop);
  4951. this.addAnimator(animator);
  4952. return animator;
  4953. };
  4954. return Animation;
  4955. }(Eventful));
  4956. var TOUCH_CLICK_DELAY = 300;
  4957. var globalEventSupported = env.domSupported;
  4958. var localNativeListenerNames = (function () {
  4959. var mouseHandlerNames = [
  4960. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  4961. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  4962. ];
  4963. var touchHandlerNames = [
  4964. 'touchstart', 'touchend', 'touchmove'
  4965. ];
  4966. var pointerEventNameMap = {
  4967. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  4968. };
  4969. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  4970. var nm = name.replace('mouse', 'pointer');
  4971. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  4972. });
  4973. return {
  4974. mouse: mouseHandlerNames,
  4975. touch: touchHandlerNames,
  4976. pointer: pointerHandlerNames
  4977. };
  4978. })();
  4979. var globalNativeListenerNames = {
  4980. mouse: ['mousemove', 'mouseup'],
  4981. pointer: ['pointermove', 'pointerup']
  4982. };
  4983. var wheelEventSupported = false;
  4984. function isPointerFromTouch(event) {
  4985. var pointerType = event.pointerType;
  4986. return pointerType === 'pen' || pointerType === 'touch';
  4987. }
  4988. function setTouchTimer(scope) {
  4989. scope.touching = true;
  4990. if (scope.touchTimer != null) {
  4991. clearTimeout(scope.touchTimer);
  4992. scope.touchTimer = null;
  4993. }
  4994. scope.touchTimer = setTimeout(function () {
  4995. scope.touching = false;
  4996. scope.touchTimer = null;
  4997. }, 700);
  4998. }
  4999. function markTouch(event) {
  5000. event && (event.zrByTouch = true);
  5001. }
  5002. function normalizeGlobalEvent(instance, event) {
  5003. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5004. }
  5005. function isLocalEl(instance, el) {
  5006. var elTmp = el;
  5007. var isLocal = false;
  5008. while (elTmp && elTmp.nodeType !== 9
  5009. && !(isLocal = elTmp.domBelongToZr
  5010. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5011. elTmp = elTmp.parentNode;
  5012. }
  5013. return isLocal;
  5014. }
  5015. var FakeGlobalEvent = (function () {
  5016. function FakeGlobalEvent(instance, event) {
  5017. this.stopPropagation = noop;
  5018. this.stopImmediatePropagation = noop;
  5019. this.preventDefault = noop;
  5020. this.type = event.type;
  5021. this.target = this.currentTarget = instance.dom;
  5022. this.pointerType = event.pointerType;
  5023. this.clientX = event.clientX;
  5024. this.clientY = event.clientY;
  5025. }
  5026. return FakeGlobalEvent;
  5027. }());
  5028. var localDOMHandlers = {
  5029. mousedown: function (event) {
  5030. event = normalizeEvent(this.dom, event);
  5031. this.__mayPointerCapture = [event.zrX, event.zrY];
  5032. this.trigger('mousedown', event);
  5033. },
  5034. mousemove: function (event) {
  5035. event = normalizeEvent(this.dom, event);
  5036. var downPoint = this.__mayPointerCapture;
  5037. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5038. this.__togglePointerCapture(true);
  5039. }
  5040. this.trigger('mousemove', event);
  5041. },
  5042. mouseup: function (event) {
  5043. event = normalizeEvent(this.dom, event);
  5044. this.__togglePointerCapture(false);
  5045. this.trigger('mouseup', event);
  5046. },
  5047. mouseout: function (event) {
  5048. event = normalizeEvent(this.dom, event);
  5049. var element = event.toElement || event.relatedTarget;
  5050. if (!isLocalEl(this, element)) {
  5051. if (this.__pointerCapturing) {
  5052. event.zrEventControl = 'no_globalout';
  5053. }
  5054. this.trigger('mouseout', event);
  5055. }
  5056. },
  5057. wheel: function (event) {
  5058. wheelEventSupported = true;
  5059. event = normalizeEvent(this.dom, event);
  5060. this.trigger('mousewheel', event);
  5061. },
  5062. mousewheel: function (event) {
  5063. if (wheelEventSupported) {
  5064. return;
  5065. }
  5066. event = normalizeEvent(this.dom, event);
  5067. this.trigger('mousewheel', event);
  5068. },
  5069. touchstart: function (event) {
  5070. event = normalizeEvent(this.dom, event);
  5071. markTouch(event);
  5072. this.__lastTouchMoment = new Date();
  5073. this.handler.processGesture(event, 'start');
  5074. localDOMHandlers.mousemove.call(this, event);
  5075. localDOMHandlers.mousedown.call(this, event);
  5076. },
  5077. touchmove: function (event) {
  5078. event = normalizeEvent(this.dom, event);
  5079. markTouch(event);
  5080. this.handler.processGesture(event, 'change');
  5081. localDOMHandlers.mousemove.call(this, event);
  5082. },
  5083. touchend: function (event) {
  5084. event = normalizeEvent(this.dom, event);
  5085. markTouch(event);
  5086. this.handler.processGesture(event, 'end');
  5087. localDOMHandlers.mouseup.call(this, event);
  5088. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5089. localDOMHandlers.click.call(this, event);
  5090. }
  5091. },
  5092. pointerdown: function (event) {
  5093. localDOMHandlers.mousedown.call(this, event);
  5094. },
  5095. pointermove: function (event) {
  5096. if (!isPointerFromTouch(event)) {
  5097. localDOMHandlers.mousemove.call(this, event);
  5098. }
  5099. },
  5100. pointerup: function (event) {
  5101. localDOMHandlers.mouseup.call(this, event);
  5102. },
  5103. pointerout: function (event) {
  5104. if (!isPointerFromTouch(event)) {
  5105. localDOMHandlers.mouseout.call(this, event);
  5106. }
  5107. }
  5108. };
  5109. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5110. localDOMHandlers[name] = function (event) {
  5111. event = normalizeEvent(this.dom, event);
  5112. this.trigger(name, event);
  5113. };
  5114. });
  5115. var globalDOMHandlers = {
  5116. pointermove: function (event) {
  5117. if (!isPointerFromTouch(event)) {
  5118. globalDOMHandlers.mousemove.call(this, event);
  5119. }
  5120. },
  5121. pointerup: function (event) {
  5122. globalDOMHandlers.mouseup.call(this, event);
  5123. },
  5124. mousemove: function (event) {
  5125. this.trigger('mousemove', event);
  5126. },
  5127. mouseup: function (event) {
  5128. var pointerCaptureReleasing = this.__pointerCapturing;
  5129. this.__togglePointerCapture(false);
  5130. this.trigger('mouseup', event);
  5131. if (pointerCaptureReleasing) {
  5132. event.zrEventControl = 'only_globalout';
  5133. this.trigger('mouseout', event);
  5134. }
  5135. }
  5136. };
  5137. function mountLocalDOMEventListeners(instance, scope) {
  5138. var domHandlers = scope.domHandlers;
  5139. if (env.pointerEventsSupported) {
  5140. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5141. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5142. domHandlers[nativeEventName].call(instance, event);
  5143. });
  5144. });
  5145. }
  5146. else {
  5147. if (env.touchEventsSupported) {
  5148. each(localNativeListenerNames.touch, function (nativeEventName) {
  5149. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5150. domHandlers[nativeEventName].call(instance, event);
  5151. setTouchTimer(scope);
  5152. });
  5153. });
  5154. }
  5155. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5156. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5157. event = getNativeEvent(event);
  5158. if (!scope.touching) {
  5159. domHandlers[nativeEventName].call(instance, event);
  5160. }
  5161. });
  5162. });
  5163. }
  5164. }
  5165. function mountGlobalDOMEventListeners(instance, scope) {
  5166. if (env.pointerEventsSupported) {
  5167. each(globalNativeListenerNames.pointer, mount);
  5168. }
  5169. else if (!env.touchEventsSupported) {
  5170. each(globalNativeListenerNames.mouse, mount);
  5171. }
  5172. function mount(nativeEventName) {
  5173. function nativeEventListener(event) {
  5174. event = getNativeEvent(event);
  5175. if (!isLocalEl(instance, event.target)) {
  5176. event = normalizeGlobalEvent(instance, event);
  5177. scope.domHandlers[nativeEventName].call(instance, event);
  5178. }
  5179. }
  5180. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  5181. }
  5182. }
  5183. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  5184. scope.mounted[nativeEventName] = listener;
  5185. scope.listenerOpts[nativeEventName] = opt;
  5186. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  5187. }
  5188. function unmountDOMEventListeners(scope) {
  5189. var mounted = scope.mounted;
  5190. for (var nativeEventName in mounted) {
  5191. if (mounted.hasOwnProperty(nativeEventName)) {
  5192. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  5193. }
  5194. }
  5195. scope.mounted = {};
  5196. }
  5197. var DOMHandlerScope = (function () {
  5198. function DOMHandlerScope(domTarget, domHandlers) {
  5199. this.mounted = {};
  5200. this.listenerOpts = {};
  5201. this.touching = false;
  5202. this.domTarget = domTarget;
  5203. this.domHandlers = domHandlers;
  5204. }
  5205. return DOMHandlerScope;
  5206. }());
  5207. var HandlerDomProxy = (function (_super) {
  5208. __extends(HandlerDomProxy, _super);
  5209. function HandlerDomProxy(dom, painterRoot) {
  5210. var _this = _super.call(this) || this;
  5211. _this.__pointerCapturing = false;
  5212. _this.dom = dom;
  5213. _this.painterRoot = painterRoot;
  5214. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  5215. if (globalEventSupported) {
  5216. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  5217. }
  5218. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  5219. return _this;
  5220. }
  5221. HandlerDomProxy.prototype.dispose = function () {
  5222. unmountDOMEventListeners(this._localHandlerScope);
  5223. if (globalEventSupported) {
  5224. unmountDOMEventListeners(this._globalHandlerScope);
  5225. }
  5226. };
  5227. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  5228. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  5229. };
  5230. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  5231. this.__mayPointerCapture = null;
  5232. if (globalEventSupported
  5233. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  5234. this.__pointerCapturing = isPointerCapturing;
  5235. var globalHandlerScope = this._globalHandlerScope;
  5236. isPointerCapturing
  5237. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  5238. : unmountDOMEventListeners(globalHandlerScope);
  5239. }
  5240. };
  5241. return HandlerDomProxy;
  5242. }(Eventful));
  5243. var dpr = 1;
  5244. if (env.hasGlobalWindow) {
  5245. dpr = Math.max(window.devicePixelRatio
  5246. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  5247. || 1, 1);
  5248. }
  5249. var devicePixelRatio = dpr;
  5250. var DARK_MODE_THRESHOLD = 0.4;
  5251. var DARK_LABEL_COLOR = '#333';
  5252. var LIGHT_LABEL_COLOR = '#ccc';
  5253. var LIGHTER_LABEL_COLOR = '#eee';
  5254. var mIdentity = identity;
  5255. var EPSILON$1 = 5e-5;
  5256. function isNotAroundZero$1(val) {
  5257. return val > EPSILON$1 || val < -EPSILON$1;
  5258. }
  5259. var scaleTmp = [];
  5260. var tmpTransform = [];
  5261. var originTransform = create$1();
  5262. var abs = Math.abs;
  5263. var Transformable = (function () {
  5264. function Transformable() {
  5265. }
  5266. Transformable.prototype.getLocalTransform = function (m) {
  5267. return Transformable.getLocalTransform(this, m);
  5268. };
  5269. Transformable.prototype.setPosition = function (arr) {
  5270. this.x = arr[0];
  5271. this.y = arr[1];
  5272. };
  5273. Transformable.prototype.setScale = function (arr) {
  5274. this.scaleX = arr[0];
  5275. this.scaleY = arr[1];
  5276. };
  5277. Transformable.prototype.setSkew = function (arr) {
  5278. this.skewX = arr[0];
  5279. this.skewY = arr[1];
  5280. };
  5281. Transformable.prototype.setOrigin = function (arr) {
  5282. this.originX = arr[0];
  5283. this.originY = arr[1];
  5284. };
  5285. Transformable.prototype.needLocalTransform = function () {
  5286. return isNotAroundZero$1(this.rotation)
  5287. || isNotAroundZero$1(this.x)
  5288. || isNotAroundZero$1(this.y)
  5289. || isNotAroundZero$1(this.scaleX - 1)
  5290. || isNotAroundZero$1(this.scaleY - 1)
  5291. || isNotAroundZero$1(this.skewX)
  5292. || isNotAroundZero$1(this.skewY);
  5293. };
  5294. Transformable.prototype.updateTransform = function () {
  5295. var parentTransform = this.parent && this.parent.transform;
  5296. var needLocalTransform = this.needLocalTransform();
  5297. var m = this.transform;
  5298. if (!(needLocalTransform || parentTransform)) {
  5299. if (m) {
  5300. mIdentity(m);
  5301. this.invTransform = null;
  5302. }
  5303. return;
  5304. }
  5305. m = m || create$1();
  5306. if (needLocalTransform) {
  5307. this.getLocalTransform(m);
  5308. }
  5309. else {
  5310. mIdentity(m);
  5311. }
  5312. if (parentTransform) {
  5313. if (needLocalTransform) {
  5314. mul$1(m, parentTransform, m);
  5315. }
  5316. else {
  5317. copy$1(m, parentTransform);
  5318. }
  5319. }
  5320. this.transform = m;
  5321. this._resolveGlobalScaleRatio(m);
  5322. };
  5323. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5324. var globalScaleRatio = this.globalScaleRatio;
  5325. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5326. this.getGlobalScale(scaleTmp);
  5327. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5328. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5329. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5330. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5331. m[0] *= sx;
  5332. m[1] *= sx;
  5333. m[2] *= sy;
  5334. m[3] *= sy;
  5335. }
  5336. this.invTransform = this.invTransform || create$1();
  5337. invert(this.invTransform, m);
  5338. };
  5339. Transformable.prototype.getComputedTransform = function () {
  5340. var transformNode = this;
  5341. var ancestors = [];
  5342. while (transformNode) {
  5343. ancestors.push(transformNode);
  5344. transformNode = transformNode.parent;
  5345. }
  5346. while (transformNode = ancestors.pop()) {
  5347. transformNode.updateTransform();
  5348. }
  5349. return this.transform;
  5350. };
  5351. Transformable.prototype.setLocalTransform = function (m) {
  5352. if (!m) {
  5353. return;
  5354. }
  5355. var sx = m[0] * m[0] + m[1] * m[1];
  5356. var sy = m[2] * m[2] + m[3] * m[3];
  5357. var rotation = Math.atan2(m[1], m[0]);
  5358. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5359. sy = Math.sqrt(sy) * Math.cos(shearX);
  5360. sx = Math.sqrt(sx);
  5361. this.skewX = shearX;
  5362. this.skewY = 0;
  5363. this.rotation = -rotation;
  5364. this.x = +m[4];
  5365. this.y = +m[5];
  5366. this.scaleX = sx;
  5367. this.scaleY = sy;
  5368. this.originX = 0;
  5369. this.originY = 0;
  5370. };
  5371. Transformable.prototype.decomposeTransform = function () {
  5372. if (!this.transform) {
  5373. return;
  5374. }
  5375. var parent = this.parent;
  5376. var m = this.transform;
  5377. if (parent && parent.transform) {
  5378. parent.invTransform = parent.invTransform || create$1();
  5379. mul$1(tmpTransform, parent.invTransform, m);
  5380. m = tmpTransform;
  5381. }
  5382. var ox = this.originX;
  5383. var oy = this.originY;
  5384. if (ox || oy) {
  5385. originTransform[4] = ox;
  5386. originTransform[5] = oy;
  5387. mul$1(tmpTransform, m, originTransform);
  5388. tmpTransform[4] -= ox;
  5389. tmpTransform[5] -= oy;
  5390. m = tmpTransform;
  5391. }
  5392. this.setLocalTransform(m);
  5393. };
  5394. Transformable.prototype.getGlobalScale = function (out) {
  5395. var m = this.transform;
  5396. out = out || [];
  5397. if (!m) {
  5398. out[0] = 1;
  5399. out[1] = 1;
  5400. return out;
  5401. }
  5402. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5403. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5404. if (m[0] < 0) {
  5405. out[0] = -out[0];
  5406. }
  5407. if (m[3] < 0) {
  5408. out[1] = -out[1];
  5409. }
  5410. return out;
  5411. };
  5412. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5413. var v2 = [x, y];
  5414. var invTransform = this.invTransform;
  5415. if (invTransform) {
  5416. applyTransform(v2, v2, invTransform);
  5417. }
  5418. return v2;
  5419. };
  5420. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5421. var v2 = [x, y];
  5422. var transform = this.transform;
  5423. if (transform) {
  5424. applyTransform(v2, v2, transform);
  5425. }
  5426. return v2;
  5427. };
  5428. Transformable.prototype.getLineScale = function () {
  5429. var m = this.transform;
  5430. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5431. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5432. : 1;
  5433. };
  5434. Transformable.prototype.copyTransform = function (source) {
  5435. copyTransform(this, source);
  5436. };
  5437. Transformable.getLocalTransform = function (target, m) {
  5438. m = m || [];
  5439. var ox = target.originX || 0;
  5440. var oy = target.originY || 0;
  5441. var sx = target.scaleX;
  5442. var sy = target.scaleY;
  5443. var ax = target.anchorX;
  5444. var ay = target.anchorY;
  5445. var rotation = target.rotation || 0;
  5446. var x = target.x;
  5447. var y = target.y;
  5448. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5449. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5450. if (ox || oy || ax || ay) {
  5451. var dx = ox + ax;
  5452. var dy = oy + ay;
  5453. m[4] = -dx * sx - skewX * dy * sy;
  5454. m[5] = -dy * sy - skewY * dx * sx;
  5455. }
  5456. else {
  5457. m[4] = m[5] = 0;
  5458. }
  5459. m[0] = sx;
  5460. m[3] = sy;
  5461. m[1] = skewY * sx;
  5462. m[2] = skewX * sy;
  5463. rotation && rotate(m, m, rotation);
  5464. m[4] += ox + x;
  5465. m[5] += oy + y;
  5466. return m;
  5467. };
  5468. Transformable.initDefaultProps = (function () {
  5469. var proto = Transformable.prototype;
  5470. proto.scaleX =
  5471. proto.scaleY =
  5472. proto.globalScaleRatio = 1;
  5473. proto.x =
  5474. proto.y =
  5475. proto.originX =
  5476. proto.originY =
  5477. proto.skewX =
  5478. proto.skewY =
  5479. proto.rotation =
  5480. proto.anchorX =
  5481. proto.anchorY = 0;
  5482. })();
  5483. return Transformable;
  5484. }());
  5485. var TRANSFORMABLE_PROPS = [
  5486. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5487. ];
  5488. function copyTransform(target, source) {
  5489. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5490. var propName = TRANSFORMABLE_PROPS[i];
  5491. target[propName] = source[propName];
  5492. }
  5493. }
  5494. var textWidthCache = {};
  5495. function getWidth(text, font) {
  5496. font = font || DEFAULT_FONT;
  5497. var cacheOfFont = textWidthCache[font];
  5498. if (!cacheOfFont) {
  5499. cacheOfFont = textWidthCache[font] = new LRU(500);
  5500. }
  5501. var width = cacheOfFont.get(text);
  5502. if (width == null) {
  5503. width = platformApi.measureText(text, font).width;
  5504. cacheOfFont.put(text, width);
  5505. }
  5506. return width;
  5507. }
  5508. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5509. var width = getWidth(text, font);
  5510. var height = getLineHeight(font);
  5511. var x = adjustTextX(0, width, textAlign);
  5512. var y = adjustTextY(0, height, textBaseline);
  5513. var rect = new BoundingRect(x, y, width, height);
  5514. return rect;
  5515. }
  5516. function getBoundingRect(text, font, textAlign, textBaseline) {
  5517. var textLines = ((text || '') + '').split('\n');
  5518. var len = textLines.length;
  5519. if (len === 1) {
  5520. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5521. }
  5522. else {
  5523. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5524. for (var i = 0; i < textLines.length; i++) {
  5525. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5526. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5527. }
  5528. return uniondRect;
  5529. }
  5530. }
  5531. function adjustTextX(x, width, textAlign) {
  5532. if (textAlign === 'right') {
  5533. x -= width;
  5534. }
  5535. else if (textAlign === 'center') {
  5536. x -= width / 2;
  5537. }
  5538. return x;
  5539. }
  5540. function adjustTextY(y, height, verticalAlign) {
  5541. if (verticalAlign === 'middle') {
  5542. y -= height / 2;
  5543. }
  5544. else if (verticalAlign === 'bottom') {
  5545. y -= height;
  5546. }
  5547. return y;
  5548. }
  5549. function getLineHeight(font) {
  5550. return getWidth('国', font);
  5551. }
  5552. function parsePercent(value, maxValue) {
  5553. if (typeof value === 'string') {
  5554. if (value.lastIndexOf('%') >= 0) {
  5555. return parseFloat(value) / 100 * maxValue;
  5556. }
  5557. return parseFloat(value);
  5558. }
  5559. return value;
  5560. }
  5561. function calculateTextPosition(out, opts, rect) {
  5562. var textPosition = opts.position || 'inside';
  5563. var distance = opts.distance != null ? opts.distance : 5;
  5564. var height = rect.height;
  5565. var width = rect.width;
  5566. var halfHeight = height / 2;
  5567. var x = rect.x;
  5568. var y = rect.y;
  5569. var textAlign = 'left';
  5570. var textVerticalAlign = 'top';
  5571. if (textPosition instanceof Array) {
  5572. x += parsePercent(textPosition[0], rect.width);
  5573. y += parsePercent(textPosition[1], rect.height);
  5574. textAlign = null;
  5575. textVerticalAlign = null;
  5576. }
  5577. else {
  5578. switch (textPosition) {
  5579. case 'left':
  5580. x -= distance;
  5581. y += halfHeight;
  5582. textAlign = 'right';
  5583. textVerticalAlign = 'middle';
  5584. break;
  5585. case 'right':
  5586. x += distance + width;
  5587. y += halfHeight;
  5588. textVerticalAlign = 'middle';
  5589. break;
  5590. case 'top':
  5591. x += width / 2;
  5592. y -= distance;
  5593. textAlign = 'center';
  5594. textVerticalAlign = 'bottom';
  5595. break;
  5596. case 'bottom':
  5597. x += width / 2;
  5598. y += height + distance;
  5599. textAlign = 'center';
  5600. break;
  5601. case 'inside':
  5602. x += width / 2;
  5603. y += halfHeight;
  5604. textAlign = 'center';
  5605. textVerticalAlign = 'middle';
  5606. break;
  5607. case 'insideLeft':
  5608. x += distance;
  5609. y += halfHeight;
  5610. textVerticalAlign = 'middle';
  5611. break;
  5612. case 'insideRight':
  5613. x += width - distance;
  5614. y += halfHeight;
  5615. textAlign = 'right';
  5616. textVerticalAlign = 'middle';
  5617. break;
  5618. case 'insideTop':
  5619. x += width / 2;
  5620. y += distance;
  5621. textAlign = 'center';
  5622. break;
  5623. case 'insideBottom':
  5624. x += width / 2;
  5625. y += height - distance;
  5626. textAlign = 'center';
  5627. textVerticalAlign = 'bottom';
  5628. break;
  5629. case 'insideTopLeft':
  5630. x += distance;
  5631. y += distance;
  5632. break;
  5633. case 'insideTopRight':
  5634. x += width - distance;
  5635. y += distance;
  5636. textAlign = 'right';
  5637. break;
  5638. case 'insideBottomLeft':
  5639. x += distance;
  5640. y += height - distance;
  5641. textVerticalAlign = 'bottom';
  5642. break;
  5643. case 'insideBottomRight':
  5644. x += width - distance;
  5645. y += height - distance;
  5646. textAlign = 'right';
  5647. textVerticalAlign = 'bottom';
  5648. break;
  5649. }
  5650. }
  5651. out = out || {};
  5652. out.x = x;
  5653. out.y = y;
  5654. out.align = textAlign;
  5655. out.verticalAlign = textVerticalAlign;
  5656. return out;
  5657. }
  5658. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5659. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5660. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5661. obj[key] = true;
  5662. return obj;
  5663. }, { ignore: false });
  5664. var tmpTextPosCalcRes = {};
  5665. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5666. var Element = (function () {
  5667. function Element(props) {
  5668. this.id = guid();
  5669. this.animators = [];
  5670. this.currentStates = [];
  5671. this.states = {};
  5672. this._init(props);
  5673. }
  5674. Element.prototype._init = function (props) {
  5675. this.attr(props);
  5676. };
  5677. Element.prototype.drift = function (dx, dy, e) {
  5678. switch (this.draggable) {
  5679. case 'horizontal':
  5680. dy = 0;
  5681. break;
  5682. case 'vertical':
  5683. dx = 0;
  5684. break;
  5685. }
  5686. var m = this.transform;
  5687. if (!m) {
  5688. m = this.transform = [1, 0, 0, 1, 0, 0];
  5689. }
  5690. m[4] += dx;
  5691. m[5] += dy;
  5692. this.decomposeTransform();
  5693. this.markRedraw();
  5694. };
  5695. Element.prototype.beforeUpdate = function () { };
  5696. Element.prototype.afterUpdate = function () { };
  5697. Element.prototype.update = function () {
  5698. this.updateTransform();
  5699. if (this.__dirty) {
  5700. this.updateInnerText();
  5701. }
  5702. };
  5703. Element.prototype.updateInnerText = function (forceUpdate) {
  5704. var textEl = this._textContent;
  5705. if (textEl && (!textEl.ignore || forceUpdate)) {
  5706. if (!this.textConfig) {
  5707. this.textConfig = {};
  5708. }
  5709. var textConfig = this.textConfig;
  5710. var isLocal = textConfig.local;
  5711. var innerTransformable = textEl.innerTransformable;
  5712. var textAlign = void 0;
  5713. var textVerticalAlign = void 0;
  5714. var textStyleChanged = false;
  5715. innerTransformable.parent = isLocal ? this : null;
  5716. var innerOrigin = false;
  5717. innerTransformable.copyTransform(textEl);
  5718. if (textConfig.position != null) {
  5719. var layoutRect = tmpBoundingRect;
  5720. if (textConfig.layoutRect) {
  5721. layoutRect.copy(textConfig.layoutRect);
  5722. }
  5723. else {
  5724. layoutRect.copy(this.getBoundingRect());
  5725. }
  5726. if (!isLocal) {
  5727. layoutRect.applyTransform(this.transform);
  5728. }
  5729. if (this.calculateTextPosition) {
  5730. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5731. }
  5732. else {
  5733. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5734. }
  5735. innerTransformable.x = tmpTextPosCalcRes.x;
  5736. innerTransformable.y = tmpTextPosCalcRes.y;
  5737. textAlign = tmpTextPosCalcRes.align;
  5738. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5739. var textOrigin = textConfig.origin;
  5740. if (textOrigin && textConfig.rotation != null) {
  5741. var relOriginX = void 0;
  5742. var relOriginY = void 0;
  5743. if (textOrigin === 'center') {
  5744. relOriginX = layoutRect.width * 0.5;
  5745. relOriginY = layoutRect.height * 0.5;
  5746. }
  5747. else {
  5748. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5749. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5750. }
  5751. innerOrigin = true;
  5752. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5753. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5754. }
  5755. }
  5756. if (textConfig.rotation != null) {
  5757. innerTransformable.rotation = textConfig.rotation;
  5758. }
  5759. var textOffset = textConfig.offset;
  5760. if (textOffset) {
  5761. innerTransformable.x += textOffset[0];
  5762. innerTransformable.y += textOffset[1];
  5763. if (!innerOrigin) {
  5764. innerTransformable.originX = -textOffset[0];
  5765. innerTransformable.originY = -textOffset[1];
  5766. }
  5767. }
  5768. var isInside = textConfig.inside == null
  5769. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5770. : textConfig.inside;
  5771. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5772. var textFill = void 0;
  5773. var textStroke = void 0;
  5774. var autoStroke = void 0;
  5775. if (isInside && this.canBeInsideText()) {
  5776. textFill = textConfig.insideFill;
  5777. textStroke = textConfig.insideStroke;
  5778. if (textFill == null || textFill === 'auto') {
  5779. textFill = this.getInsideTextFill();
  5780. }
  5781. if (textStroke == null || textStroke === 'auto') {
  5782. textStroke = this.getInsideTextStroke(textFill);
  5783. autoStroke = true;
  5784. }
  5785. }
  5786. else {
  5787. textFill = textConfig.outsideFill;
  5788. textStroke = textConfig.outsideStroke;
  5789. if (textFill == null || textFill === 'auto') {
  5790. textFill = this.getOutsideFill();
  5791. }
  5792. if (textStroke == null || textStroke === 'auto') {
  5793. textStroke = this.getOutsideStroke(textFill);
  5794. autoStroke = true;
  5795. }
  5796. }
  5797. textFill = textFill || '#000';
  5798. if (textFill !== innerTextDefaultStyle.fill
  5799. || textStroke !== innerTextDefaultStyle.stroke
  5800. || autoStroke !== innerTextDefaultStyle.autoStroke
  5801. || textAlign !== innerTextDefaultStyle.align
  5802. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5803. textStyleChanged = true;
  5804. innerTextDefaultStyle.fill = textFill;
  5805. innerTextDefaultStyle.stroke = textStroke;
  5806. innerTextDefaultStyle.autoStroke = autoStroke;
  5807. innerTextDefaultStyle.align = textAlign;
  5808. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5809. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5810. }
  5811. textEl.__dirty |= REDRAW_BIT;
  5812. if (textStyleChanged) {
  5813. textEl.dirtyStyle(true);
  5814. }
  5815. }
  5816. };
  5817. Element.prototype.canBeInsideText = function () {
  5818. return true;
  5819. };
  5820. Element.prototype.getInsideTextFill = function () {
  5821. return '#fff';
  5822. };
  5823. Element.prototype.getInsideTextStroke = function (textFill) {
  5824. return '#000';
  5825. };
  5826. Element.prototype.getOutsideFill = function () {
  5827. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5828. };
  5829. Element.prototype.getOutsideStroke = function (textFill) {
  5830. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5831. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5832. if (!colorArr) {
  5833. colorArr = [255, 255, 255, 1];
  5834. }
  5835. var alpha = colorArr[3];
  5836. var isDark = this.__zr.isDarkMode();
  5837. for (var i = 0; i < 3; i++) {
  5838. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5839. }
  5840. colorArr[3] = 1;
  5841. return stringify(colorArr, 'rgba');
  5842. };
  5843. Element.prototype.traverse = function (cb, context) { };
  5844. Element.prototype.attrKV = function (key, value) {
  5845. if (key === 'textConfig') {
  5846. this.setTextConfig(value);
  5847. }
  5848. else if (key === 'textContent') {
  5849. this.setTextContent(value);
  5850. }
  5851. else if (key === 'clipPath') {
  5852. this.setClipPath(value);
  5853. }
  5854. else if (key === 'extra') {
  5855. this.extra = this.extra || {};
  5856. extend(this.extra, value);
  5857. }
  5858. else {
  5859. this[key] = value;
  5860. }
  5861. };
  5862. Element.prototype.hide = function () {
  5863. this.ignore = true;
  5864. this.markRedraw();
  5865. };
  5866. Element.prototype.show = function () {
  5867. this.ignore = false;
  5868. this.markRedraw();
  5869. };
  5870. Element.prototype.attr = function (keyOrObj, value) {
  5871. if (typeof keyOrObj === 'string') {
  5872. this.attrKV(keyOrObj, value);
  5873. }
  5874. else if (isObject(keyOrObj)) {
  5875. var obj = keyOrObj;
  5876. var keysArr = keys(obj);
  5877. for (var i = 0; i < keysArr.length; i++) {
  5878. var key = keysArr[i];
  5879. this.attrKV(key, keyOrObj[key]);
  5880. }
  5881. }
  5882. this.markRedraw();
  5883. return this;
  5884. };
  5885. Element.prototype.saveCurrentToNormalState = function (toState) {
  5886. this._innerSaveToNormal(toState);
  5887. var normalState = this._normalState;
  5888. for (var i = 0; i < this.animators.length; i++) {
  5889. var animator = this.animators[i];
  5890. var fromStateTransition = animator.__fromStateTransition;
  5891. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  5892. continue;
  5893. }
  5894. var targetName = animator.targetName;
  5895. var target = targetName
  5896. ? normalState[targetName] : normalState;
  5897. animator.saveTo(target);
  5898. }
  5899. };
  5900. Element.prototype._innerSaveToNormal = function (toState) {
  5901. var normalState = this._normalState;
  5902. if (!normalState) {
  5903. normalState = this._normalState = {};
  5904. }
  5905. if (toState.textConfig && !normalState.textConfig) {
  5906. normalState.textConfig = this.textConfig;
  5907. }
  5908. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  5909. };
  5910. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  5911. for (var i = 0; i < primaryKeys.length; i++) {
  5912. var key = primaryKeys[i];
  5913. if (toState[key] != null && !(key in normalState)) {
  5914. normalState[key] = this[key];
  5915. }
  5916. }
  5917. };
  5918. Element.prototype.hasState = function () {
  5919. return this.currentStates.length > 0;
  5920. };
  5921. Element.prototype.getState = function (name) {
  5922. return this.states[name];
  5923. };
  5924. Element.prototype.ensureState = function (name) {
  5925. var states = this.states;
  5926. if (!states[name]) {
  5927. states[name] = {};
  5928. }
  5929. return states[name];
  5930. };
  5931. Element.prototype.clearStates = function (noAnimation) {
  5932. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  5933. };
  5934. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  5935. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  5936. var hasStates = this.hasState();
  5937. if (!hasStates && toNormalState) {
  5938. return;
  5939. }
  5940. var currentStates = this.currentStates;
  5941. var animationCfg = this.stateTransition;
  5942. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  5943. return;
  5944. }
  5945. var state;
  5946. if (this.stateProxy && !toNormalState) {
  5947. state = this.stateProxy(stateName);
  5948. }
  5949. if (!state) {
  5950. state = (this.states && this.states[stateName]);
  5951. }
  5952. if (!state && !toNormalState) {
  5953. logError("State " + stateName + " not exists.");
  5954. return;
  5955. }
  5956. if (!toNormalState) {
  5957. this.saveCurrentToNormalState(state);
  5958. }
  5959. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  5960. if (useHoverLayer) {
  5961. this._toggleHoverLayerFlag(true);
  5962. }
  5963. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  5964. var textContent = this._textContent;
  5965. var textGuide = this._textGuide;
  5966. if (textContent) {
  5967. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5968. }
  5969. if (textGuide) {
  5970. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5971. }
  5972. if (toNormalState) {
  5973. this.currentStates = [];
  5974. this._normalState = {};
  5975. }
  5976. else {
  5977. if (!keepCurrentStates) {
  5978. this.currentStates = [stateName];
  5979. }
  5980. else {
  5981. this.currentStates.push(stateName);
  5982. }
  5983. }
  5984. this._updateAnimationTargets();
  5985. this.markRedraw();
  5986. if (!useHoverLayer && this.__inHover) {
  5987. this._toggleHoverLayerFlag(false);
  5988. this.__dirty &= ~REDRAW_BIT;
  5989. }
  5990. return state;
  5991. };
  5992. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  5993. if (!states.length) {
  5994. this.clearStates();
  5995. }
  5996. else {
  5997. var stateObjects = [];
  5998. var currentStates = this.currentStates;
  5999. var len = states.length;
  6000. var notChange = len === currentStates.length;
  6001. if (notChange) {
  6002. for (var i = 0; i < len; i++) {
  6003. if (states[i] !== currentStates[i]) {
  6004. notChange = false;
  6005. break;
  6006. }
  6007. }
  6008. }
  6009. if (notChange) {
  6010. return;
  6011. }
  6012. for (var i = 0; i < len; i++) {
  6013. var stateName = states[i];
  6014. var stateObj = void 0;
  6015. if (this.stateProxy) {
  6016. stateObj = this.stateProxy(stateName, states);
  6017. }
  6018. if (!stateObj) {
  6019. stateObj = this.states[stateName];
  6020. }
  6021. if (stateObj) {
  6022. stateObjects.push(stateObj);
  6023. }
  6024. }
  6025. var lastStateObj = stateObjects[len - 1];
  6026. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6027. if (useHoverLayer) {
  6028. this._toggleHoverLayerFlag(true);
  6029. }
  6030. var mergedState = this._mergeStates(stateObjects);
  6031. var animationCfg = this.stateTransition;
  6032. this.saveCurrentToNormalState(mergedState);
  6033. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6034. var textContent = this._textContent;
  6035. var textGuide = this._textGuide;
  6036. if (textContent) {
  6037. textContent.useStates(states, noAnimation, useHoverLayer);
  6038. }
  6039. if (textGuide) {
  6040. textGuide.useStates(states, noAnimation, useHoverLayer);
  6041. }
  6042. this._updateAnimationTargets();
  6043. this.currentStates = states.slice();
  6044. this.markRedraw();
  6045. if (!useHoverLayer && this.__inHover) {
  6046. this._toggleHoverLayerFlag(false);
  6047. this.__dirty &= ~REDRAW_BIT;
  6048. }
  6049. }
  6050. };
  6051. Element.prototype.isSilent = function () {
  6052. var isSilent = this.silent;
  6053. var ancestor = this.parent;
  6054. while (!isSilent && ancestor) {
  6055. if (ancestor.silent) {
  6056. isSilent = true;
  6057. break;
  6058. }
  6059. ancestor = ancestor.parent;
  6060. }
  6061. return isSilent;
  6062. };
  6063. Element.prototype._updateAnimationTargets = function () {
  6064. for (var i = 0; i < this.animators.length; i++) {
  6065. var animator = this.animators[i];
  6066. if (animator.targetName) {
  6067. animator.changeTarget(this[animator.targetName]);
  6068. }
  6069. }
  6070. };
  6071. Element.prototype.removeState = function (state) {
  6072. var idx = indexOf(this.currentStates, state);
  6073. if (idx >= 0) {
  6074. var currentStates = this.currentStates.slice();
  6075. currentStates.splice(idx, 1);
  6076. this.useStates(currentStates);
  6077. }
  6078. };
  6079. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6080. var currentStates = this.currentStates.slice();
  6081. var idx = indexOf(currentStates, oldState);
  6082. var newStateExists = indexOf(currentStates, newState) >= 0;
  6083. if (idx >= 0) {
  6084. if (!newStateExists) {
  6085. currentStates[idx] = newState;
  6086. }
  6087. else {
  6088. currentStates.splice(idx, 1);
  6089. }
  6090. }
  6091. else if (forceAdd && !newStateExists) {
  6092. currentStates.push(newState);
  6093. }
  6094. this.useStates(currentStates);
  6095. };
  6096. Element.prototype.toggleState = function (state, enable) {
  6097. if (enable) {
  6098. this.useState(state, true);
  6099. }
  6100. else {
  6101. this.removeState(state);
  6102. }
  6103. };
  6104. Element.prototype._mergeStates = function (states) {
  6105. var mergedState = {};
  6106. var mergedTextConfig;
  6107. for (var i = 0; i < states.length; i++) {
  6108. var state = states[i];
  6109. extend(mergedState, state);
  6110. if (state.textConfig) {
  6111. mergedTextConfig = mergedTextConfig || {};
  6112. extend(mergedTextConfig, state.textConfig);
  6113. }
  6114. }
  6115. if (mergedTextConfig) {
  6116. mergedState.textConfig = mergedTextConfig;
  6117. }
  6118. return mergedState;
  6119. };
  6120. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6121. var needsRestoreToNormal = !(state && keepCurrentStates);
  6122. if (state && state.textConfig) {
  6123. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6124. extend(this.textConfig, state.textConfig);
  6125. }
  6126. else if (needsRestoreToNormal) {
  6127. if (normalState.textConfig) {
  6128. this.textConfig = normalState.textConfig;
  6129. }
  6130. }
  6131. var transitionTarget = {};
  6132. var hasTransition = false;
  6133. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6134. var key = PRIMARY_STATES_KEYS[i];
  6135. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6136. if (state && state[key] != null) {
  6137. if (propNeedsTransition) {
  6138. hasTransition = true;
  6139. transitionTarget[key] = state[key];
  6140. }
  6141. else {
  6142. this[key] = state[key];
  6143. }
  6144. }
  6145. else if (needsRestoreToNormal) {
  6146. if (normalState[key] != null) {
  6147. if (propNeedsTransition) {
  6148. hasTransition = true;
  6149. transitionTarget[key] = normalState[key];
  6150. }
  6151. else {
  6152. this[key] = normalState[key];
  6153. }
  6154. }
  6155. }
  6156. }
  6157. if (!transition) {
  6158. for (var i = 0; i < this.animators.length; i++) {
  6159. var animator = this.animators[i];
  6160. var targetName = animator.targetName;
  6161. if (!animator.getLoop()) {
  6162. animator.__changeFinalValue(targetName
  6163. ? (state || normalState)[targetName]
  6164. : (state || normalState));
  6165. }
  6166. }
  6167. }
  6168. if (hasTransition) {
  6169. this._transitionState(stateName, transitionTarget, animationCfg);
  6170. }
  6171. };
  6172. Element.prototype._attachComponent = function (componentEl) {
  6173. if (componentEl.__zr && !componentEl.__hostTarget) {
  6174. if ("development" !== 'production') {
  6175. throw new Error('Text element has been added to zrender.');
  6176. }
  6177. return;
  6178. }
  6179. if (componentEl === this) {
  6180. if ("development" !== 'production') {
  6181. throw new Error('Recursive component attachment.');
  6182. }
  6183. return;
  6184. }
  6185. var zr = this.__zr;
  6186. if (zr) {
  6187. componentEl.addSelfToZr(zr);
  6188. }
  6189. componentEl.__zr = zr;
  6190. componentEl.__hostTarget = this;
  6191. };
  6192. Element.prototype._detachComponent = function (componentEl) {
  6193. if (componentEl.__zr) {
  6194. componentEl.removeSelfFromZr(componentEl.__zr);
  6195. }
  6196. componentEl.__zr = null;
  6197. componentEl.__hostTarget = null;
  6198. };
  6199. Element.prototype.getClipPath = function () {
  6200. return this._clipPath;
  6201. };
  6202. Element.prototype.setClipPath = function (clipPath) {
  6203. if (this._clipPath && this._clipPath !== clipPath) {
  6204. this.removeClipPath();
  6205. }
  6206. this._attachComponent(clipPath);
  6207. this._clipPath = clipPath;
  6208. this.markRedraw();
  6209. };
  6210. Element.prototype.removeClipPath = function () {
  6211. var clipPath = this._clipPath;
  6212. if (clipPath) {
  6213. this._detachComponent(clipPath);
  6214. this._clipPath = null;
  6215. this.markRedraw();
  6216. }
  6217. };
  6218. Element.prototype.getTextContent = function () {
  6219. return this._textContent;
  6220. };
  6221. Element.prototype.setTextContent = function (textEl) {
  6222. var previousTextContent = this._textContent;
  6223. if (previousTextContent === textEl) {
  6224. return;
  6225. }
  6226. if (previousTextContent && previousTextContent !== textEl) {
  6227. this.removeTextContent();
  6228. }
  6229. if ("development" !== 'production') {
  6230. if (textEl.__zr && !textEl.__hostTarget) {
  6231. throw new Error('Text element has been added to zrender.');
  6232. }
  6233. }
  6234. textEl.innerTransformable = new Transformable();
  6235. this._attachComponent(textEl);
  6236. this._textContent = textEl;
  6237. this.markRedraw();
  6238. };
  6239. Element.prototype.setTextConfig = function (cfg) {
  6240. if (!this.textConfig) {
  6241. this.textConfig = {};
  6242. }
  6243. extend(this.textConfig, cfg);
  6244. this.markRedraw();
  6245. };
  6246. Element.prototype.removeTextConfig = function () {
  6247. this.textConfig = null;
  6248. this.markRedraw();
  6249. };
  6250. Element.prototype.removeTextContent = function () {
  6251. var textEl = this._textContent;
  6252. if (textEl) {
  6253. textEl.innerTransformable = null;
  6254. this._detachComponent(textEl);
  6255. this._textContent = null;
  6256. this._innerTextDefaultStyle = null;
  6257. this.markRedraw();
  6258. }
  6259. };
  6260. Element.prototype.getTextGuideLine = function () {
  6261. return this._textGuide;
  6262. };
  6263. Element.prototype.setTextGuideLine = function (guideLine) {
  6264. if (this._textGuide && this._textGuide !== guideLine) {
  6265. this.removeTextGuideLine();
  6266. }
  6267. this._attachComponent(guideLine);
  6268. this._textGuide = guideLine;
  6269. this.markRedraw();
  6270. };
  6271. Element.prototype.removeTextGuideLine = function () {
  6272. var textGuide = this._textGuide;
  6273. if (textGuide) {
  6274. this._detachComponent(textGuide);
  6275. this._textGuide = null;
  6276. this.markRedraw();
  6277. }
  6278. };
  6279. Element.prototype.markRedraw = function () {
  6280. this.__dirty |= REDRAW_BIT;
  6281. var zr = this.__zr;
  6282. if (zr) {
  6283. if (this.__inHover) {
  6284. zr.refreshHover();
  6285. }
  6286. else {
  6287. zr.refresh();
  6288. }
  6289. }
  6290. if (this.__hostTarget) {
  6291. this.__hostTarget.markRedraw();
  6292. }
  6293. };
  6294. Element.prototype.dirty = function () {
  6295. this.markRedraw();
  6296. };
  6297. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6298. this.__inHover = inHover;
  6299. var textContent = this._textContent;
  6300. var textGuide = this._textGuide;
  6301. if (textContent) {
  6302. textContent.__inHover = inHover;
  6303. }
  6304. if (textGuide) {
  6305. textGuide.__inHover = inHover;
  6306. }
  6307. };
  6308. Element.prototype.addSelfToZr = function (zr) {
  6309. if (this.__zr === zr) {
  6310. return;
  6311. }
  6312. this.__zr = zr;
  6313. var animators = this.animators;
  6314. if (animators) {
  6315. for (var i = 0; i < animators.length; i++) {
  6316. zr.animation.addAnimator(animators[i]);
  6317. }
  6318. }
  6319. if (this._clipPath) {
  6320. this._clipPath.addSelfToZr(zr);
  6321. }
  6322. if (this._textContent) {
  6323. this._textContent.addSelfToZr(zr);
  6324. }
  6325. if (this._textGuide) {
  6326. this._textGuide.addSelfToZr(zr);
  6327. }
  6328. };
  6329. Element.prototype.removeSelfFromZr = function (zr) {
  6330. if (!this.__zr) {
  6331. return;
  6332. }
  6333. this.__zr = null;
  6334. var animators = this.animators;
  6335. if (animators) {
  6336. for (var i = 0; i < animators.length; i++) {
  6337. zr.animation.removeAnimator(animators[i]);
  6338. }
  6339. }
  6340. if (this._clipPath) {
  6341. this._clipPath.removeSelfFromZr(zr);
  6342. }
  6343. if (this._textContent) {
  6344. this._textContent.removeSelfFromZr(zr);
  6345. }
  6346. if (this._textGuide) {
  6347. this._textGuide.removeSelfFromZr(zr);
  6348. }
  6349. };
  6350. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6351. var target = key ? this[key] : this;
  6352. if ("development" !== 'production') {
  6353. if (!target) {
  6354. logError('Property "'
  6355. + key
  6356. + '" is not existed in element '
  6357. + this.id);
  6358. return;
  6359. }
  6360. }
  6361. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6362. key && (animator.targetName = key);
  6363. this.addAnimator(animator, key);
  6364. return animator;
  6365. };
  6366. Element.prototype.addAnimator = function (animator, key) {
  6367. var zr = this.__zr;
  6368. var el = this;
  6369. animator.during(function () {
  6370. el.updateDuringAnimation(key);
  6371. }).done(function () {
  6372. var animators = el.animators;
  6373. var idx = indexOf(animators, animator);
  6374. if (idx >= 0) {
  6375. animators.splice(idx, 1);
  6376. }
  6377. });
  6378. this.animators.push(animator);
  6379. if (zr) {
  6380. zr.animation.addAnimator(animator);
  6381. }
  6382. zr && zr.wakeUp();
  6383. };
  6384. Element.prototype.updateDuringAnimation = function (key) {
  6385. this.markRedraw();
  6386. };
  6387. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6388. var animators = this.animators;
  6389. var len = animators.length;
  6390. var leftAnimators = [];
  6391. for (var i = 0; i < len; i++) {
  6392. var animator = animators[i];
  6393. if (!scope || scope === animator.scope) {
  6394. animator.stop(forwardToLast);
  6395. }
  6396. else {
  6397. leftAnimators.push(animator);
  6398. }
  6399. }
  6400. this.animators = leftAnimators;
  6401. return this;
  6402. };
  6403. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6404. animateTo(this, target, cfg, animationProps);
  6405. };
  6406. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6407. animateTo(this, target, cfg, animationProps, true);
  6408. };
  6409. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6410. var animators = animateTo(this, target, cfg, animationProps);
  6411. for (var i = 0; i < animators.length; i++) {
  6412. animators[i].__fromStateTransition = stateName;
  6413. }
  6414. };
  6415. Element.prototype.getBoundingRect = function () {
  6416. return null;
  6417. };
  6418. Element.prototype.getPaintRect = function () {
  6419. return null;
  6420. };
  6421. Element.initDefaultProps = (function () {
  6422. var elProto = Element.prototype;
  6423. elProto.type = 'element';
  6424. elProto.name = '';
  6425. elProto.ignore =
  6426. elProto.silent =
  6427. elProto.isGroup =
  6428. elProto.draggable =
  6429. elProto.dragging =
  6430. elProto.ignoreClip =
  6431. elProto.__inHover = false;
  6432. elProto.__dirty = REDRAW_BIT;
  6433. var logs = {};
  6434. function logDeprecatedError(key, xKey, yKey) {
  6435. if (!logs[key + xKey + yKey]) {
  6436. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6437. logs[key + xKey + yKey] = true;
  6438. }
  6439. }
  6440. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6441. Object.defineProperty(elProto, key, {
  6442. get: function () {
  6443. if ("development" !== 'production') {
  6444. logDeprecatedError(key, xKey, yKey);
  6445. }
  6446. if (!this[privateKey]) {
  6447. var pos = this[privateKey] = [];
  6448. enhanceArray(this, pos);
  6449. }
  6450. return this[privateKey];
  6451. },
  6452. set: function (pos) {
  6453. if ("development" !== 'production') {
  6454. logDeprecatedError(key, xKey, yKey);
  6455. }
  6456. this[xKey] = pos[0];
  6457. this[yKey] = pos[1];
  6458. this[privateKey] = pos;
  6459. enhanceArray(this, pos);
  6460. }
  6461. });
  6462. function enhanceArray(self, pos) {
  6463. Object.defineProperty(pos, 0, {
  6464. get: function () {
  6465. return self[xKey];
  6466. },
  6467. set: function (val) {
  6468. self[xKey] = val;
  6469. }
  6470. });
  6471. Object.defineProperty(pos, 1, {
  6472. get: function () {
  6473. return self[yKey];
  6474. },
  6475. set: function (val) {
  6476. self[yKey] = val;
  6477. }
  6478. });
  6479. }
  6480. }
  6481. if (Object.defineProperty) {
  6482. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6483. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6484. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6485. }
  6486. })();
  6487. return Element;
  6488. }());
  6489. mixin(Element, Eventful);
  6490. mixin(Element, Transformable);
  6491. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6492. cfg = cfg || {};
  6493. var animators = [];
  6494. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6495. var finishCount = animators.length;
  6496. var doneHappened = false;
  6497. var cfgDone = cfg.done;
  6498. var cfgAborted = cfg.aborted;
  6499. var doneCb = function () {
  6500. doneHappened = true;
  6501. finishCount--;
  6502. if (finishCount <= 0) {
  6503. doneHappened
  6504. ? (cfgDone && cfgDone())
  6505. : (cfgAborted && cfgAborted());
  6506. }
  6507. };
  6508. var abortedCb = function () {
  6509. finishCount--;
  6510. if (finishCount <= 0) {
  6511. doneHappened
  6512. ? (cfgDone && cfgDone())
  6513. : (cfgAborted && cfgAborted());
  6514. }
  6515. };
  6516. if (!finishCount) {
  6517. cfgDone && cfgDone();
  6518. }
  6519. if (animators.length > 0 && cfg.during) {
  6520. animators[0].during(function (target, percent) {
  6521. cfg.during(percent);
  6522. });
  6523. }
  6524. for (var i = 0; i < animators.length; i++) {
  6525. var animator = animators[i];
  6526. if (doneCb) {
  6527. animator.done(doneCb);
  6528. }
  6529. if (abortedCb) {
  6530. animator.aborted(abortedCb);
  6531. }
  6532. if (cfg.force) {
  6533. animator.duration(cfg.duration);
  6534. }
  6535. animator.start(cfg.easing);
  6536. }
  6537. return animators;
  6538. }
  6539. function copyArrShallow(source, target, len) {
  6540. for (var i = 0; i < len; i++) {
  6541. source[i] = target[i];
  6542. }
  6543. }
  6544. function is2DArray(value) {
  6545. return isArrayLike(value[0]);
  6546. }
  6547. function copyValue(target, source, key) {
  6548. if (isArrayLike(source[key])) {
  6549. if (!isArrayLike(target[key])) {
  6550. target[key] = [];
  6551. }
  6552. if (isTypedArray(source[key])) {
  6553. var len = source[key].length;
  6554. if (target[key].length !== len) {
  6555. target[key] = new (source[key].constructor)(len);
  6556. copyArrShallow(target[key], source[key], len);
  6557. }
  6558. }
  6559. else {
  6560. var sourceArr = source[key];
  6561. var targetArr = target[key];
  6562. var len0 = sourceArr.length;
  6563. if (is2DArray(sourceArr)) {
  6564. var len1 = sourceArr[0].length;
  6565. for (var i = 0; i < len0; i++) {
  6566. if (!targetArr[i]) {
  6567. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6568. }
  6569. else {
  6570. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6571. }
  6572. }
  6573. }
  6574. else {
  6575. copyArrShallow(targetArr, sourceArr, len0);
  6576. }
  6577. targetArr.length = sourceArr.length;
  6578. }
  6579. }
  6580. else {
  6581. target[key] = source[key];
  6582. }
  6583. }
  6584. function isValueSame(val1, val2) {
  6585. return val1 === val2
  6586. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6587. }
  6588. function is1DArraySame(arr0, arr1) {
  6589. var len = arr0.length;
  6590. if (len !== arr1.length) {
  6591. return false;
  6592. }
  6593. for (var i = 0; i < len; i++) {
  6594. if (arr0[i] !== arr1[i]) {
  6595. return false;
  6596. }
  6597. }
  6598. return true;
  6599. }
  6600. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6601. var targetKeys = keys(target);
  6602. var duration = cfg.duration;
  6603. var delay = cfg.delay;
  6604. var additive = cfg.additive;
  6605. var setToFinal = cfg.setToFinal;
  6606. var animateAll = !isObject(animationProps);
  6607. var existsAnimators = animatable.animators;
  6608. var animationKeys = [];
  6609. for (var k = 0; k < targetKeys.length; k++) {
  6610. var innerKey = targetKeys[k];
  6611. var targetVal = target[innerKey];
  6612. if (targetVal != null && animateObj[innerKey] != null
  6613. && (animateAll || animationProps[innerKey])) {
  6614. if (isObject(targetVal)
  6615. && !isArrayLike(targetVal)
  6616. && !isGradientObject(targetVal)) {
  6617. if (topKey) {
  6618. if (!reverse) {
  6619. animateObj[innerKey] = targetVal;
  6620. animatable.updateDuringAnimation(topKey);
  6621. }
  6622. continue;
  6623. }
  6624. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6625. }
  6626. else {
  6627. animationKeys.push(innerKey);
  6628. }
  6629. }
  6630. else if (!reverse) {
  6631. animateObj[innerKey] = targetVal;
  6632. animatable.updateDuringAnimation(topKey);
  6633. animationKeys.push(innerKey);
  6634. }
  6635. }
  6636. var keyLen = animationKeys.length;
  6637. if (!additive && keyLen) {
  6638. for (var i = 0; i < existsAnimators.length; i++) {
  6639. var animator = existsAnimators[i];
  6640. if (animator.targetName === topKey) {
  6641. var allAborted = animator.stopTracks(animationKeys);
  6642. if (allAborted) {
  6643. var idx = indexOf(existsAnimators, animator);
  6644. existsAnimators.splice(idx, 1);
  6645. }
  6646. }
  6647. }
  6648. }
  6649. if (!cfg.force) {
  6650. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6651. keyLen = animationKeys.length;
  6652. }
  6653. if (keyLen > 0
  6654. || (cfg.force && !animators.length)) {
  6655. var revertedSource = void 0;
  6656. var reversedTarget = void 0;
  6657. var sourceClone = void 0;
  6658. if (reverse) {
  6659. reversedTarget = {};
  6660. if (setToFinal) {
  6661. revertedSource = {};
  6662. }
  6663. for (var i = 0; i < keyLen; i++) {
  6664. var innerKey = animationKeys[i];
  6665. reversedTarget[innerKey] = animateObj[innerKey];
  6666. if (setToFinal) {
  6667. revertedSource[innerKey] = target[innerKey];
  6668. }
  6669. else {
  6670. animateObj[innerKey] = target[innerKey];
  6671. }
  6672. }
  6673. }
  6674. else if (setToFinal) {
  6675. sourceClone = {};
  6676. for (var i = 0; i < keyLen; i++) {
  6677. var innerKey = animationKeys[i];
  6678. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6679. copyValue(animateObj, target, innerKey);
  6680. }
  6681. }
  6682. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6683. animator.targetName = topKey;
  6684. if (cfg.scope) {
  6685. animator.scope = cfg.scope;
  6686. }
  6687. if (setToFinal && revertedSource) {
  6688. animator.whenWithKeys(0, revertedSource, animationKeys);
  6689. }
  6690. if (sourceClone) {
  6691. animator.whenWithKeys(0, sourceClone, animationKeys);
  6692. }
  6693. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6694. animatable.addAnimator(animator, topKey);
  6695. animators.push(animator);
  6696. }
  6697. }
  6698. var Group = (function (_super) {
  6699. __extends(Group, _super);
  6700. function Group(opts) {
  6701. var _this = _super.call(this) || this;
  6702. _this.isGroup = true;
  6703. _this._children = [];
  6704. _this.attr(opts);
  6705. return _this;
  6706. }
  6707. Group.prototype.childrenRef = function () {
  6708. return this._children;
  6709. };
  6710. Group.prototype.children = function () {
  6711. return this._children.slice();
  6712. };
  6713. Group.prototype.childAt = function (idx) {
  6714. return this._children[idx];
  6715. };
  6716. Group.prototype.childOfName = function (name) {
  6717. var children = this._children;
  6718. for (var i = 0; i < children.length; i++) {
  6719. if (children[i].name === name) {
  6720. return children[i];
  6721. }
  6722. }
  6723. };
  6724. Group.prototype.childCount = function () {
  6725. return this._children.length;
  6726. };
  6727. Group.prototype.add = function (child) {
  6728. if (child) {
  6729. if (child !== this && child.parent !== this) {
  6730. this._children.push(child);
  6731. this._doAdd(child);
  6732. }
  6733. if ("development" !== 'production') {
  6734. if (child.__hostTarget) {
  6735. throw 'This elemenet has been used as an attachment';
  6736. }
  6737. }
  6738. }
  6739. return this;
  6740. };
  6741. Group.prototype.addBefore = function (child, nextSibling) {
  6742. if (child && child !== this && child.parent !== this
  6743. && nextSibling && nextSibling.parent === this) {
  6744. var children = this._children;
  6745. var idx = children.indexOf(nextSibling);
  6746. if (idx >= 0) {
  6747. children.splice(idx, 0, child);
  6748. this._doAdd(child);
  6749. }
  6750. }
  6751. return this;
  6752. };
  6753. Group.prototype.replace = function (oldChild, newChild) {
  6754. var idx = indexOf(this._children, oldChild);
  6755. if (idx >= 0) {
  6756. this.replaceAt(newChild, idx);
  6757. }
  6758. return this;
  6759. };
  6760. Group.prototype.replaceAt = function (child, index) {
  6761. var children = this._children;
  6762. var old = children[index];
  6763. if (child && child !== this && child.parent !== this && child !== old) {
  6764. children[index] = child;
  6765. old.parent = null;
  6766. var zr = this.__zr;
  6767. if (zr) {
  6768. old.removeSelfFromZr(zr);
  6769. }
  6770. this._doAdd(child);
  6771. }
  6772. return this;
  6773. };
  6774. Group.prototype._doAdd = function (child) {
  6775. if (child.parent) {
  6776. child.parent.remove(child);
  6777. }
  6778. child.parent = this;
  6779. var zr = this.__zr;
  6780. if (zr && zr !== child.__zr) {
  6781. child.addSelfToZr(zr);
  6782. }
  6783. zr && zr.refresh();
  6784. };
  6785. Group.prototype.remove = function (child) {
  6786. var zr = this.__zr;
  6787. var children = this._children;
  6788. var idx = indexOf(children, child);
  6789. if (idx < 0) {
  6790. return this;
  6791. }
  6792. children.splice(idx, 1);
  6793. child.parent = null;
  6794. if (zr) {
  6795. child.removeSelfFromZr(zr);
  6796. }
  6797. zr && zr.refresh();
  6798. return this;
  6799. };
  6800. Group.prototype.removeAll = function () {
  6801. var children = this._children;
  6802. var zr = this.__zr;
  6803. for (var i = 0; i < children.length; i++) {
  6804. var child = children[i];
  6805. if (zr) {
  6806. child.removeSelfFromZr(zr);
  6807. }
  6808. child.parent = null;
  6809. }
  6810. children.length = 0;
  6811. return this;
  6812. };
  6813. Group.prototype.eachChild = function (cb, context) {
  6814. var children = this._children;
  6815. for (var i = 0; i < children.length; i++) {
  6816. var child = children[i];
  6817. cb.call(context, child, i);
  6818. }
  6819. return this;
  6820. };
  6821. Group.prototype.traverse = function (cb, context) {
  6822. for (var i = 0; i < this._children.length; i++) {
  6823. var child = this._children[i];
  6824. var stopped = cb.call(context, child);
  6825. if (child.isGroup && !stopped) {
  6826. child.traverse(cb, context);
  6827. }
  6828. }
  6829. return this;
  6830. };
  6831. Group.prototype.addSelfToZr = function (zr) {
  6832. _super.prototype.addSelfToZr.call(this, zr);
  6833. for (var i = 0; i < this._children.length; i++) {
  6834. var child = this._children[i];
  6835. child.addSelfToZr(zr);
  6836. }
  6837. };
  6838. Group.prototype.removeSelfFromZr = function (zr) {
  6839. _super.prototype.removeSelfFromZr.call(this, zr);
  6840. for (var i = 0; i < this._children.length; i++) {
  6841. var child = this._children[i];
  6842. child.removeSelfFromZr(zr);
  6843. }
  6844. };
  6845. Group.prototype.getBoundingRect = function (includeChildren) {
  6846. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6847. var children = includeChildren || this._children;
  6848. var tmpMat = [];
  6849. var rect = null;
  6850. for (var i = 0; i < children.length; i++) {
  6851. var child = children[i];
  6852. if (child.ignore || child.invisible) {
  6853. continue;
  6854. }
  6855. var childRect = child.getBoundingRect();
  6856. var transform = child.getLocalTransform(tmpMat);
  6857. if (transform) {
  6858. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6859. rect = rect || tmpRect.clone();
  6860. rect.union(tmpRect);
  6861. }
  6862. else {
  6863. rect = rect || childRect.clone();
  6864. rect.union(childRect);
  6865. }
  6866. }
  6867. return rect || tmpRect;
  6868. };
  6869. return Group;
  6870. }(Element));
  6871. Group.prototype.type = 'group';
  6872. /*!
  6873. * ZRender, a high performance 2d drawing library.
  6874. *
  6875. * Copyright (c) 2013, Baidu Inc.
  6876. * All rights reserved.
  6877. *
  6878. * LICENSE
  6879. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6880. */
  6881. var painterCtors = {};
  6882. var instances = {};
  6883. function delInstance(id) {
  6884. delete instances[id];
  6885. }
  6886. function isDarkMode(backgroundColor) {
  6887. if (!backgroundColor) {
  6888. return false;
  6889. }
  6890. if (typeof backgroundColor === 'string') {
  6891. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6892. }
  6893. else if (backgroundColor.colorStops) {
  6894. var colorStops = backgroundColor.colorStops;
  6895. var totalLum = 0;
  6896. var len = colorStops.length;
  6897. for (var i = 0; i < len; i++) {
  6898. totalLum += lum(colorStops[i].color, 1);
  6899. }
  6900. totalLum /= len;
  6901. return totalLum < DARK_MODE_THRESHOLD;
  6902. }
  6903. return false;
  6904. }
  6905. var ZRender = (function () {
  6906. function ZRender(id, dom, opts) {
  6907. var _this = this;
  6908. this._sleepAfterStill = 10;
  6909. this._stillFrameAccum = 0;
  6910. this._needsRefresh = true;
  6911. this._needsRefreshHover = true;
  6912. this._darkMode = false;
  6913. opts = opts || {};
  6914. this.dom = dom;
  6915. this.id = id;
  6916. var storage = new Storage();
  6917. var rendererType = opts.renderer || 'canvas';
  6918. if (!painterCtors[rendererType]) {
  6919. rendererType = keys(painterCtors)[0];
  6920. }
  6921. if ("development" !== 'production') {
  6922. if (!painterCtors[rendererType]) {
  6923. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  6924. }
  6925. }
  6926. opts.useDirtyRect = opts.useDirtyRect == null
  6927. ? false
  6928. : opts.useDirtyRect;
  6929. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  6930. var ssrMode = opts.ssr || painter.ssrOnly;
  6931. this.storage = storage;
  6932. this.painter = painter;
  6933. var handlerProxy = (!env.node && !env.worker && !ssrMode)
  6934. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  6935. : null;
  6936. var useCoarsePointer = opts.useCoarsePointer;
  6937. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  6938. ? env.touchEventsSupported
  6939. : !!useCoarsePointer;
  6940. var defaultPointerSize = 44;
  6941. var pointerSize;
  6942. if (usePointerSize) {
  6943. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  6944. }
  6945. this.handler = new Handler(storage, painter, handlerProxy, painter.root, pointerSize);
  6946. this.animation = new Animation({
  6947. stage: {
  6948. update: ssrMode ? null : function () { return _this._flush(true); }
  6949. }
  6950. });
  6951. if (!ssrMode) {
  6952. this.animation.start();
  6953. }
  6954. }
  6955. ZRender.prototype.add = function (el) {
  6956. if (this._disposed || !el) {
  6957. return;
  6958. }
  6959. this.storage.addRoot(el);
  6960. el.addSelfToZr(this);
  6961. this.refresh();
  6962. };
  6963. ZRender.prototype.remove = function (el) {
  6964. if (this._disposed || !el) {
  6965. return;
  6966. }
  6967. this.storage.delRoot(el);
  6968. el.removeSelfFromZr(this);
  6969. this.refresh();
  6970. };
  6971. ZRender.prototype.configLayer = function (zLevel, config) {
  6972. if (this._disposed) {
  6973. return;
  6974. }
  6975. if (this.painter.configLayer) {
  6976. this.painter.configLayer(zLevel, config);
  6977. }
  6978. this.refresh();
  6979. };
  6980. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  6981. if (this._disposed) {
  6982. return;
  6983. }
  6984. if (this.painter.setBackgroundColor) {
  6985. this.painter.setBackgroundColor(backgroundColor);
  6986. }
  6987. this.refresh();
  6988. this._backgroundColor = backgroundColor;
  6989. this._darkMode = isDarkMode(backgroundColor);
  6990. };
  6991. ZRender.prototype.getBackgroundColor = function () {
  6992. return this._backgroundColor;
  6993. };
  6994. ZRender.prototype.setDarkMode = function (darkMode) {
  6995. this._darkMode = darkMode;
  6996. };
  6997. ZRender.prototype.isDarkMode = function () {
  6998. return this._darkMode;
  6999. };
  7000. ZRender.prototype.refreshImmediately = function (fromInside) {
  7001. if (this._disposed) {
  7002. return;
  7003. }
  7004. if (!fromInside) {
  7005. this.animation.update(true);
  7006. }
  7007. this._needsRefresh = false;
  7008. this.painter.refresh();
  7009. this._needsRefresh = false;
  7010. };
  7011. ZRender.prototype.refresh = function () {
  7012. if (this._disposed) {
  7013. return;
  7014. }
  7015. this._needsRefresh = true;
  7016. this.animation.start();
  7017. };
  7018. ZRender.prototype.flush = function () {
  7019. if (this._disposed) {
  7020. return;
  7021. }
  7022. this._flush(false);
  7023. };
  7024. ZRender.prototype._flush = function (fromInside) {
  7025. var triggerRendered;
  7026. var start = getTime();
  7027. if (this._needsRefresh) {
  7028. triggerRendered = true;
  7029. this.refreshImmediately(fromInside);
  7030. }
  7031. if (this._needsRefreshHover) {
  7032. triggerRendered = true;
  7033. this.refreshHoverImmediately();
  7034. }
  7035. var end = getTime();
  7036. if (triggerRendered) {
  7037. this._stillFrameAccum = 0;
  7038. this.trigger('rendered', {
  7039. elapsedTime: end - start
  7040. });
  7041. }
  7042. else if (this._sleepAfterStill > 0) {
  7043. this._stillFrameAccum++;
  7044. if (this._stillFrameAccum > this._sleepAfterStill) {
  7045. this.animation.stop();
  7046. }
  7047. }
  7048. };
  7049. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7050. this._sleepAfterStill = stillFramesCount;
  7051. };
  7052. ZRender.prototype.wakeUp = function () {
  7053. if (this._disposed) {
  7054. return;
  7055. }
  7056. this.animation.start();
  7057. this._stillFrameAccum = 0;
  7058. };
  7059. ZRender.prototype.refreshHover = function () {
  7060. this._needsRefreshHover = true;
  7061. };
  7062. ZRender.prototype.refreshHoverImmediately = function () {
  7063. if (this._disposed) {
  7064. return;
  7065. }
  7066. this._needsRefreshHover = false;
  7067. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7068. this.painter.refreshHover();
  7069. }
  7070. };
  7071. ZRender.prototype.resize = function (opts) {
  7072. if (this._disposed) {
  7073. return;
  7074. }
  7075. opts = opts || {};
  7076. this.painter.resize(opts.width, opts.height);
  7077. this.handler.resize();
  7078. };
  7079. ZRender.prototype.clearAnimation = function () {
  7080. if (this._disposed) {
  7081. return;
  7082. }
  7083. this.animation.clear();
  7084. };
  7085. ZRender.prototype.getWidth = function () {
  7086. if (this._disposed) {
  7087. return;
  7088. }
  7089. return this.painter.getWidth();
  7090. };
  7091. ZRender.prototype.getHeight = function () {
  7092. if (this._disposed) {
  7093. return;
  7094. }
  7095. return this.painter.getHeight();
  7096. };
  7097. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7098. if (this._disposed) {
  7099. return;
  7100. }
  7101. this.handler.setCursorStyle(cursorStyle);
  7102. };
  7103. ZRender.prototype.findHover = function (x, y) {
  7104. if (this._disposed) {
  7105. return;
  7106. }
  7107. return this.handler.findHover(x, y);
  7108. };
  7109. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7110. if (!this._disposed) {
  7111. this.handler.on(eventName, eventHandler, context);
  7112. }
  7113. return this;
  7114. };
  7115. ZRender.prototype.off = function (eventName, eventHandler) {
  7116. if (this._disposed) {
  7117. return;
  7118. }
  7119. this.handler.off(eventName, eventHandler);
  7120. };
  7121. ZRender.prototype.trigger = function (eventName, event) {
  7122. if (this._disposed) {
  7123. return;
  7124. }
  7125. this.handler.trigger(eventName, event);
  7126. };
  7127. ZRender.prototype.clear = function () {
  7128. if (this._disposed) {
  7129. return;
  7130. }
  7131. var roots = this.storage.getRoots();
  7132. for (var i = 0; i < roots.length; i++) {
  7133. if (roots[i] instanceof Group) {
  7134. roots[i].removeSelfFromZr(this);
  7135. }
  7136. }
  7137. this.storage.delAllRoots();
  7138. this.painter.clear();
  7139. };
  7140. ZRender.prototype.dispose = function () {
  7141. if (this._disposed) {
  7142. return;
  7143. }
  7144. this.animation.stop();
  7145. this.clear();
  7146. this.storage.dispose();
  7147. this.painter.dispose();
  7148. this.handler.dispose();
  7149. this.animation =
  7150. this.storage =
  7151. this.painter =
  7152. this.handler = null;
  7153. this._disposed = true;
  7154. delInstance(this.id);
  7155. };
  7156. return ZRender;
  7157. }());
  7158. function init(dom, opts) {
  7159. var zr = new ZRender(guid(), dom, opts);
  7160. instances[zr.id] = zr;
  7161. return zr;
  7162. }
  7163. function dispose(zr) {
  7164. zr.dispose();
  7165. }
  7166. function disposeAll() {
  7167. for (var key in instances) {
  7168. if (instances.hasOwnProperty(key)) {
  7169. instances[key].dispose();
  7170. }
  7171. }
  7172. instances = {};
  7173. }
  7174. function getInstance(id) {
  7175. return instances[id];
  7176. }
  7177. function registerPainter(name, Ctor) {
  7178. painterCtors[name] = Ctor;
  7179. }
  7180. var ssrDataGetter;
  7181. function getElementSSRData(el) {
  7182. if (typeof ssrDataGetter === 'function') {
  7183. return ssrDataGetter(el);
  7184. }
  7185. }
  7186. function registerSSRDataGetter(getter) {
  7187. ssrDataGetter = getter;
  7188. }
  7189. var version = '5.6.0';
  7190. var zrender = /*#__PURE__*/Object.freeze({
  7191. __proto__: null,
  7192. init: init,
  7193. dispose: dispose,
  7194. disposeAll: disposeAll,
  7195. getInstance: getInstance,
  7196. registerPainter: registerPainter,
  7197. getElementSSRData: getElementSSRData,
  7198. registerSSRDataGetter: registerSSRDataGetter,
  7199. version: version
  7200. });
  7201. var RADIAN_EPSILON = 1e-4;
  7202. // Although chrome already enlarge this number to 100 for `toFixed`, but
  7203. // we sill follow the spec for compatibility.
  7204. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7205. function _trim(str) {
  7206. return str.replace(/^\s+|\s+$/g, '');
  7207. }
  7208. /**
  7209. * Linear mapping a value from domain to range
  7210. * @param val
  7211. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7212. * @param range Range extent range[0] can be bigger than range[1]
  7213. * @param clamp Default to be false
  7214. */
  7215. function linearMap(val, domain, range, clamp) {
  7216. var d0 = domain[0];
  7217. var d1 = domain[1];
  7218. var r0 = range[0];
  7219. var r1 = range[1];
  7220. var subDomain = d1 - d0;
  7221. var subRange = r1 - r0;
  7222. if (subDomain === 0) {
  7223. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7224. }
  7225. // Avoid accuracy problem in edge, such as
  7226. // 146.39 - 62.83 === 83.55999999999999.
  7227. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7228. // It is a little verbose for efficiency considering this method
  7229. // is a hotspot.
  7230. if (clamp) {
  7231. if (subDomain > 0) {
  7232. if (val <= d0) {
  7233. return r0;
  7234. } else if (val >= d1) {
  7235. return r1;
  7236. }
  7237. } else {
  7238. if (val >= d0) {
  7239. return r0;
  7240. } else if (val <= d1) {
  7241. return r1;
  7242. }
  7243. }
  7244. } else {
  7245. if (val === d0) {
  7246. return r0;
  7247. }
  7248. if (val === d1) {
  7249. return r1;
  7250. }
  7251. }
  7252. return (val - d0) / subDomain * subRange + r0;
  7253. }
  7254. /**
  7255. * Convert a percent string to absolute number.
  7256. * Returns NaN if percent is not a valid string or number
  7257. */
  7258. function parsePercent$1(percent, all) {
  7259. switch (percent) {
  7260. case 'center':
  7261. case 'middle':
  7262. percent = '50%';
  7263. break;
  7264. case 'left':
  7265. case 'top':
  7266. percent = '0%';
  7267. break;
  7268. case 'right':
  7269. case 'bottom':
  7270. percent = '100%';
  7271. break;
  7272. }
  7273. if (isString(percent)) {
  7274. if (_trim(percent).match(/%$/)) {
  7275. return parseFloat(percent) / 100 * all;
  7276. }
  7277. return parseFloat(percent);
  7278. }
  7279. return percent == null ? NaN : +percent;
  7280. }
  7281. function round(x, precision, returnStr) {
  7282. if (precision == null) {
  7283. precision = 10;
  7284. }
  7285. // Avoid range error
  7286. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX);
  7287. // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7288. x = (+x).toFixed(precision);
  7289. return returnStr ? x : +x;
  7290. }
  7291. /**
  7292. * Inplacd asc sort arr.
  7293. * The input arr will be modified.
  7294. */
  7295. function asc(arr) {
  7296. arr.sort(function (a, b) {
  7297. return a - b;
  7298. });
  7299. return arr;
  7300. }
  7301. /**
  7302. * Get precision.
  7303. */
  7304. function getPrecision(val) {
  7305. val = +val;
  7306. if (isNaN(val)) {
  7307. return 0;
  7308. }
  7309. // It is much faster than methods converting number to string as follows
  7310. // let tmp = val.toString();
  7311. // return tmp.length - 1 - tmp.indexOf('.');
  7312. // especially when precision is low
  7313. // Notice:
  7314. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7315. // (see https://jsbench.me/2vkpcekkvw/1)
  7316. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7317. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7318. if (val > 1e-14) {
  7319. var e = 1;
  7320. for (var i = 0; i < 15; i++, e *= 10) {
  7321. if (Math.round(val * e) / e === val) {
  7322. return i;
  7323. }
  7324. }
  7325. }
  7326. return getPrecisionSafe(val);
  7327. }
  7328. /**
  7329. * Get precision with slow but safe method
  7330. */
  7331. function getPrecisionSafe(val) {
  7332. // toLowerCase for: '3.4E-12'
  7333. var str = val.toString().toLowerCase();
  7334. // Consider scientific notation: '3.4e-12' '3.4e+12'
  7335. var eIndex = str.indexOf('e');
  7336. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7337. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7338. var dotIndex = str.indexOf('.');
  7339. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7340. return Math.max(0, decimalPartLen - exp);
  7341. }
  7342. /**
  7343. * Minimal dicernible data precisioin according to a single pixel.
  7344. */
  7345. function getPixelPrecision(dataExtent, pixelExtent) {
  7346. var log = Math.log;
  7347. var LN10 = Math.LN10;
  7348. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7349. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  7350. // toFixed() digits argument must be between 0 and 20.
  7351. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7352. return !isFinite(precision) ? 20 : precision;
  7353. }
  7354. /**
  7355. * Get a data of given precision, assuring the sum of percentages
  7356. * in valueList is 1.
  7357. * The largest remainder method is used.
  7358. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7359. *
  7360. * @param valueList a list of all data
  7361. * @param idx index of the data to be processed in valueList
  7362. * @param precision integer number showing digits of precision
  7363. * @return percent ranging from 0 to 100
  7364. */
  7365. function getPercentWithPrecision(valueList, idx, precision) {
  7366. if (!valueList[idx]) {
  7367. return 0;
  7368. }
  7369. var seats = getPercentSeats(valueList, precision);
  7370. return seats[idx] || 0;
  7371. }
  7372. /**
  7373. * Get a data of given precision, assuring the sum of percentages
  7374. * in valueList is 1.
  7375. * The largest remainder method is used.
  7376. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7377. *
  7378. * @param valueList a list of all data
  7379. * @param precision integer number showing digits of precision
  7380. * @return {Array<number>}
  7381. */
  7382. function getPercentSeats(valueList, precision) {
  7383. var sum = reduce(valueList, function (acc, val) {
  7384. return acc + (isNaN(val) ? 0 : val);
  7385. }, 0);
  7386. if (sum === 0) {
  7387. return [];
  7388. }
  7389. var digits = Math.pow(10, precision);
  7390. var votesPerQuota = map(valueList, function (val) {
  7391. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7392. });
  7393. var targetSeats = digits * 100;
  7394. var seats = map(votesPerQuota, function (votes) {
  7395. // Assign automatic seats.
  7396. return Math.floor(votes);
  7397. });
  7398. var currentSum = reduce(seats, function (acc, val) {
  7399. return acc + val;
  7400. }, 0);
  7401. var remainder = map(votesPerQuota, function (votes, idx) {
  7402. return votes - seats[idx];
  7403. });
  7404. // Has remainding votes.
  7405. while (currentSum < targetSeats) {
  7406. // Find next largest remainder.
  7407. var max = Number.NEGATIVE_INFINITY;
  7408. var maxId = null;
  7409. for (var i = 0, len = remainder.length; i < len; ++i) {
  7410. if (remainder[i] > max) {
  7411. max = remainder[i];
  7412. maxId = i;
  7413. }
  7414. }
  7415. // Add a vote to max remainder.
  7416. ++seats[maxId];
  7417. remainder[maxId] = 0;
  7418. ++currentSum;
  7419. }
  7420. return map(seats, function (seat) {
  7421. return seat / digits;
  7422. });
  7423. }
  7424. /**
  7425. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7426. * See <http://0.30000000000000004.com/>
  7427. */
  7428. function addSafe(val0, val1) {
  7429. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1));
  7430. // const multiplier = Math.pow(10, maxPrecision);
  7431. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7432. var sum = val0 + val1;
  7433. // // PENDING: support more?
  7434. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7435. }
  7436. // Number.MAX_SAFE_INTEGER, ie do not support.
  7437. var MAX_SAFE_INTEGER = 9007199254740991;
  7438. /**
  7439. * To 0 - 2 * PI, considering negative radian.
  7440. */
  7441. function remRadian(radian) {
  7442. var pi2 = Math.PI * 2;
  7443. return (radian % pi2 + pi2) % pi2;
  7444. }
  7445. /**
  7446. * @param {type} radian
  7447. * @return {boolean}
  7448. */
  7449. function isRadianAroundZero(val) {
  7450. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7451. }
  7452. // eslint-disable-next-line
  7453. 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
  7454. /**
  7455. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7456. * These values can be accepted:
  7457. * + An instance of Date, represent a time in its own time zone.
  7458. * + Or string in a subset of ISO 8601, only including:
  7459. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7460. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7461. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7462. * all of which will be treated as local time if time zone is not specified
  7463. * (see <https://momentjs.com/>).
  7464. * + Or other string format, including (all of which will be treated as local time):
  7465. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7466. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7467. * + a timestamp, which represent a time in UTC.
  7468. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7469. */
  7470. function parseDate(value) {
  7471. if (value instanceof Date) {
  7472. return value;
  7473. } else if (isString(value)) {
  7474. // Different browsers parse date in different way, so we parse it manually.
  7475. // Some other issues:
  7476. // new Date('1970-01-01') is UTC,
  7477. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7478. // See issue #3623
  7479. var match = TIME_REG.exec(value);
  7480. if (!match) {
  7481. // return Invalid Date.
  7482. return new Date(NaN);
  7483. }
  7484. // Use local time when no timezone offset is specified.
  7485. if (!match[8]) {
  7486. // match[n] can only be string or undefined.
  7487. // But take care of '12' + 1 => '121'.
  7488. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, match[7] ? +match[7].substring(0, 3) : 0);
  7489. }
  7490. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7491. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7492. // For example, system timezone is set as "Time Zone: America/Toronto",
  7493. // then these code will get different result:
  7494. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7495. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7496. // So we should not use `new Date`, but use `Date.UTC`.
  7497. else {
  7498. var hour = +match[4] || 0;
  7499. if (match[8].toUpperCase() !== 'Z') {
  7500. hour -= +match[8].slice(0, 3);
  7501. }
  7502. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, match[7] ? +match[7].substring(0, 3) : 0));
  7503. }
  7504. } else if (value == null) {
  7505. return new Date(NaN);
  7506. }
  7507. return new Date(Math.round(value));
  7508. }
  7509. /**
  7510. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7511. *
  7512. * @param val
  7513. * @return
  7514. */
  7515. function quantity(val) {
  7516. return Math.pow(10, quantityExponent(val));
  7517. }
  7518. /**
  7519. * Exponent of the quantity of a number
  7520. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7521. *
  7522. * @param val non-negative value
  7523. * @return
  7524. */
  7525. function quantityExponent(val) {
  7526. if (val === 0) {
  7527. return 0;
  7528. }
  7529. var exp = Math.floor(Math.log(val) / Math.LN10);
  7530. /**
  7531. * exp is expected to be the rounded-down result of the base-10 log of val.
  7532. * But due to the precision loss with Math.log(val), we need to restore it
  7533. * using 10^exp to make sure we can get val back from exp. #11249
  7534. */
  7535. if (val / Math.pow(10, exp) >= 10) {
  7536. exp++;
  7537. }
  7538. return exp;
  7539. }
  7540. /**
  7541. * find a “nice” number approximately equal to x. Round the number if round = true,
  7542. * take ceiling if round = false. The primary observation is that the “nicest”
  7543. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7544. *
  7545. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7546. *
  7547. * @param val Non-negative value.
  7548. * @param round
  7549. * @return Niced number
  7550. */
  7551. function nice(val, round) {
  7552. var exponent = quantityExponent(val);
  7553. var exp10 = Math.pow(10, exponent);
  7554. var f = val / exp10; // 1 <= f < 10
  7555. var nf;
  7556. if (round) {
  7557. if (f < 1.5) {
  7558. nf = 1;
  7559. } else if (f < 2.5) {
  7560. nf = 2;
  7561. } else if (f < 4) {
  7562. nf = 3;
  7563. } else if (f < 7) {
  7564. nf = 5;
  7565. } else {
  7566. nf = 10;
  7567. }
  7568. } else {
  7569. if (f < 1) {
  7570. nf = 1;
  7571. } else if (f < 2) {
  7572. nf = 2;
  7573. } else if (f < 3) {
  7574. nf = 3;
  7575. } else if (f < 5) {
  7576. nf = 5;
  7577. } else {
  7578. nf = 10;
  7579. }
  7580. }
  7581. val = nf * exp10;
  7582. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7583. // 20 is the uppper bound of toFixed.
  7584. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7585. }
  7586. /**
  7587. * This code was copied from "d3.js"
  7588. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7589. * See the license statement at the head of this file.
  7590. * @param ascArr
  7591. */
  7592. function quantile(ascArr, p) {
  7593. var H = (ascArr.length - 1) * p + 1;
  7594. var h = Math.floor(H);
  7595. var v = +ascArr[h - 1];
  7596. var e = H - h;
  7597. return e ? v + e * (ascArr[h] - v) : v;
  7598. }
  7599. /**
  7600. * Order intervals asc, and split them when overlap.
  7601. * expect(numberUtil.reformIntervals([
  7602. * {interval: [18, 62], close: [1, 1]},
  7603. * {interval: [-Infinity, -70], close: [0, 0]},
  7604. * {interval: [-70, -26], close: [1, 1]},
  7605. * {interval: [-26, 18], close: [1, 1]},
  7606. * {interval: [62, 150], close: [1, 1]},
  7607. * {interval: [106, 150], close: [1, 1]},
  7608. * {interval: [150, Infinity], close: [0, 0]}
  7609. * ])).toEqual([
  7610. * {interval: [-Infinity, -70], close: [0, 0]},
  7611. * {interval: [-70, -26], close: [1, 1]},
  7612. * {interval: [-26, 18], close: [0, 1]},
  7613. * {interval: [18, 62], close: [0, 1]},
  7614. * {interval: [62, 150], close: [0, 1]},
  7615. * {interval: [150, Infinity], close: [0, 0]}
  7616. * ]);
  7617. * @param list, where `close` mean open or close
  7618. * of the interval, and Infinity can be used.
  7619. * @return The origin list, which has been reformed.
  7620. */
  7621. function reformIntervals(list) {
  7622. list.sort(function (a, b) {
  7623. return littleThan(a, b, 0) ? -1 : 1;
  7624. });
  7625. var curr = -Infinity;
  7626. var currClose = 1;
  7627. for (var i = 0; i < list.length;) {
  7628. var interval = list[i].interval;
  7629. var close_1 = list[i].close;
  7630. for (var lg = 0; lg < 2; lg++) {
  7631. if (interval[lg] <= curr) {
  7632. interval[lg] = curr;
  7633. close_1[lg] = !lg ? 1 - currClose : 1;
  7634. }
  7635. curr = interval[lg];
  7636. currClose = close_1[lg];
  7637. }
  7638. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7639. list.splice(i, 1);
  7640. } else {
  7641. i++;
  7642. }
  7643. }
  7644. return list;
  7645. function littleThan(a, b, lg) {
  7646. 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));
  7647. }
  7648. }
  7649. /**
  7650. * [Numeric is defined as]:
  7651. * `parseFloat(val) == val`
  7652. * For example:
  7653. * numeric:
  7654. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7655. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7656. * not-numeric:
  7657. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7658. * empty string, string with only white-spaces or line-terminal (see es spec),
  7659. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7660. * non-string, ...
  7661. *
  7662. * @test See full test cases in `test/ut/spec/util/number.js`.
  7663. * @return Must be a typeof number. If not numeric, return NaN.
  7664. */
  7665. function numericToNumber(val) {
  7666. var valFloat = parseFloat(val);
  7667. return valFloat == val // eslint-disable-line eqeqeq
  7668. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7669. ? valFloat : NaN;
  7670. }
  7671. /**
  7672. * Definition of "numeric": see `numericToNumber`.
  7673. */
  7674. function isNumeric(val) {
  7675. return !isNaN(numericToNumber(val));
  7676. }
  7677. /**
  7678. * Use random base to prevent users hard code depending on
  7679. * this auto generated marker id.
  7680. * @return An positive integer.
  7681. */
  7682. function getRandomIdBase() {
  7683. return Math.round(Math.random() * 9);
  7684. }
  7685. /**
  7686. * Get the greatest common divisor.
  7687. *
  7688. * @param {number} a one number
  7689. * @param {number} b the other number
  7690. */
  7691. function getGreatestCommonDividor(a, b) {
  7692. if (b === 0) {
  7693. return a;
  7694. }
  7695. return getGreatestCommonDividor(b, a % b);
  7696. }
  7697. /**
  7698. * Get the least common multiple.
  7699. *
  7700. * @param {number} a one number
  7701. * @param {number} b the other number
  7702. */
  7703. function getLeastCommonMultiple(a, b) {
  7704. if (a == null) {
  7705. return b;
  7706. }
  7707. if (b == null) {
  7708. return a;
  7709. }
  7710. return a * b / getGreatestCommonDividor(a, b);
  7711. }
  7712. var ECHARTS_PREFIX = '[ECharts] ';
  7713. var storedLogs = {};
  7714. var hasConsole = typeof console !== 'undefined'
  7715. // eslint-disable-next-line
  7716. && console.warn && console.log;
  7717. function outputLog(type, str, onlyOnce) {
  7718. if (hasConsole) {
  7719. if (onlyOnce) {
  7720. if (storedLogs[str]) {
  7721. return;
  7722. }
  7723. storedLogs[str] = true;
  7724. }
  7725. // eslint-disable-next-line
  7726. console[type](ECHARTS_PREFIX + str);
  7727. }
  7728. }
  7729. function log(str, onlyOnce) {
  7730. outputLog('log', str, onlyOnce);
  7731. }
  7732. function warn(str, onlyOnce) {
  7733. outputLog('warn', str, onlyOnce);
  7734. }
  7735. function error(str, onlyOnce) {
  7736. outputLog('error', str, onlyOnce);
  7737. }
  7738. function deprecateLog(str) {
  7739. if ("development" !== 'production') {
  7740. // Not display duplicate message.
  7741. outputLog('warn', 'DEPRECATED: ' + str, true);
  7742. }
  7743. }
  7744. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7745. if ("development" !== 'production') {
  7746. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7747. }
  7748. }
  7749. /**
  7750. * If in __DEV__ environment, get console printable message for users hint.
  7751. * Parameters are separated by ' '.
  7752. * @usage
  7753. * makePrintable('This is an error on', someVar, someObj);
  7754. *
  7755. * @param hintInfo anything about the current execution context to hint users.
  7756. * @throws Error
  7757. */
  7758. function makePrintable() {
  7759. var hintInfo = [];
  7760. for (var _i = 0; _i < arguments.length; _i++) {
  7761. hintInfo[_i] = arguments[_i];
  7762. }
  7763. var msg = '';
  7764. if ("development" !== 'production') {
  7765. // Fuzzy stringify for print.
  7766. // This code only exist in dev environment.
  7767. var makePrintableStringIfPossible_1 = function (val) {
  7768. 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;
  7769. };
  7770. msg = map(hintInfo, function (arg) {
  7771. if (isString(arg)) {
  7772. // Print without quotation mark for some statement.
  7773. return arg;
  7774. } else {
  7775. var printableStr = makePrintableStringIfPossible_1(arg);
  7776. if (printableStr != null) {
  7777. return printableStr;
  7778. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7779. try {
  7780. return JSON.stringify(arg, function (n, val) {
  7781. var printableStr = makePrintableStringIfPossible_1(val);
  7782. return printableStr == null ? val : printableStr;
  7783. });
  7784. // In most cases the info object is small, so do not line break.
  7785. } catch (err) {
  7786. return '?';
  7787. }
  7788. } else {
  7789. return '?';
  7790. }
  7791. }
  7792. }).join(' ');
  7793. }
  7794. return msg;
  7795. }
  7796. /**
  7797. * @throws Error
  7798. */
  7799. function throwError(msg) {
  7800. throw new Error(msg);
  7801. }
  7802. function interpolateNumber$1(p0, p1, percent) {
  7803. return (p1 - p0) * percent + p0;
  7804. }
  7805. /**
  7806. * Make the name displayable. But we should
  7807. * make sure it is not duplicated with user
  7808. * specified name, so use '\0';
  7809. */
  7810. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7811. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7812. /**
  7813. * If value is not array, then translate it to array.
  7814. * @param {*} value
  7815. * @return {Array} [value] or value
  7816. */
  7817. function normalizeToArray(value) {
  7818. return value instanceof Array ? value : value == null ? [] : [value];
  7819. }
  7820. /**
  7821. * Sync default option between normal and emphasis like `position` and `show`
  7822. * In case some one will write code like
  7823. * label: {
  7824. * show: false,
  7825. * position: 'outside',
  7826. * fontSize: 18
  7827. * },
  7828. * emphasis: {
  7829. * label: { show: true }
  7830. * }
  7831. */
  7832. function defaultEmphasis(opt, key, subOpts) {
  7833. // Caution: performance sensitive.
  7834. if (opt) {
  7835. opt[key] = opt[key] || {};
  7836. opt.emphasis = opt.emphasis || {};
  7837. opt.emphasis[key] = opt.emphasis[key] || {};
  7838. // Default emphasis option from normal
  7839. for (var i = 0, len = subOpts.length; i < len; i++) {
  7840. var subOptName = subOpts[i];
  7841. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7842. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7843. }
  7844. }
  7845. }
  7846. }
  7847. 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'];
  7848. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  7849. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7850. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7851. // // FIXME: deprecated, check and remove it.
  7852. // 'textStyle'
  7853. // ]);
  7854. /**
  7855. * The method does not ensure performance.
  7856. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7857. * This helper method retrieves value from data.
  7858. */
  7859. function getDataItemValue(dataItem) {
  7860. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7861. }
  7862. /**
  7863. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7864. * This helper method determine if dataItem has extra option besides value
  7865. */
  7866. function isDataItemOption(dataItem) {
  7867. return isObject(dataItem) && !(dataItem instanceof Array);
  7868. // // markLine data can be array
  7869. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7870. }
  7871. /**
  7872. * Mapping to existings for merge.
  7873. *
  7874. * Mode "normalMege":
  7875. * The mapping result (merge result) will keep the order of the existing
  7876. * component, rather than the order of new option. Because we should ensure
  7877. * some specified index reference (like xAxisIndex) keep work.
  7878. * And in most cases, "merge option" is used to update partial option but not
  7879. * be expected to change the order.
  7880. *
  7881. * Mode "replaceMege":
  7882. * (1) Only the id mapped components will be merged.
  7883. * (2) Other existing components (except internal components) will be removed.
  7884. * (3) Other new options will be used to create new component.
  7885. * (4) The index of the existing components will not be modified.
  7886. * That means their might be "hole" after the removal.
  7887. * The new components are created first at those available index.
  7888. *
  7889. * Mode "replaceAll":
  7890. * This mode try to support that reproduce an echarts instance from another
  7891. * echarts instance (via `getOption`) in some simple cases.
  7892. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7893. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  7894. * the "hole" in `newCmptOptions` will also be kept.
  7895. * On the contrary, other modes try best to eliminate holes.
  7896. * PENDING: This is an experimental mode yet.
  7897. *
  7898. * @return See the comment of <MappingResult>.
  7899. */
  7900. function mappingToExists(existings, newCmptOptions, mode) {
  7901. var isNormalMergeMode = mode === 'normalMerge';
  7902. var isReplaceMergeMode = mode === 'replaceMerge';
  7903. var isReplaceAllMode = mode === 'replaceAll';
  7904. existings = existings || [];
  7905. newCmptOptions = (newCmptOptions || []).slice();
  7906. var existingIdIdxMap = createHashMap();
  7907. // Validate id and name on user input option.
  7908. each(newCmptOptions, function (cmptOption, index) {
  7909. if (!isObject(cmptOption)) {
  7910. newCmptOptions[index] = null;
  7911. return;
  7912. }
  7913. if ("development" !== 'production') {
  7914. // There is some legacy case that name is set as `false`.
  7915. // But should work normally rather than throw error.
  7916. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7917. warnInvalidateIdOrName(cmptOption.id);
  7918. }
  7919. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7920. warnInvalidateIdOrName(cmptOption.name);
  7921. }
  7922. }
  7923. });
  7924. var result = prepareResult(existings, existingIdIdxMap, mode);
  7925. if (isNormalMergeMode || isReplaceMergeMode) {
  7926. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7927. }
  7928. if (isNormalMergeMode) {
  7929. mappingByName(result, newCmptOptions);
  7930. }
  7931. if (isNormalMergeMode || isReplaceMergeMode) {
  7932. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7933. } else if (isReplaceAllMode) {
  7934. mappingInReplaceAllMode(result, newCmptOptions);
  7935. }
  7936. makeIdAndName(result);
  7937. // The array `result` MUST NOT contain elided items, otherwise the
  7938. // forEach will omit those items and result in incorrect result.
  7939. return result;
  7940. }
  7941. function prepareResult(existings, existingIdIdxMap, mode) {
  7942. var result = [];
  7943. if (mode === 'replaceAll') {
  7944. return result;
  7945. }
  7946. // Do not use native `map` to in case that the array `existings`
  7947. // contains elided items, which will be omitted.
  7948. for (var index = 0; index < existings.length; index++) {
  7949. var existing = existings[index];
  7950. // Because of replaceMerge, `existing` may be null/undefined.
  7951. if (existing && existing.id != null) {
  7952. existingIdIdxMap.set(existing.id, index);
  7953. }
  7954. // For non-internal-componnets:
  7955. // Mode "normalMerge": all existings kept.
  7956. // Mode "replaceMerge": all existing removed unless mapped by id.
  7957. // For internal-components:
  7958. // go with "replaceMerge" approach in both mode.
  7959. result.push({
  7960. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7961. newOption: null,
  7962. keyInfo: null,
  7963. brandNew: null
  7964. });
  7965. }
  7966. return result;
  7967. }
  7968. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7969. // Mapping by id if specified.
  7970. each(newCmptOptions, function (cmptOption, index) {
  7971. if (!cmptOption || cmptOption.id == null) {
  7972. return;
  7973. }
  7974. var optionId = makeComparableKey(cmptOption.id);
  7975. var existingIdx = existingIdIdxMap.get(optionId);
  7976. if (existingIdx != null) {
  7977. var resultItem = result[existingIdx];
  7978. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7979. resultItem.newOption = cmptOption;
  7980. // In both mode, if id matched, new option will be merged to
  7981. // the existings rather than creating new component model.
  7982. resultItem.existing = existings[existingIdx];
  7983. newCmptOptions[index] = null;
  7984. }
  7985. });
  7986. }
  7987. function mappingByName(result, newCmptOptions) {
  7988. // Mapping by name if specified.
  7989. each(newCmptOptions, function (cmptOption, index) {
  7990. if (!cmptOption || cmptOption.name == null) {
  7991. return;
  7992. }
  7993. for (var i = 0; i < result.length; i++) {
  7994. var existing = result[i].existing;
  7995. if (!result[i].newOption // Consider name: two map to one.
  7996. // Can not match when both ids existing but different.
  7997. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  7998. result[i].newOption = cmptOption;
  7999. newCmptOptions[index] = null;
  8000. return;
  8001. }
  8002. }
  8003. });
  8004. }
  8005. function mappingByIndex(result, newCmptOptions, brandNew) {
  8006. each(newCmptOptions, function (cmptOption) {
  8007. if (!cmptOption) {
  8008. return;
  8009. }
  8010. // Find the first place that not mapped by id and not internal component (consider the "hole").
  8011. var resultItem;
  8012. var nextIdx = 0;
  8013. while (
  8014. // Be `!resultItem` only when `nextIdx >= result.length`.
  8015. (resultItem = result[nextIdx]
  8016. // (1) Existing models that already have id should be able to mapped to. Because
  8017. // after mapping performed, model will always be assigned with an id if user not given.
  8018. // After that all models have id.
  8019. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8020. // not be merged to the existings with different id. Because id should not be overwritten.
  8021. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8022. ) && (resultItem.newOption || isComponentIdInternal(resultItem.existing) ||
  8023. // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8024. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8025. nextIdx++;
  8026. }
  8027. if (resultItem) {
  8028. resultItem.newOption = cmptOption;
  8029. resultItem.brandNew = brandNew;
  8030. } else {
  8031. result.push({
  8032. newOption: cmptOption,
  8033. brandNew: brandNew,
  8034. existing: null,
  8035. keyInfo: null
  8036. });
  8037. }
  8038. nextIdx++;
  8039. });
  8040. }
  8041. function mappingInReplaceAllMode(result, newCmptOptions) {
  8042. each(newCmptOptions, function (cmptOption) {
  8043. // The feature "reproduce" requires "hole" will also reproduced
  8044. // in case that component index referring are broken.
  8045. result.push({
  8046. newOption: cmptOption,
  8047. brandNew: true,
  8048. existing: null,
  8049. keyInfo: null
  8050. });
  8051. });
  8052. }
  8053. /**
  8054. * Make id and name for mapping result (result of mappingToExists)
  8055. * into `keyInfo` field.
  8056. */
  8057. function makeIdAndName(mapResult) {
  8058. // We use this id to hash component models and view instances
  8059. // in echarts. id can be specified by user, or auto generated.
  8060. // The id generation rule ensures new view instance are able
  8061. // to mapped to old instance when setOption are called in
  8062. // no-merge mode. So we generate model id by name and plus
  8063. // type in view id.
  8064. // name can be duplicated among components, which is convenient
  8065. // to specify multi components (like series) by one name.
  8066. // Ensure that each id is distinct.
  8067. var idMap = createHashMap();
  8068. each(mapResult, function (item) {
  8069. var existing = item.existing;
  8070. existing && idMap.set(existing.id, item);
  8071. });
  8072. each(mapResult, function (item) {
  8073. var opt = item.newOption;
  8074. // Force ensure id not duplicated.
  8075. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8076. opt && opt.id != null && idMap.set(opt.id, item);
  8077. !item.keyInfo && (item.keyInfo = {});
  8078. });
  8079. // Make name and id.
  8080. each(mapResult, function (item, index) {
  8081. var existing = item.existing;
  8082. var opt = item.newOption;
  8083. var keyInfo = item.keyInfo;
  8084. if (!isObject(opt)) {
  8085. return;
  8086. }
  8087. // Name can be overwritten. Consider case: axis.name = '20km'.
  8088. // But id generated by name will not be changed, which affect
  8089. // only in that case: setOption with 'not merge mode' and view
  8090. // instance will be recreated, which can be accepted.
  8091. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name
  8092. // Avoid that different series has the same name,
  8093. // because name may be used like in color pallet.
  8094. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8095. if (existing) {
  8096. keyInfo.id = makeComparableKey(existing.id);
  8097. } else if (opt.id != null) {
  8098. keyInfo.id = makeComparableKey(opt.id);
  8099. } else {
  8100. // Consider this situatoin:
  8101. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8102. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8103. // Series with the same name between optionA and optionB
  8104. // should be mapped.
  8105. var idNum = 0;
  8106. do {
  8107. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8108. } while (idMap.get(keyInfo.id));
  8109. }
  8110. idMap.set(keyInfo.id, item);
  8111. });
  8112. }
  8113. function keyExistAndEqual(attr, obj1, obj2) {
  8114. var key1 = convertOptionIdName(obj1[attr], null);
  8115. var key2 = convertOptionIdName(obj2[attr], null);
  8116. // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8117. return key1 != null && key2 != null && key1 === key2;
  8118. }
  8119. /**
  8120. * @return return null if not exist.
  8121. */
  8122. function makeComparableKey(val) {
  8123. if ("development" !== 'production') {
  8124. if (val == null) {
  8125. throw new Error();
  8126. }
  8127. }
  8128. return convertOptionIdName(val, '');
  8129. }
  8130. function convertOptionIdName(idOrName, defaultValue) {
  8131. if (idOrName == null) {
  8132. return defaultValue;
  8133. }
  8134. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8135. }
  8136. function warnInvalidateIdOrName(idOrName) {
  8137. if ("development" !== 'production') {
  8138. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8139. }
  8140. }
  8141. function isValidIdOrName(idOrName) {
  8142. return isStringSafe(idOrName) || isNumeric(idOrName);
  8143. }
  8144. function isNameSpecified(componentModel) {
  8145. var name = componentModel.name;
  8146. // Is specified when `indexOf` get -1 or > 0.
  8147. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8148. }
  8149. /**
  8150. * @public
  8151. * @param {Object} cmptOption
  8152. * @return {boolean}
  8153. */
  8154. function isComponentIdInternal(cmptOption) {
  8155. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8156. }
  8157. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8158. // Set mainType and complete subType.
  8159. each(mappingResult, function (item) {
  8160. var newOption = item.newOption;
  8161. if (isObject(newOption)) {
  8162. item.keyInfo.mainType = mainType;
  8163. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8164. }
  8165. });
  8166. }
  8167. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8168. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType
  8169. // Use determineSubType only when there is no existComponent.
  8170. : componentModelCtor.determineSubType(mainType, newCmptOption);
  8171. // tooltip, markline, markpoint may always has no subType
  8172. return subType;
  8173. }
  8174. /**
  8175. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8176. * each of which can be Array or primary type.
  8177. * @return dataIndex If not found, return undefined/null.
  8178. */
  8179. function queryDataIndex(data, payload) {
  8180. if (payload.dataIndexInside != null) {
  8181. return payload.dataIndexInside;
  8182. } else if (payload.dataIndex != null) {
  8183. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8184. return data.indexOfRawIndex(value);
  8185. }) : data.indexOfRawIndex(payload.dataIndex);
  8186. } else if (payload.name != null) {
  8187. return isArray(payload.name) ? map(payload.name, function (value) {
  8188. return data.indexOfName(value);
  8189. }) : data.indexOfName(payload.name);
  8190. }
  8191. }
  8192. /**
  8193. * Enable property storage to any host object.
  8194. * Notice: Serialization is not supported.
  8195. *
  8196. * For example:
  8197. * let inner = zrUitl.makeInner();
  8198. *
  8199. * function some1(hostObj) {
  8200. * inner(hostObj).someProperty = 1212;
  8201. * ...
  8202. * }
  8203. * function some2() {
  8204. * let fields = inner(this);
  8205. * fields.someProperty1 = 1212;
  8206. * fields.someProperty2 = 'xx';
  8207. * ...
  8208. * }
  8209. *
  8210. * @return {Function}
  8211. */
  8212. function makeInner() {
  8213. var key = '__ec_inner_' + innerUniqueIndex++;
  8214. return function (hostObj) {
  8215. return hostObj[key] || (hostObj[key] = {});
  8216. };
  8217. }
  8218. var innerUniqueIndex = getRandomIdBase();
  8219. /**
  8220. * The same behavior as `component.getReferringComponents`.
  8221. */
  8222. function parseFinder(ecModel, finderInput, opt) {
  8223. var _a = preParseFinder(finderInput, opt),
  8224. mainTypeSpecified = _a.mainTypeSpecified,
  8225. queryOptionMap = _a.queryOptionMap,
  8226. others = _a.others;
  8227. var result = others;
  8228. var defaultMainType = opt ? opt.defaultMainType : null;
  8229. if (!mainTypeSpecified && defaultMainType) {
  8230. queryOptionMap.set(defaultMainType, {});
  8231. }
  8232. queryOptionMap.each(function (queryOption, mainType) {
  8233. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8234. useDefault: defaultMainType === mainType,
  8235. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8236. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8237. });
  8238. result[mainType + 'Models'] = queryResult.models;
  8239. result[mainType + 'Model'] = queryResult.models[0];
  8240. });
  8241. return result;
  8242. }
  8243. function preParseFinder(finderInput, opt) {
  8244. var finder;
  8245. if (isString(finderInput)) {
  8246. var obj = {};
  8247. obj[finderInput + 'Index'] = 0;
  8248. finder = obj;
  8249. } else {
  8250. finder = finderInput;
  8251. }
  8252. var queryOptionMap = createHashMap();
  8253. var others = {};
  8254. var mainTypeSpecified = false;
  8255. each(finder, function (value, key) {
  8256. // Exclude 'dataIndex' and other illgal keys.
  8257. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8258. others[key] = value;
  8259. return;
  8260. }
  8261. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8262. var mainType = parsedKey[1];
  8263. var queryType = (parsedKey[2] || '').toLowerCase();
  8264. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8265. return;
  8266. }
  8267. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8268. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8269. queryOption[queryType] = value;
  8270. });
  8271. return {
  8272. mainTypeSpecified: mainTypeSpecified,
  8273. queryOptionMap: queryOptionMap,
  8274. others: others
  8275. };
  8276. }
  8277. var SINGLE_REFERRING = {
  8278. useDefault: true,
  8279. enableAll: false,
  8280. enableNone: false
  8281. };
  8282. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8283. opt = opt || SINGLE_REFERRING;
  8284. var indexOption = userOption.index;
  8285. var idOption = userOption.id;
  8286. var nameOption = userOption.name;
  8287. var result = {
  8288. models: null,
  8289. specified: indexOption != null || idOption != null || nameOption != null
  8290. };
  8291. if (!result.specified) {
  8292. // Use the first as default if `useDefault`.
  8293. var firstCmpt = void 0;
  8294. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8295. return result;
  8296. }
  8297. if (indexOption === 'none' || indexOption === false) {
  8298. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8299. result.models = [];
  8300. return result;
  8301. }
  8302. // `queryComponents` will return all components if
  8303. // both all of index/id/name are null/undefined.
  8304. if (indexOption === 'all') {
  8305. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8306. indexOption = idOption = nameOption = null;
  8307. }
  8308. result.models = ecModel.queryComponents({
  8309. mainType: mainType,
  8310. index: indexOption,
  8311. id: idOption,
  8312. name: nameOption
  8313. });
  8314. return result;
  8315. }
  8316. function setAttribute(dom, key, value) {
  8317. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8318. }
  8319. function getAttribute(dom, key) {
  8320. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8321. }
  8322. /**
  8323. * Interpolate raw values of a series with percent
  8324. *
  8325. * @param data data
  8326. * @param labelModel label model of the text element
  8327. * @param sourceValue start value. May be null/undefined when init.
  8328. * @param targetValue end value
  8329. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8330. * @return interpolated values
  8331. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8332. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8333. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8334. * Other cases do not supported.
  8335. */
  8336. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8337. var isAutoPrecision = precision == null || precision === 'auto';
  8338. if (targetValue == null) {
  8339. return targetValue;
  8340. }
  8341. if (isNumber(targetValue)) {
  8342. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8343. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8344. } else if (isString(targetValue)) {
  8345. return percent < 1 ? sourceValue : targetValue;
  8346. } else {
  8347. var interpolated = [];
  8348. var leftArr = sourceValue;
  8349. var rightArr = targetValue;
  8350. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8351. for (var i = 0; i < length_1; ++i) {
  8352. var info = data.getDimensionInfo(i);
  8353. // Don't interpolate ordinal dims
  8354. if (info && info.type === 'ordinal') {
  8355. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8356. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8357. } else {
  8358. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8359. var rightVal = rightArr[i];
  8360. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8361. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8362. }
  8363. }
  8364. return interpolated;
  8365. }
  8366. }
  8367. var TYPE_DELIMITER = '.';
  8368. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8369. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8370. /**
  8371. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8372. * @public
  8373. */
  8374. function parseClassType(componentType) {
  8375. var ret = {
  8376. main: '',
  8377. sub: ''
  8378. };
  8379. if (componentType) {
  8380. var typeArr = componentType.split(TYPE_DELIMITER);
  8381. ret.main = typeArr[0] || '';
  8382. ret.sub = typeArr[1] || '';
  8383. }
  8384. return ret;
  8385. }
  8386. /**
  8387. * @public
  8388. */
  8389. function checkClassType(componentType) {
  8390. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8391. }
  8392. function isExtendedClass(clz) {
  8393. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8394. }
  8395. /**
  8396. * Implements `ExtendableConstructor` for `rootClz`.
  8397. *
  8398. * @usage
  8399. * ```ts
  8400. * class Xxx {}
  8401. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8402. * enableClassExtend(Xxx as XxxConstructor);
  8403. * ```
  8404. */
  8405. function enableClassExtend(rootClz, mandatoryMethods) {
  8406. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8407. rootClz.extend = function (proto) {
  8408. if ("development" !== 'production') {
  8409. each(mandatoryMethods, function (method) {
  8410. if (!proto[method]) {
  8411. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8412. }
  8413. });
  8414. }
  8415. var superClass = this;
  8416. var ExtendedClass;
  8417. if (isESClass(superClass)) {
  8418. ExtendedClass = /** @class */function (_super) {
  8419. __extends(class_1, _super);
  8420. function class_1() {
  8421. return _super.apply(this, arguments) || this;
  8422. }
  8423. return class_1;
  8424. }(superClass);
  8425. } else {
  8426. // For backward compat, we both support ts class inheritance and this
  8427. // "extend" approach.
  8428. // The constructor should keep the same behavior as ts class inheritance:
  8429. // If this constructor/$constructor is not declared, auto invoke the super
  8430. // constructor.
  8431. // If this constructor/$constructor is declared, it is responsible for
  8432. // calling the super constructor.
  8433. ExtendedClass = function () {
  8434. (proto.$constructor || superClass).apply(this, arguments);
  8435. };
  8436. inherits(ExtendedClass, this);
  8437. }
  8438. extend(ExtendedClass.prototype, proto);
  8439. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8440. ExtendedClass.extend = this.extend;
  8441. ExtendedClass.superCall = superCall;
  8442. ExtendedClass.superApply = superApply;
  8443. ExtendedClass.superClass = superClass;
  8444. return ExtendedClass;
  8445. };
  8446. }
  8447. function isESClass(fn) {
  8448. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8449. }
  8450. /**
  8451. * A work around to both support ts extend and this extend mechanism.
  8452. * on sub-class.
  8453. * @usage
  8454. * ```ts
  8455. * class Component { ... }
  8456. * classUtil.enableClassExtend(Component);
  8457. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8458. *
  8459. * class Series extends Component { ... }
  8460. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8461. * Component.markExtend(Series);
  8462. * ```
  8463. */
  8464. function mountExtend(SubClz, SupperClz) {
  8465. SubClz.extend = SupperClz.extend;
  8466. }
  8467. // A random offset.
  8468. var classBase = Math.round(Math.random() * 10);
  8469. /**
  8470. * Implements `CheckableConstructor` for `target`.
  8471. * Can not use instanceof, consider different scope by
  8472. * cross domain or es module import in ec extensions.
  8473. * Mount a method "isInstance()" to Clz.
  8474. *
  8475. * @usage
  8476. * ```ts
  8477. * class Xxx {}
  8478. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8479. * enableClassCheck(Xxx as XxxConstructor)
  8480. * ```
  8481. */
  8482. function enableClassCheck(target) {
  8483. var classAttr = ['__\0is_clz', classBase++].join('_');
  8484. target.prototype[classAttr] = true;
  8485. if ("development" !== 'production') {
  8486. assert(!target.isInstance, 'The method "is" can not be defined.');
  8487. }
  8488. target.isInstance = function (obj) {
  8489. return !!(obj && obj[classAttr]);
  8490. };
  8491. }
  8492. // superCall should have class info, which can not be fetched from 'this'.
  8493. // Consider this case:
  8494. // class A has method f,
  8495. // class B inherits class A, overrides method f, f call superApply('f'),
  8496. // class C inherits class B, does not override method f,
  8497. // then when method of class C is called, dead loop occurred.
  8498. function superCall(context, methodName) {
  8499. var args = [];
  8500. for (var _i = 2; _i < arguments.length; _i++) {
  8501. args[_i - 2] = arguments[_i];
  8502. }
  8503. return this.superClass.prototype[methodName].apply(context, args);
  8504. }
  8505. function superApply(context, methodName, args) {
  8506. return this.superClass.prototype[methodName].apply(context, args);
  8507. }
  8508. /**
  8509. * Implements `ClassManager` for `target`
  8510. *
  8511. * @usage
  8512. * ```ts
  8513. * class Xxx {}
  8514. * type XxxConstructor = typeof Xxx & ClassManager
  8515. * enableClassManagement(Xxx as XxxConstructor);
  8516. * ```
  8517. */
  8518. function enableClassManagement(target) {
  8519. /**
  8520. * Component model classes
  8521. * key: componentType,
  8522. * value:
  8523. * componentClass, when componentType is 'a'
  8524. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8525. */
  8526. var storage = {};
  8527. target.registerClass = function (clz) {
  8528. // `type` should not be a "instance member".
  8529. // If using TS class, should better declared as `static type = 'series.pie'`.
  8530. // otherwise users have to mount `type` on prototype manually.
  8531. // For backward compat and enable instance visit type via `this.type`,
  8532. // we still support fetch `type` from prototype.
  8533. var componentFullType = clz.type || clz.prototype.type;
  8534. if (componentFullType) {
  8535. checkClassType(componentFullType);
  8536. // If only static type declared, we assign it to prototype mandatorily.
  8537. clz.prototype.type = componentFullType;
  8538. var componentTypeInfo = parseClassType(componentFullType);
  8539. if (!componentTypeInfo.sub) {
  8540. if ("development" !== 'production') {
  8541. if (storage[componentTypeInfo.main]) {
  8542. console.warn(componentTypeInfo.main + ' exists.');
  8543. }
  8544. }
  8545. storage[componentTypeInfo.main] = clz;
  8546. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8547. var container = makeContainer(componentTypeInfo);
  8548. container[componentTypeInfo.sub] = clz;
  8549. }
  8550. }
  8551. return clz;
  8552. };
  8553. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8554. var clz = storage[mainType];
  8555. if (clz && clz[IS_CONTAINER]) {
  8556. clz = subType ? clz[subType] : null;
  8557. }
  8558. if (throwWhenNotFound && !clz) {
  8559. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8560. }
  8561. return clz;
  8562. };
  8563. target.getClassesByMainType = function (componentType) {
  8564. var componentTypeInfo = parseClassType(componentType);
  8565. var result = [];
  8566. var obj = storage[componentTypeInfo.main];
  8567. if (obj && obj[IS_CONTAINER]) {
  8568. each(obj, function (o, type) {
  8569. type !== IS_CONTAINER && result.push(o);
  8570. });
  8571. } else {
  8572. result.push(obj);
  8573. }
  8574. return result;
  8575. };
  8576. target.hasClass = function (componentType) {
  8577. // Just consider componentType.main.
  8578. var componentTypeInfo = parseClassType(componentType);
  8579. return !!storage[componentTypeInfo.main];
  8580. };
  8581. /**
  8582. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8583. */
  8584. target.getAllClassMainTypes = function () {
  8585. var types = [];
  8586. each(storage, function (obj, type) {
  8587. types.push(type);
  8588. });
  8589. return types;
  8590. };
  8591. /**
  8592. * If a main type is container and has sub types
  8593. */
  8594. target.hasSubTypes = function (componentType) {
  8595. var componentTypeInfo = parseClassType(componentType);
  8596. var obj = storage[componentTypeInfo.main];
  8597. return obj && obj[IS_CONTAINER];
  8598. };
  8599. function makeContainer(componentTypeInfo) {
  8600. var container = storage[componentTypeInfo.main];
  8601. if (!container || !container[IS_CONTAINER]) {
  8602. container = storage[componentTypeInfo.main] = {};
  8603. container[IS_CONTAINER] = true;
  8604. }
  8605. return container;
  8606. }
  8607. }
  8608. // /**
  8609. // * @param {string|Array.<string>} properties
  8610. // */
  8611. // export function setReadOnly(obj, properties) {
  8612. // FIXME It seems broken in IE8 simulation of IE11
  8613. // if (!zrUtil.isArray(properties)) {
  8614. // properties = properties != null ? [properties] : [];
  8615. // }
  8616. // zrUtil.each(properties, function (prop) {
  8617. // let value = obj[prop];
  8618. // Object.defineProperty
  8619. // && Object.defineProperty(obj, prop, {
  8620. // value: value, writable: false
  8621. // });
  8622. // zrUtil.isArray(obj[prop])
  8623. // && Object.freeze
  8624. // && Object.freeze(obj[prop]);
  8625. // });
  8626. // }
  8627. function makeStyleMapper(properties, ignoreParent) {
  8628. // Normalize
  8629. for (var i = 0; i < properties.length; i++) {
  8630. if (!properties[i][1]) {
  8631. properties[i][1] = properties[i][0];
  8632. }
  8633. }
  8634. ignoreParent = ignoreParent || false;
  8635. return function (model, excludes, includes) {
  8636. var style = {};
  8637. for (var i = 0; i < properties.length; i++) {
  8638. var propName = properties[i][1];
  8639. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8640. continue;
  8641. }
  8642. var val = model.getShallow(propName, ignoreParent);
  8643. if (val != null) {
  8644. style[properties[i][0]] = val;
  8645. }
  8646. }
  8647. // TODO Text or image?
  8648. return style;
  8649. };
  8650. }
  8651. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor']
  8652. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8653. // So do not transfer decal directly.
  8654. ];
  8655. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8656. var AreaStyleMixin = /** @class */function () {
  8657. function AreaStyleMixin() {}
  8658. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8659. return getAreaStyle(this, excludes, includes);
  8660. };
  8661. return AreaStyleMixin;
  8662. }();
  8663. var globalImageCache = new LRU(50);
  8664. function findExistImage(newImageOrSrc) {
  8665. if (typeof newImageOrSrc === 'string') {
  8666. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8667. return cachedImgObj && cachedImgObj.image;
  8668. }
  8669. else {
  8670. return newImageOrSrc;
  8671. }
  8672. }
  8673. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8674. if (!newImageOrSrc) {
  8675. return image;
  8676. }
  8677. else if (typeof newImageOrSrc === 'string') {
  8678. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8679. return image;
  8680. }
  8681. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8682. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8683. if (cachedImgObj) {
  8684. image = cachedImgObj.image;
  8685. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8686. }
  8687. else {
  8688. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8689. image.__zrImageSrc = newImageOrSrc;
  8690. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8691. image: image,
  8692. pending: [pendingWrap]
  8693. });
  8694. }
  8695. return image;
  8696. }
  8697. else {
  8698. return newImageOrSrc;
  8699. }
  8700. }
  8701. function imageOnLoad() {
  8702. var cachedImgObj = this.__cachedImgObj;
  8703. this.onload = this.onerror = this.__cachedImgObj = null;
  8704. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8705. var pendingWrap = cachedImgObj.pending[i];
  8706. var cb = pendingWrap.cb;
  8707. cb && cb(this, pendingWrap.cbPayload);
  8708. pendingWrap.hostEl.dirty();
  8709. }
  8710. cachedImgObj.pending.length = 0;
  8711. }
  8712. function isImageReady(image) {
  8713. return image && image.width && image.height;
  8714. }
  8715. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8716. function truncateText(text, containerWidth, font, ellipsis, options) {
  8717. if (!containerWidth) {
  8718. return '';
  8719. }
  8720. var textLines = (text + '').split('\n');
  8721. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8722. for (var i = 0, len = textLines.length; i < len; i++) {
  8723. textLines[i] = truncateSingleLine(textLines[i], options);
  8724. }
  8725. return textLines.join('\n');
  8726. }
  8727. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8728. options = options || {};
  8729. var preparedOpts = extend({}, options);
  8730. preparedOpts.font = font;
  8731. ellipsis = retrieve2(ellipsis, '...');
  8732. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8733. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8734. preparedOpts.cnCharWidth = getWidth('国', font);
  8735. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8736. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8737. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8738. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8739. contentWidth -= ascCharWidth;
  8740. }
  8741. var ellipsisWidth = getWidth(ellipsis, font);
  8742. if (ellipsisWidth > contentWidth) {
  8743. ellipsis = '';
  8744. ellipsisWidth = 0;
  8745. }
  8746. contentWidth = containerWidth - ellipsisWidth;
  8747. preparedOpts.ellipsis = ellipsis;
  8748. preparedOpts.ellipsisWidth = ellipsisWidth;
  8749. preparedOpts.contentWidth = contentWidth;
  8750. preparedOpts.containerWidth = containerWidth;
  8751. return preparedOpts;
  8752. }
  8753. function truncateSingleLine(textLine, options) {
  8754. var containerWidth = options.containerWidth;
  8755. var font = options.font;
  8756. var contentWidth = options.contentWidth;
  8757. if (!containerWidth) {
  8758. return '';
  8759. }
  8760. var lineWidth = getWidth(textLine, font);
  8761. if (lineWidth <= containerWidth) {
  8762. return textLine;
  8763. }
  8764. for (var j = 0;; j++) {
  8765. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8766. textLine += options.ellipsis;
  8767. break;
  8768. }
  8769. var subLength = j === 0
  8770. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8771. : lineWidth > 0
  8772. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8773. : 0;
  8774. textLine = textLine.substr(0, subLength);
  8775. lineWidth = getWidth(textLine, font);
  8776. }
  8777. if (textLine === '') {
  8778. textLine = options.placeholder;
  8779. }
  8780. return textLine;
  8781. }
  8782. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8783. var width = 0;
  8784. var i = 0;
  8785. for (var len = text.length; i < len && width < contentWidth; i++) {
  8786. var charCode = text.charCodeAt(i);
  8787. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8788. }
  8789. return i;
  8790. }
  8791. function parsePlainText(text, style) {
  8792. text != null && (text += '');
  8793. var overflow = style.overflow;
  8794. var padding = style.padding;
  8795. var font = style.font;
  8796. var truncate = overflow === 'truncate';
  8797. var calculatedLineHeight = getLineHeight(font);
  8798. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8799. var bgColorDrawn = !!(style.backgroundColor);
  8800. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8801. var width = style.width;
  8802. var lines;
  8803. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8804. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8805. }
  8806. else {
  8807. lines = text ? text.split('\n') : [];
  8808. }
  8809. var contentHeight = lines.length * lineHeight;
  8810. var height = retrieve2(style.height, contentHeight);
  8811. if (contentHeight > height && truncateLineOverflow) {
  8812. var lineCount = Math.floor(height / lineHeight);
  8813. lines = lines.slice(0, lineCount);
  8814. }
  8815. if (text && truncate && width != null) {
  8816. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8817. minChar: style.truncateMinChar,
  8818. placeholder: style.placeholder
  8819. });
  8820. for (var i = 0; i < lines.length; i++) {
  8821. lines[i] = truncateSingleLine(lines[i], options);
  8822. }
  8823. }
  8824. var outerHeight = height;
  8825. var contentWidth = 0;
  8826. for (var i = 0; i < lines.length; i++) {
  8827. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8828. }
  8829. if (width == null) {
  8830. width = contentWidth;
  8831. }
  8832. var outerWidth = contentWidth;
  8833. if (padding) {
  8834. outerHeight += padding[0] + padding[2];
  8835. outerWidth += padding[1] + padding[3];
  8836. width += padding[1] + padding[3];
  8837. }
  8838. if (bgColorDrawn) {
  8839. outerWidth = width;
  8840. }
  8841. return {
  8842. lines: lines,
  8843. height: height,
  8844. outerWidth: outerWidth,
  8845. outerHeight: outerHeight,
  8846. lineHeight: lineHeight,
  8847. calculatedLineHeight: calculatedLineHeight,
  8848. contentWidth: contentWidth,
  8849. contentHeight: contentHeight,
  8850. width: width
  8851. };
  8852. }
  8853. var RichTextToken = (function () {
  8854. function RichTextToken() {
  8855. }
  8856. return RichTextToken;
  8857. }());
  8858. var RichTextLine = (function () {
  8859. function RichTextLine(tokens) {
  8860. this.tokens = [];
  8861. if (tokens) {
  8862. this.tokens = tokens;
  8863. }
  8864. }
  8865. return RichTextLine;
  8866. }());
  8867. var RichTextContentBlock = (function () {
  8868. function RichTextContentBlock() {
  8869. this.width = 0;
  8870. this.height = 0;
  8871. this.contentWidth = 0;
  8872. this.contentHeight = 0;
  8873. this.outerWidth = 0;
  8874. this.outerHeight = 0;
  8875. this.lines = [];
  8876. }
  8877. return RichTextContentBlock;
  8878. }());
  8879. function parseRichText(text, style) {
  8880. var contentBlock = new RichTextContentBlock();
  8881. text != null && (text += '');
  8882. if (!text) {
  8883. return contentBlock;
  8884. }
  8885. var topWidth = style.width;
  8886. var topHeight = style.height;
  8887. var overflow = style.overflow;
  8888. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8889. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8890. : null;
  8891. var lastIndex = STYLE_REG.lastIndex = 0;
  8892. var result;
  8893. while ((result = STYLE_REG.exec(text)) != null) {
  8894. var matchedIndex = result.index;
  8895. if (matchedIndex > lastIndex) {
  8896. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8897. }
  8898. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8899. lastIndex = STYLE_REG.lastIndex;
  8900. }
  8901. if (lastIndex < text.length) {
  8902. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8903. }
  8904. var pendingList = [];
  8905. var calculatedHeight = 0;
  8906. var calculatedWidth = 0;
  8907. var stlPadding = style.padding;
  8908. var truncate = overflow === 'truncate';
  8909. var truncateLine = style.lineOverflow === 'truncate';
  8910. function finishLine(line, lineWidth, lineHeight) {
  8911. line.width = lineWidth;
  8912. line.lineHeight = lineHeight;
  8913. calculatedHeight += lineHeight;
  8914. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8915. }
  8916. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8917. var line = contentBlock.lines[i];
  8918. var lineHeight = 0;
  8919. var lineWidth = 0;
  8920. for (var j = 0; j < line.tokens.length; j++) {
  8921. var token = line.tokens[j];
  8922. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8923. var textPadding = token.textPadding = tokenStyle.padding;
  8924. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8925. var font = token.font = tokenStyle.font || style.font;
  8926. token.contentHeight = getLineHeight(font);
  8927. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8928. token.innerHeight = tokenHeight;
  8929. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8930. token.height = tokenHeight;
  8931. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8932. token.align = tokenStyle && tokenStyle.align || style.align;
  8933. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8934. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8935. if (j > 0) {
  8936. line.tokens = line.tokens.slice(0, j);
  8937. finishLine(line, lineWidth, lineHeight);
  8938. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8939. }
  8940. else {
  8941. contentBlock.lines = contentBlock.lines.slice(0, i);
  8942. }
  8943. break outer;
  8944. }
  8945. var styleTokenWidth = tokenStyle.width;
  8946. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8947. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8948. token.percentWidth = styleTokenWidth;
  8949. pendingList.push(token);
  8950. token.contentWidth = getWidth(token.text, font);
  8951. }
  8952. else {
  8953. if (tokenWidthNotSpecified) {
  8954. var textBackgroundColor = tokenStyle.backgroundColor;
  8955. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8956. if (bgImg) {
  8957. bgImg = findExistImage(bgImg);
  8958. if (isImageReady(bgImg)) {
  8959. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8960. }
  8961. }
  8962. }
  8963. var remainTruncWidth = truncate && topWidth != null
  8964. ? topWidth - lineWidth : null;
  8965. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8966. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8967. token.text = '';
  8968. token.width = token.contentWidth = 0;
  8969. }
  8970. else {
  8971. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8972. token.width = token.contentWidth = getWidth(token.text, font);
  8973. }
  8974. }
  8975. else {
  8976. token.contentWidth = getWidth(token.text, font);
  8977. }
  8978. }
  8979. token.width += paddingH;
  8980. lineWidth += token.width;
  8981. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8982. }
  8983. finishLine(line, lineWidth, lineHeight);
  8984. }
  8985. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8986. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8987. contentBlock.contentHeight = calculatedHeight;
  8988. contentBlock.contentWidth = calculatedWidth;
  8989. if (stlPadding) {
  8990. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  8991. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  8992. }
  8993. for (var i = 0; i < pendingList.length; i++) {
  8994. var token = pendingList[i];
  8995. var percentWidth = token.percentWidth;
  8996. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  8997. }
  8998. return contentBlock;
  8999. }
  9000. function pushTokens(block, str, style, wrapInfo, styleName) {
  9001. var isEmptyStr = str === '';
  9002. var tokenStyle = styleName && style.rich[styleName] || {};
  9003. var lines = block.lines;
  9004. var font = tokenStyle.font || style.font;
  9005. var newLine = false;
  9006. var strLines;
  9007. var linesWidths;
  9008. if (wrapInfo) {
  9009. var tokenPadding = tokenStyle.padding;
  9010. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9011. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9012. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9013. if (lines.length > 0) {
  9014. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9015. strLines = str.split('\n');
  9016. newLine = true;
  9017. }
  9018. }
  9019. wrapInfo.accumWidth = outerWidth_1;
  9020. }
  9021. else {
  9022. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9023. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9024. linesWidths = res.linesWidths;
  9025. strLines = res.lines;
  9026. }
  9027. }
  9028. else {
  9029. strLines = str.split('\n');
  9030. }
  9031. for (var i = 0; i < strLines.length; i++) {
  9032. var text = strLines[i];
  9033. var token = new RichTextToken();
  9034. token.styleName = styleName;
  9035. token.text = text;
  9036. token.isLineHolder = !text && !isEmptyStr;
  9037. if (typeof tokenStyle.width === 'number') {
  9038. token.width = tokenStyle.width;
  9039. }
  9040. else {
  9041. token.width = linesWidths
  9042. ? linesWidths[i]
  9043. : getWidth(text, font);
  9044. }
  9045. if (!i && !newLine) {
  9046. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9047. var tokensLen = tokens.length;
  9048. (tokensLen === 1 && tokens[0].isLineHolder)
  9049. ? (tokens[0] = token)
  9050. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9051. }
  9052. else {
  9053. lines.push(new RichTextLine([token]));
  9054. }
  9055. }
  9056. }
  9057. function isAlphabeticLetter(ch) {
  9058. var code = ch.charCodeAt(0);
  9059. return code >= 0x20 && code <= 0x24F
  9060. || code >= 0x370 && code <= 0x10FF
  9061. || code >= 0x1200 && code <= 0x13FF
  9062. || code >= 0x1E00 && code <= 0x206F;
  9063. }
  9064. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9065. obj[ch] = true;
  9066. return obj;
  9067. }, {});
  9068. function isWordBreakChar(ch) {
  9069. if (isAlphabeticLetter(ch)) {
  9070. if (breakCharMap[ch]) {
  9071. return true;
  9072. }
  9073. return false;
  9074. }
  9075. return true;
  9076. }
  9077. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9078. var lines = [];
  9079. var linesWidths = [];
  9080. var line = '';
  9081. var currentWord = '';
  9082. var currentWordWidth = 0;
  9083. var accumWidth = 0;
  9084. for (var i = 0; i < text.length; i++) {
  9085. var ch = text.charAt(i);
  9086. if (ch === '\n') {
  9087. if (currentWord) {
  9088. line += currentWord;
  9089. accumWidth += currentWordWidth;
  9090. }
  9091. lines.push(line);
  9092. linesWidths.push(accumWidth);
  9093. line = '';
  9094. currentWord = '';
  9095. currentWordWidth = 0;
  9096. accumWidth = 0;
  9097. continue;
  9098. }
  9099. var chWidth = getWidth(ch, font);
  9100. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9101. if (!lines.length
  9102. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9103. : accumWidth + chWidth > lineWidth) {
  9104. if (!accumWidth) {
  9105. if (inWord) {
  9106. lines.push(currentWord);
  9107. linesWidths.push(currentWordWidth);
  9108. currentWord = ch;
  9109. currentWordWidth = chWidth;
  9110. }
  9111. else {
  9112. lines.push(ch);
  9113. linesWidths.push(chWidth);
  9114. }
  9115. }
  9116. else if (line || currentWord) {
  9117. if (inWord) {
  9118. if (!line) {
  9119. line = currentWord;
  9120. currentWord = '';
  9121. currentWordWidth = 0;
  9122. accumWidth = currentWordWidth;
  9123. }
  9124. lines.push(line);
  9125. linesWidths.push(accumWidth - currentWordWidth);
  9126. currentWord += ch;
  9127. currentWordWidth += chWidth;
  9128. line = '';
  9129. accumWidth = currentWordWidth;
  9130. }
  9131. else {
  9132. if (currentWord) {
  9133. line += currentWord;
  9134. currentWord = '';
  9135. currentWordWidth = 0;
  9136. }
  9137. lines.push(line);
  9138. linesWidths.push(accumWidth);
  9139. line = ch;
  9140. accumWidth = chWidth;
  9141. }
  9142. }
  9143. continue;
  9144. }
  9145. accumWidth += chWidth;
  9146. if (inWord) {
  9147. currentWord += ch;
  9148. currentWordWidth += chWidth;
  9149. }
  9150. else {
  9151. if (currentWord) {
  9152. line += currentWord;
  9153. currentWord = '';
  9154. currentWordWidth = 0;
  9155. }
  9156. line += ch;
  9157. }
  9158. }
  9159. if (!lines.length && !line) {
  9160. line = text;
  9161. currentWord = '';
  9162. currentWordWidth = 0;
  9163. }
  9164. if (currentWord) {
  9165. line += currentWord;
  9166. }
  9167. if (line) {
  9168. lines.push(line);
  9169. linesWidths.push(accumWidth);
  9170. }
  9171. if (lines.length === 1) {
  9172. accumWidth += lastAccumWidth;
  9173. }
  9174. return {
  9175. accumWidth: accumWidth,
  9176. lines: lines,
  9177. linesWidths: linesWidths
  9178. };
  9179. }
  9180. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9181. var DEFAULT_COMMON_STYLE = {
  9182. shadowBlur: 0,
  9183. shadowOffsetX: 0,
  9184. shadowOffsetY: 0,
  9185. shadowColor: '#000',
  9186. opacity: 1,
  9187. blend: 'source-over'
  9188. };
  9189. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9190. style: {
  9191. shadowBlur: true,
  9192. shadowOffsetX: true,
  9193. shadowOffsetY: true,
  9194. shadowColor: true,
  9195. opacity: true
  9196. }
  9197. };
  9198. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9199. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9200. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9201. var Displayable = (function (_super) {
  9202. __extends(Displayable, _super);
  9203. function Displayable(props) {
  9204. return _super.call(this, props) || this;
  9205. }
  9206. Displayable.prototype._init = function (props) {
  9207. var keysArr = keys(props);
  9208. for (var i = 0; i < keysArr.length; i++) {
  9209. var key = keysArr[i];
  9210. if (key === 'style') {
  9211. this.useStyle(props[key]);
  9212. }
  9213. else {
  9214. _super.prototype.attrKV.call(this, key, props[key]);
  9215. }
  9216. }
  9217. if (!this.style) {
  9218. this.useStyle({});
  9219. }
  9220. };
  9221. Displayable.prototype.beforeBrush = function () { };
  9222. Displayable.prototype.afterBrush = function () { };
  9223. Displayable.prototype.innerBeforeBrush = function () { };
  9224. Displayable.prototype.innerAfterBrush = function () { };
  9225. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9226. var m = this.transform;
  9227. if (this.ignore
  9228. || this.invisible
  9229. || this.style.opacity === 0
  9230. || (this.culling
  9231. && isDisplayableCulled(this, viewWidth, viewHeight))
  9232. || (m && !m[0] && !m[3])) {
  9233. return false;
  9234. }
  9235. if (considerClipPath && this.__clipPaths) {
  9236. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9237. if (this.__clipPaths[i].isZeroArea()) {
  9238. return false;
  9239. }
  9240. }
  9241. }
  9242. if (considerAncestors && this.parent) {
  9243. var parent_1 = this.parent;
  9244. while (parent_1) {
  9245. if (parent_1.ignore) {
  9246. return false;
  9247. }
  9248. parent_1 = parent_1.parent;
  9249. }
  9250. }
  9251. return true;
  9252. };
  9253. Displayable.prototype.contain = function (x, y) {
  9254. return this.rectContain(x, y);
  9255. };
  9256. Displayable.prototype.traverse = function (cb, context) {
  9257. cb.call(context, this);
  9258. };
  9259. Displayable.prototype.rectContain = function (x, y) {
  9260. var coord = this.transformCoordToLocal(x, y);
  9261. var rect = this.getBoundingRect();
  9262. return rect.contain(coord[0], coord[1]);
  9263. };
  9264. Displayable.prototype.getPaintRect = function () {
  9265. var rect = this._paintRect;
  9266. if (!this._paintRect || this.__dirty) {
  9267. var transform = this.transform;
  9268. var elRect = this.getBoundingRect();
  9269. var style = this.style;
  9270. var shadowSize = style.shadowBlur || 0;
  9271. var shadowOffsetX = style.shadowOffsetX || 0;
  9272. var shadowOffsetY = style.shadowOffsetY || 0;
  9273. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9274. if (transform) {
  9275. BoundingRect.applyTransform(rect, elRect, transform);
  9276. }
  9277. else {
  9278. rect.copy(elRect);
  9279. }
  9280. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9281. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9282. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9283. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9284. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9285. }
  9286. var tolerance = this.dirtyRectTolerance;
  9287. if (!rect.isZero()) {
  9288. rect.x = Math.floor(rect.x - tolerance);
  9289. rect.y = Math.floor(rect.y - tolerance);
  9290. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9291. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9292. }
  9293. }
  9294. return rect;
  9295. };
  9296. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9297. if (paintRect) {
  9298. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9299. this._prevPaintRect.copy(paintRect);
  9300. }
  9301. else {
  9302. this._prevPaintRect = null;
  9303. }
  9304. };
  9305. Displayable.prototype.getPrevPaintRect = function () {
  9306. return this._prevPaintRect;
  9307. };
  9308. Displayable.prototype.animateStyle = function (loop) {
  9309. return this.animate('style', loop);
  9310. };
  9311. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9312. if (targetKey === 'style') {
  9313. this.dirtyStyle();
  9314. }
  9315. else {
  9316. this.markRedraw();
  9317. }
  9318. };
  9319. Displayable.prototype.attrKV = function (key, value) {
  9320. if (key !== 'style') {
  9321. _super.prototype.attrKV.call(this, key, value);
  9322. }
  9323. else {
  9324. if (!this.style) {
  9325. this.useStyle(value);
  9326. }
  9327. else {
  9328. this.setStyle(value);
  9329. }
  9330. }
  9331. };
  9332. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9333. if (typeof keyOrObj === 'string') {
  9334. this.style[keyOrObj] = value;
  9335. }
  9336. else {
  9337. extend(this.style, keyOrObj);
  9338. }
  9339. this.dirtyStyle();
  9340. return this;
  9341. };
  9342. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9343. if (!notRedraw) {
  9344. this.markRedraw();
  9345. }
  9346. this.__dirty |= STYLE_CHANGED_BIT;
  9347. if (this._rect) {
  9348. this._rect = null;
  9349. }
  9350. };
  9351. Displayable.prototype.dirty = function () {
  9352. this.dirtyStyle();
  9353. };
  9354. Displayable.prototype.styleChanged = function () {
  9355. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9356. };
  9357. Displayable.prototype.styleUpdated = function () {
  9358. this.__dirty &= ~STYLE_CHANGED_BIT;
  9359. };
  9360. Displayable.prototype.createStyle = function (obj) {
  9361. return createObject(DEFAULT_COMMON_STYLE, obj);
  9362. };
  9363. Displayable.prototype.useStyle = function (obj) {
  9364. if (!obj[STYLE_MAGIC_KEY]) {
  9365. obj = this.createStyle(obj);
  9366. }
  9367. if (this.__inHover) {
  9368. this.__hoverStyle = obj;
  9369. }
  9370. else {
  9371. this.style = obj;
  9372. }
  9373. this.dirtyStyle();
  9374. };
  9375. Displayable.prototype.isStyleObject = function (obj) {
  9376. return obj[STYLE_MAGIC_KEY];
  9377. };
  9378. Displayable.prototype._innerSaveToNormal = function (toState) {
  9379. _super.prototype._innerSaveToNormal.call(this, toState);
  9380. var normalState = this._normalState;
  9381. if (toState.style && !normalState.style) {
  9382. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9383. }
  9384. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9385. };
  9386. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9387. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9388. var needsRestoreToNormal = !(state && keepCurrentStates);
  9389. var targetStyle;
  9390. if (state && state.style) {
  9391. if (transition) {
  9392. if (keepCurrentStates) {
  9393. targetStyle = state.style;
  9394. }
  9395. else {
  9396. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9397. this._mergeStyle(targetStyle, state.style);
  9398. }
  9399. }
  9400. else {
  9401. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9402. this._mergeStyle(targetStyle, state.style);
  9403. }
  9404. }
  9405. else if (needsRestoreToNormal) {
  9406. targetStyle = normalState.style;
  9407. }
  9408. if (targetStyle) {
  9409. if (transition) {
  9410. var sourceStyle = this.style;
  9411. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9412. if (needsRestoreToNormal) {
  9413. var changedKeys = keys(sourceStyle);
  9414. for (var i = 0; i < changedKeys.length; i++) {
  9415. var key = changedKeys[i];
  9416. if (key in targetStyle) {
  9417. targetStyle[key] = targetStyle[key];
  9418. this.style[key] = sourceStyle[key];
  9419. }
  9420. }
  9421. }
  9422. var targetKeys = keys(targetStyle);
  9423. for (var i = 0; i < targetKeys.length; i++) {
  9424. var key = targetKeys[i];
  9425. this.style[key] = this.style[key];
  9426. }
  9427. this._transitionState(stateName, {
  9428. style: targetStyle
  9429. }, animationCfg, this.getAnimationStyleProps());
  9430. }
  9431. else {
  9432. this.useStyle(targetStyle);
  9433. }
  9434. }
  9435. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9436. for (var i = 0; i < statesKeys.length; i++) {
  9437. var key = statesKeys[i];
  9438. if (state && state[key] != null) {
  9439. this[key] = state[key];
  9440. }
  9441. else if (needsRestoreToNormal) {
  9442. if (normalState[key] != null) {
  9443. this[key] = normalState[key];
  9444. }
  9445. }
  9446. }
  9447. };
  9448. Displayable.prototype._mergeStates = function (states) {
  9449. var mergedState = _super.prototype._mergeStates.call(this, states);
  9450. var mergedStyle;
  9451. for (var i = 0; i < states.length; i++) {
  9452. var state = states[i];
  9453. if (state.style) {
  9454. mergedStyle = mergedStyle || {};
  9455. this._mergeStyle(mergedStyle, state.style);
  9456. }
  9457. }
  9458. if (mergedStyle) {
  9459. mergedState.style = mergedStyle;
  9460. }
  9461. return mergedState;
  9462. };
  9463. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9464. extend(targetStyle, sourceStyle);
  9465. return targetStyle;
  9466. };
  9467. Displayable.prototype.getAnimationStyleProps = function () {
  9468. return DEFAULT_COMMON_ANIMATION_PROPS;
  9469. };
  9470. Displayable.initDefaultProps = (function () {
  9471. var dispProto = Displayable.prototype;
  9472. dispProto.type = 'displayable';
  9473. dispProto.invisible = false;
  9474. dispProto.z = 0;
  9475. dispProto.z2 = 0;
  9476. dispProto.zlevel = 0;
  9477. dispProto.culling = false;
  9478. dispProto.cursor = 'pointer';
  9479. dispProto.rectHover = false;
  9480. dispProto.incremental = false;
  9481. dispProto._rect = null;
  9482. dispProto.dirtyRectTolerance = 0;
  9483. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9484. })();
  9485. return Displayable;
  9486. }(Element));
  9487. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9488. var viewRect = new BoundingRect(0, 0, 0, 0);
  9489. function isDisplayableCulled(el, width, height) {
  9490. tmpRect$1.copy(el.getBoundingRect());
  9491. if (el.transform) {
  9492. tmpRect$1.applyTransform(el.transform);
  9493. }
  9494. viewRect.width = width;
  9495. viewRect.height = height;
  9496. return !tmpRect$1.intersect(viewRect);
  9497. }
  9498. var mathMin$1 = Math.min;
  9499. var mathMax$1 = Math.max;
  9500. var mathSin = Math.sin;
  9501. var mathCos = Math.cos;
  9502. var PI2 = Math.PI * 2;
  9503. var start = create();
  9504. var end = create();
  9505. var extremity = create();
  9506. function fromLine(x0, y0, x1, y1, min, max) {
  9507. min[0] = mathMin$1(x0, x1);
  9508. min[1] = mathMin$1(y0, y1);
  9509. max[0] = mathMax$1(x0, x1);
  9510. max[1] = mathMax$1(y0, y1);
  9511. }
  9512. var xDim = [];
  9513. var yDim = [];
  9514. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9515. var cubicExtrema$1 = cubicExtrema;
  9516. var cubicAt$1 = cubicAt;
  9517. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9518. min[0] = Infinity;
  9519. min[1] = Infinity;
  9520. max[0] = -Infinity;
  9521. max[1] = -Infinity;
  9522. for (var i = 0; i < n; i++) {
  9523. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9524. min[0] = mathMin$1(x, min[0]);
  9525. max[0] = mathMax$1(x, max[0]);
  9526. }
  9527. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9528. for (var i = 0; i < n; i++) {
  9529. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9530. min[1] = mathMin$1(y, min[1]);
  9531. max[1] = mathMax$1(y, max[1]);
  9532. }
  9533. min[0] = mathMin$1(x0, min[0]);
  9534. max[0] = mathMax$1(x0, max[0]);
  9535. min[0] = mathMin$1(x3, min[0]);
  9536. max[0] = mathMax$1(x3, max[0]);
  9537. min[1] = mathMin$1(y0, min[1]);
  9538. max[1] = mathMax$1(y0, max[1]);
  9539. min[1] = mathMin$1(y3, min[1]);
  9540. max[1] = mathMax$1(y3, max[1]);
  9541. }
  9542. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9543. var quadraticExtremum$1 = quadraticExtremum;
  9544. var quadraticAt$1 = quadraticAt;
  9545. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9546. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9547. var x = quadraticAt$1(x0, x1, x2, tx);
  9548. var y = quadraticAt$1(y0, y1, y2, ty);
  9549. min[0] = mathMin$1(x0, x2, x);
  9550. min[1] = mathMin$1(y0, y2, y);
  9551. max[0] = mathMax$1(x0, x2, x);
  9552. max[1] = mathMax$1(y0, y2, y);
  9553. }
  9554. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9555. var vec2Min = min;
  9556. var vec2Max = max;
  9557. var diff = Math.abs(startAngle - endAngle);
  9558. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9559. min$1[0] = x - rx;
  9560. min$1[1] = y - ry;
  9561. max$1[0] = x + rx;
  9562. max$1[1] = y + ry;
  9563. return;
  9564. }
  9565. start[0] = mathCos(startAngle) * rx + x;
  9566. start[1] = mathSin(startAngle) * ry + y;
  9567. end[0] = mathCos(endAngle) * rx + x;
  9568. end[1] = mathSin(endAngle) * ry + y;
  9569. vec2Min(min$1, start, end);
  9570. vec2Max(max$1, start, end);
  9571. startAngle = startAngle % (PI2);
  9572. if (startAngle < 0) {
  9573. startAngle = startAngle + PI2;
  9574. }
  9575. endAngle = endAngle % (PI2);
  9576. if (endAngle < 0) {
  9577. endAngle = endAngle + PI2;
  9578. }
  9579. if (startAngle > endAngle && !anticlockwise) {
  9580. endAngle += PI2;
  9581. }
  9582. else if (startAngle < endAngle && anticlockwise) {
  9583. startAngle += PI2;
  9584. }
  9585. if (anticlockwise) {
  9586. var tmp = endAngle;
  9587. endAngle = startAngle;
  9588. startAngle = tmp;
  9589. }
  9590. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9591. if (angle > startAngle) {
  9592. extremity[0] = mathCos(angle) * rx + x;
  9593. extremity[1] = mathSin(angle) * ry + y;
  9594. vec2Min(min$1, extremity, min$1);
  9595. vec2Max(max$1, extremity, max$1);
  9596. }
  9597. }
  9598. }
  9599. var CMD = {
  9600. M: 1,
  9601. L: 2,
  9602. C: 3,
  9603. Q: 4,
  9604. A: 5,
  9605. Z: 6,
  9606. R: 7
  9607. };
  9608. var tmpOutX = [];
  9609. var tmpOutY = [];
  9610. var min$1 = [];
  9611. var max$1 = [];
  9612. var min2 = [];
  9613. var max2 = [];
  9614. var mathMin$2 = Math.min;
  9615. var mathMax$2 = Math.max;
  9616. var mathCos$1 = Math.cos;
  9617. var mathSin$1 = Math.sin;
  9618. var mathAbs = Math.abs;
  9619. var PI = Math.PI;
  9620. var PI2$1 = PI * 2;
  9621. var hasTypedArray = typeof Float32Array !== 'undefined';
  9622. var tmpAngles = [];
  9623. function modPI2(radian) {
  9624. var n = Math.round(radian / PI * 1e8) / 1e8;
  9625. return (n % 2) * PI;
  9626. }
  9627. function normalizeArcAngles(angles, anticlockwise) {
  9628. var newStartAngle = modPI2(angles[0]);
  9629. if (newStartAngle < 0) {
  9630. newStartAngle += PI2$1;
  9631. }
  9632. var delta = newStartAngle - angles[0];
  9633. var newEndAngle = angles[1];
  9634. newEndAngle += delta;
  9635. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9636. newEndAngle = newStartAngle + PI2$1;
  9637. }
  9638. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9639. newEndAngle = newStartAngle - PI2$1;
  9640. }
  9641. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9642. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9643. }
  9644. else if (anticlockwise && newStartAngle < newEndAngle) {
  9645. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9646. }
  9647. angles[0] = newStartAngle;
  9648. angles[1] = newEndAngle;
  9649. }
  9650. var PathProxy = (function () {
  9651. function PathProxy(notSaveData) {
  9652. this.dpr = 1;
  9653. this._xi = 0;
  9654. this._yi = 0;
  9655. this._x0 = 0;
  9656. this._y0 = 0;
  9657. this._len = 0;
  9658. if (notSaveData) {
  9659. this._saveData = false;
  9660. }
  9661. if (this._saveData) {
  9662. this.data = [];
  9663. }
  9664. }
  9665. PathProxy.prototype.increaseVersion = function () {
  9666. this._version++;
  9667. };
  9668. PathProxy.prototype.getVersion = function () {
  9669. return this._version;
  9670. };
  9671. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9672. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9673. if (segmentIgnoreThreshold > 0) {
  9674. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9675. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9676. }
  9677. };
  9678. PathProxy.prototype.setDPR = function (dpr) {
  9679. this.dpr = dpr;
  9680. };
  9681. PathProxy.prototype.setContext = function (ctx) {
  9682. this._ctx = ctx;
  9683. };
  9684. PathProxy.prototype.getContext = function () {
  9685. return this._ctx;
  9686. };
  9687. PathProxy.prototype.beginPath = function () {
  9688. this._ctx && this._ctx.beginPath();
  9689. this.reset();
  9690. return this;
  9691. };
  9692. PathProxy.prototype.reset = function () {
  9693. if (this._saveData) {
  9694. this._len = 0;
  9695. }
  9696. if (this._pathSegLen) {
  9697. this._pathSegLen = null;
  9698. this._pathLen = 0;
  9699. }
  9700. this._version++;
  9701. };
  9702. PathProxy.prototype.moveTo = function (x, y) {
  9703. this._drawPendingPt();
  9704. this.addData(CMD.M, x, y);
  9705. this._ctx && this._ctx.moveTo(x, y);
  9706. this._x0 = x;
  9707. this._y0 = y;
  9708. this._xi = x;
  9709. this._yi = y;
  9710. return this;
  9711. };
  9712. PathProxy.prototype.lineTo = function (x, y) {
  9713. var dx = mathAbs(x - this._xi);
  9714. var dy = mathAbs(y - this._yi);
  9715. var exceedUnit = dx > this._ux || dy > this._uy;
  9716. this.addData(CMD.L, x, y);
  9717. if (this._ctx && exceedUnit) {
  9718. this._ctx.lineTo(x, y);
  9719. }
  9720. if (exceedUnit) {
  9721. this._xi = x;
  9722. this._yi = y;
  9723. this._pendingPtDist = 0;
  9724. }
  9725. else {
  9726. var d2 = dx * dx + dy * dy;
  9727. if (d2 > this._pendingPtDist) {
  9728. this._pendingPtX = x;
  9729. this._pendingPtY = y;
  9730. this._pendingPtDist = d2;
  9731. }
  9732. }
  9733. return this;
  9734. };
  9735. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9736. this._drawPendingPt();
  9737. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9738. if (this._ctx) {
  9739. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9740. }
  9741. this._xi = x3;
  9742. this._yi = y3;
  9743. return this;
  9744. };
  9745. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9746. this._drawPendingPt();
  9747. this.addData(CMD.Q, x1, y1, x2, y2);
  9748. if (this._ctx) {
  9749. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9750. }
  9751. this._xi = x2;
  9752. this._yi = y2;
  9753. return this;
  9754. };
  9755. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9756. this._drawPendingPt();
  9757. tmpAngles[0] = startAngle;
  9758. tmpAngles[1] = endAngle;
  9759. normalizeArcAngles(tmpAngles, anticlockwise);
  9760. startAngle = tmpAngles[0];
  9761. endAngle = tmpAngles[1];
  9762. var delta = endAngle - startAngle;
  9763. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9764. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9765. this._xi = mathCos$1(endAngle) * r + cx;
  9766. this._yi = mathSin$1(endAngle) * r + cy;
  9767. return this;
  9768. };
  9769. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9770. this._drawPendingPt();
  9771. if (this._ctx) {
  9772. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9773. }
  9774. return this;
  9775. };
  9776. PathProxy.prototype.rect = function (x, y, w, h) {
  9777. this._drawPendingPt();
  9778. this._ctx && this._ctx.rect(x, y, w, h);
  9779. this.addData(CMD.R, x, y, w, h);
  9780. return this;
  9781. };
  9782. PathProxy.prototype.closePath = function () {
  9783. this._drawPendingPt();
  9784. this.addData(CMD.Z);
  9785. var ctx = this._ctx;
  9786. var x0 = this._x0;
  9787. var y0 = this._y0;
  9788. if (ctx) {
  9789. ctx.closePath();
  9790. }
  9791. this._xi = x0;
  9792. this._yi = y0;
  9793. return this;
  9794. };
  9795. PathProxy.prototype.fill = function (ctx) {
  9796. ctx && ctx.fill();
  9797. this.toStatic();
  9798. };
  9799. PathProxy.prototype.stroke = function (ctx) {
  9800. ctx && ctx.stroke();
  9801. this.toStatic();
  9802. };
  9803. PathProxy.prototype.len = function () {
  9804. return this._len;
  9805. };
  9806. PathProxy.prototype.setData = function (data) {
  9807. var len = data.length;
  9808. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9809. this.data = new Float32Array(len);
  9810. }
  9811. for (var i = 0; i < len; i++) {
  9812. this.data[i] = data[i];
  9813. }
  9814. this._len = len;
  9815. };
  9816. PathProxy.prototype.appendPath = function (path) {
  9817. if (!(path instanceof Array)) {
  9818. path = [path];
  9819. }
  9820. var len = path.length;
  9821. var appendSize = 0;
  9822. var offset = this._len;
  9823. for (var i = 0; i < len; i++) {
  9824. appendSize += path[i].len();
  9825. }
  9826. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9827. this.data = new Float32Array(offset + appendSize);
  9828. }
  9829. for (var i = 0; i < len; i++) {
  9830. var appendPathData = path[i].data;
  9831. for (var k = 0; k < appendPathData.length; k++) {
  9832. this.data[offset++] = appendPathData[k];
  9833. }
  9834. }
  9835. this._len = offset;
  9836. };
  9837. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9838. if (!this._saveData) {
  9839. return;
  9840. }
  9841. var data = this.data;
  9842. if (this._len + arguments.length > data.length) {
  9843. this._expandData();
  9844. data = this.data;
  9845. }
  9846. for (var i = 0; i < arguments.length; i++) {
  9847. data[this._len++] = arguments[i];
  9848. }
  9849. };
  9850. PathProxy.prototype._drawPendingPt = function () {
  9851. if (this._pendingPtDist > 0) {
  9852. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9853. this._pendingPtDist = 0;
  9854. }
  9855. };
  9856. PathProxy.prototype._expandData = function () {
  9857. if (!(this.data instanceof Array)) {
  9858. var newData = [];
  9859. for (var i = 0; i < this._len; i++) {
  9860. newData[i] = this.data[i];
  9861. }
  9862. this.data = newData;
  9863. }
  9864. };
  9865. PathProxy.prototype.toStatic = function () {
  9866. if (!this._saveData) {
  9867. return;
  9868. }
  9869. this._drawPendingPt();
  9870. var data = this.data;
  9871. if (data instanceof Array) {
  9872. data.length = this._len;
  9873. if (hasTypedArray && this._len > 11) {
  9874. this.data = new Float32Array(data);
  9875. }
  9876. }
  9877. };
  9878. PathProxy.prototype.getBoundingRect = function () {
  9879. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9880. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9881. var data = this.data;
  9882. var xi = 0;
  9883. var yi = 0;
  9884. var x0 = 0;
  9885. var y0 = 0;
  9886. var i;
  9887. for (i = 0; i < this._len;) {
  9888. var cmd = data[i++];
  9889. var isFirst = i === 1;
  9890. if (isFirst) {
  9891. xi = data[i];
  9892. yi = data[i + 1];
  9893. x0 = xi;
  9894. y0 = yi;
  9895. }
  9896. switch (cmd) {
  9897. case CMD.M:
  9898. xi = x0 = data[i++];
  9899. yi = y0 = data[i++];
  9900. min2[0] = x0;
  9901. min2[1] = y0;
  9902. max2[0] = x0;
  9903. max2[1] = y0;
  9904. break;
  9905. case CMD.L:
  9906. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9907. xi = data[i++];
  9908. yi = data[i++];
  9909. break;
  9910. case CMD.C:
  9911. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9912. xi = data[i++];
  9913. yi = data[i++];
  9914. break;
  9915. case CMD.Q:
  9916. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9917. xi = data[i++];
  9918. yi = data[i++];
  9919. break;
  9920. case CMD.A:
  9921. var cx = data[i++];
  9922. var cy = data[i++];
  9923. var rx = data[i++];
  9924. var ry = data[i++];
  9925. var startAngle = data[i++];
  9926. var endAngle = data[i++] + startAngle;
  9927. i += 1;
  9928. var anticlockwise = !data[i++];
  9929. if (isFirst) {
  9930. x0 = mathCos$1(startAngle) * rx + cx;
  9931. y0 = mathSin$1(startAngle) * ry + cy;
  9932. }
  9933. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9934. xi = mathCos$1(endAngle) * rx + cx;
  9935. yi = mathSin$1(endAngle) * ry + cy;
  9936. break;
  9937. case CMD.R:
  9938. x0 = xi = data[i++];
  9939. y0 = yi = data[i++];
  9940. var width = data[i++];
  9941. var height = data[i++];
  9942. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9943. break;
  9944. case CMD.Z:
  9945. xi = x0;
  9946. yi = y0;
  9947. break;
  9948. }
  9949. min(min$1, min$1, min2);
  9950. max(max$1, max$1, max2);
  9951. }
  9952. if (i === 0) {
  9953. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9954. }
  9955. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9956. };
  9957. PathProxy.prototype._calculateLength = function () {
  9958. var data = this.data;
  9959. var len = this._len;
  9960. var ux = this._ux;
  9961. var uy = this._uy;
  9962. var xi = 0;
  9963. var yi = 0;
  9964. var x0 = 0;
  9965. var y0 = 0;
  9966. if (!this._pathSegLen) {
  9967. this._pathSegLen = [];
  9968. }
  9969. var pathSegLen = this._pathSegLen;
  9970. var pathTotalLen = 0;
  9971. var segCount = 0;
  9972. for (var i = 0; i < len;) {
  9973. var cmd = data[i++];
  9974. var isFirst = i === 1;
  9975. if (isFirst) {
  9976. xi = data[i];
  9977. yi = data[i + 1];
  9978. x0 = xi;
  9979. y0 = yi;
  9980. }
  9981. var l = -1;
  9982. switch (cmd) {
  9983. case CMD.M:
  9984. xi = x0 = data[i++];
  9985. yi = y0 = data[i++];
  9986. break;
  9987. case CMD.L: {
  9988. var x2 = data[i++];
  9989. var y2 = data[i++];
  9990. var dx = x2 - xi;
  9991. var dy = y2 - yi;
  9992. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  9993. l = Math.sqrt(dx * dx + dy * dy);
  9994. xi = x2;
  9995. yi = y2;
  9996. }
  9997. break;
  9998. }
  9999. case CMD.C: {
  10000. var x1 = data[i++];
  10001. var y1 = data[i++];
  10002. var x2 = data[i++];
  10003. var y2 = data[i++];
  10004. var x3 = data[i++];
  10005. var y3 = data[i++];
  10006. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10007. xi = x3;
  10008. yi = y3;
  10009. break;
  10010. }
  10011. case CMD.Q: {
  10012. var x1 = data[i++];
  10013. var y1 = data[i++];
  10014. var x2 = data[i++];
  10015. var y2 = data[i++];
  10016. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10017. xi = x2;
  10018. yi = y2;
  10019. break;
  10020. }
  10021. case CMD.A:
  10022. var cx = data[i++];
  10023. var cy = data[i++];
  10024. var rx = data[i++];
  10025. var ry = data[i++];
  10026. var startAngle = data[i++];
  10027. var delta = data[i++];
  10028. var endAngle = delta + startAngle;
  10029. i += 1;
  10030. if (isFirst) {
  10031. x0 = mathCos$1(startAngle) * rx + cx;
  10032. y0 = mathSin$1(startAngle) * ry + cy;
  10033. }
  10034. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  10035. xi = mathCos$1(endAngle) * rx + cx;
  10036. yi = mathSin$1(endAngle) * ry + cy;
  10037. break;
  10038. case CMD.R: {
  10039. x0 = xi = data[i++];
  10040. y0 = yi = data[i++];
  10041. var width = data[i++];
  10042. var height = data[i++];
  10043. l = width * 2 + height * 2;
  10044. break;
  10045. }
  10046. case CMD.Z: {
  10047. var dx = x0 - xi;
  10048. var dy = y0 - yi;
  10049. l = Math.sqrt(dx * dx + dy * dy);
  10050. xi = x0;
  10051. yi = y0;
  10052. break;
  10053. }
  10054. }
  10055. if (l >= 0) {
  10056. pathSegLen[segCount++] = l;
  10057. pathTotalLen += l;
  10058. }
  10059. }
  10060. this._pathLen = pathTotalLen;
  10061. return pathTotalLen;
  10062. };
  10063. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10064. var d = this.data;
  10065. var ux = this._ux;
  10066. var uy = this._uy;
  10067. var len = this._len;
  10068. var x0;
  10069. var y0;
  10070. var xi;
  10071. var yi;
  10072. var x;
  10073. var y;
  10074. var drawPart = percent < 1;
  10075. var pathSegLen;
  10076. var pathTotalLen;
  10077. var accumLength = 0;
  10078. var segCount = 0;
  10079. var displayedLength;
  10080. var pendingPtDist = 0;
  10081. var pendingPtX;
  10082. var pendingPtY;
  10083. if (drawPart) {
  10084. if (!this._pathSegLen) {
  10085. this._calculateLength();
  10086. }
  10087. pathSegLen = this._pathSegLen;
  10088. pathTotalLen = this._pathLen;
  10089. displayedLength = percent * pathTotalLen;
  10090. if (!displayedLength) {
  10091. return;
  10092. }
  10093. }
  10094. lo: for (var i = 0; i < len;) {
  10095. var cmd = d[i++];
  10096. var isFirst = i === 1;
  10097. if (isFirst) {
  10098. xi = d[i];
  10099. yi = d[i + 1];
  10100. x0 = xi;
  10101. y0 = yi;
  10102. }
  10103. if (cmd !== CMD.L && pendingPtDist > 0) {
  10104. ctx.lineTo(pendingPtX, pendingPtY);
  10105. pendingPtDist = 0;
  10106. }
  10107. switch (cmd) {
  10108. case CMD.M:
  10109. x0 = xi = d[i++];
  10110. y0 = yi = d[i++];
  10111. ctx.moveTo(xi, yi);
  10112. break;
  10113. case CMD.L: {
  10114. x = d[i++];
  10115. y = d[i++];
  10116. var dx = mathAbs(x - xi);
  10117. var dy = mathAbs(y - yi);
  10118. if (dx > ux || dy > uy) {
  10119. if (drawPart) {
  10120. var l = pathSegLen[segCount++];
  10121. if (accumLength + l > displayedLength) {
  10122. var t = (displayedLength - accumLength) / l;
  10123. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10124. break lo;
  10125. }
  10126. accumLength += l;
  10127. }
  10128. ctx.lineTo(x, y);
  10129. xi = x;
  10130. yi = y;
  10131. pendingPtDist = 0;
  10132. }
  10133. else {
  10134. var d2 = dx * dx + dy * dy;
  10135. if (d2 > pendingPtDist) {
  10136. pendingPtX = x;
  10137. pendingPtY = y;
  10138. pendingPtDist = d2;
  10139. }
  10140. }
  10141. break;
  10142. }
  10143. case CMD.C: {
  10144. var x1 = d[i++];
  10145. var y1 = d[i++];
  10146. var x2 = d[i++];
  10147. var y2 = d[i++];
  10148. var x3 = d[i++];
  10149. var y3 = d[i++];
  10150. if (drawPart) {
  10151. var l = pathSegLen[segCount++];
  10152. if (accumLength + l > displayedLength) {
  10153. var t = (displayedLength - accumLength) / l;
  10154. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10155. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10156. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10157. break lo;
  10158. }
  10159. accumLength += l;
  10160. }
  10161. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10162. xi = x3;
  10163. yi = y3;
  10164. break;
  10165. }
  10166. case CMD.Q: {
  10167. var x1 = d[i++];
  10168. var y1 = d[i++];
  10169. var x2 = d[i++];
  10170. var y2 = d[i++];
  10171. if (drawPart) {
  10172. var l = pathSegLen[segCount++];
  10173. if (accumLength + l > displayedLength) {
  10174. var t = (displayedLength - accumLength) / l;
  10175. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10176. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10177. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10178. break lo;
  10179. }
  10180. accumLength += l;
  10181. }
  10182. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10183. xi = x2;
  10184. yi = y2;
  10185. break;
  10186. }
  10187. case CMD.A:
  10188. var cx = d[i++];
  10189. var cy = d[i++];
  10190. var rx = d[i++];
  10191. var ry = d[i++];
  10192. var startAngle = d[i++];
  10193. var delta = d[i++];
  10194. var psi = d[i++];
  10195. var anticlockwise = !d[i++];
  10196. var r = (rx > ry) ? rx : ry;
  10197. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10198. var endAngle = startAngle + delta;
  10199. var breakBuild = false;
  10200. if (drawPart) {
  10201. var l = pathSegLen[segCount++];
  10202. if (accumLength + l > displayedLength) {
  10203. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10204. breakBuild = true;
  10205. }
  10206. accumLength += l;
  10207. }
  10208. if (isEllipse && ctx.ellipse) {
  10209. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10210. }
  10211. else {
  10212. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10213. }
  10214. if (breakBuild) {
  10215. break lo;
  10216. }
  10217. if (isFirst) {
  10218. x0 = mathCos$1(startAngle) * rx + cx;
  10219. y0 = mathSin$1(startAngle) * ry + cy;
  10220. }
  10221. xi = mathCos$1(endAngle) * rx + cx;
  10222. yi = mathSin$1(endAngle) * ry + cy;
  10223. break;
  10224. case CMD.R:
  10225. x0 = xi = d[i];
  10226. y0 = yi = d[i + 1];
  10227. x = d[i++];
  10228. y = d[i++];
  10229. var width = d[i++];
  10230. var height = d[i++];
  10231. if (drawPart) {
  10232. var l = pathSegLen[segCount++];
  10233. if (accumLength + l > displayedLength) {
  10234. var d_1 = displayedLength - accumLength;
  10235. ctx.moveTo(x, y);
  10236. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10237. d_1 -= width;
  10238. if (d_1 > 0) {
  10239. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10240. }
  10241. d_1 -= height;
  10242. if (d_1 > 0) {
  10243. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10244. }
  10245. d_1 -= width;
  10246. if (d_1 > 0) {
  10247. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10248. }
  10249. break lo;
  10250. }
  10251. accumLength += l;
  10252. }
  10253. ctx.rect(x, y, width, height);
  10254. break;
  10255. case CMD.Z:
  10256. if (drawPart) {
  10257. var l = pathSegLen[segCount++];
  10258. if (accumLength + l > displayedLength) {
  10259. var t = (displayedLength - accumLength) / l;
  10260. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10261. break lo;
  10262. }
  10263. accumLength += l;
  10264. }
  10265. ctx.closePath();
  10266. xi = x0;
  10267. yi = y0;
  10268. }
  10269. }
  10270. };
  10271. PathProxy.prototype.clone = function () {
  10272. var newProxy = new PathProxy();
  10273. var data = this.data;
  10274. newProxy.data = data.slice ? data.slice()
  10275. : Array.prototype.slice.call(data);
  10276. newProxy._len = this._len;
  10277. return newProxy;
  10278. };
  10279. PathProxy.CMD = CMD;
  10280. PathProxy.initDefaultProps = (function () {
  10281. var proto = PathProxy.prototype;
  10282. proto._saveData = true;
  10283. proto._ux = 0;
  10284. proto._uy = 0;
  10285. proto._pendingPtDist = 0;
  10286. proto._version = 0;
  10287. })();
  10288. return PathProxy;
  10289. }());
  10290. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10291. if (lineWidth === 0) {
  10292. return false;
  10293. }
  10294. var _l = lineWidth;
  10295. var _a = 0;
  10296. var _b = x0;
  10297. if ((y > y0 + _l && y > y1 + _l)
  10298. || (y < y0 - _l && y < y1 - _l)
  10299. || (x > x0 + _l && x > x1 + _l)
  10300. || (x < x0 - _l && x < x1 - _l)) {
  10301. return false;
  10302. }
  10303. if (x0 !== x1) {
  10304. _a = (y0 - y1) / (x0 - x1);
  10305. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10306. }
  10307. else {
  10308. return Math.abs(x - x0) <= _l / 2;
  10309. }
  10310. var tmp = _a * x - y + _b;
  10311. var _s = tmp * tmp / (_a * _a + 1);
  10312. return _s <= _l / 2 * _l / 2;
  10313. }
  10314. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10315. if (lineWidth === 0) {
  10316. return false;
  10317. }
  10318. var _l = lineWidth;
  10319. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10320. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10321. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10322. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10323. return false;
  10324. }
  10325. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10326. return d <= _l / 2;
  10327. }
  10328. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10329. if (lineWidth === 0) {
  10330. return false;
  10331. }
  10332. var _l = lineWidth;
  10333. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10334. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10335. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10336. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10337. return false;
  10338. }
  10339. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10340. return d <= _l / 2;
  10341. }
  10342. var PI2$2 = Math.PI * 2;
  10343. function normalizeRadian(angle) {
  10344. angle %= PI2$2;
  10345. if (angle < 0) {
  10346. angle += PI2$2;
  10347. }
  10348. return angle;
  10349. }
  10350. var PI2$3 = Math.PI * 2;
  10351. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10352. if (lineWidth === 0) {
  10353. return false;
  10354. }
  10355. var _l = lineWidth;
  10356. x -= cx;
  10357. y -= cy;
  10358. var d = Math.sqrt(x * x + y * y);
  10359. if ((d - _l > r) || (d + _l < r)) {
  10360. return false;
  10361. }
  10362. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10363. return true;
  10364. }
  10365. if (anticlockwise) {
  10366. var tmp = startAngle;
  10367. startAngle = normalizeRadian(endAngle);
  10368. endAngle = normalizeRadian(tmp);
  10369. }
  10370. else {
  10371. startAngle = normalizeRadian(startAngle);
  10372. endAngle = normalizeRadian(endAngle);
  10373. }
  10374. if (startAngle > endAngle) {
  10375. endAngle += PI2$3;
  10376. }
  10377. var angle = Math.atan2(y, x);
  10378. if (angle < 0) {
  10379. angle += PI2$3;
  10380. }
  10381. return (angle >= startAngle && angle <= endAngle)
  10382. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10383. }
  10384. function windingLine(x0, y0, x1, y1, x, y) {
  10385. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10386. return 0;
  10387. }
  10388. if (y1 === y0) {
  10389. return 0;
  10390. }
  10391. var t = (y - y0) / (y1 - y0);
  10392. var dir = y1 < y0 ? 1 : -1;
  10393. if (t === 1 || t === 0) {
  10394. dir = y1 < y0 ? 0.5 : -0.5;
  10395. }
  10396. var x_ = t * (x1 - x0) + x0;
  10397. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10398. }
  10399. var CMD$1 = PathProxy.CMD;
  10400. var PI2$4 = Math.PI * 2;
  10401. var EPSILON$2 = 1e-4;
  10402. function isAroundEqual(a, b) {
  10403. return Math.abs(a - b) < EPSILON$2;
  10404. }
  10405. var roots = [-1, -1, -1];
  10406. var extrema = [-1, -1];
  10407. function swapExtrema() {
  10408. var tmp = extrema[0];
  10409. extrema[0] = extrema[1];
  10410. extrema[1] = tmp;
  10411. }
  10412. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10413. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10414. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10415. return 0;
  10416. }
  10417. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10418. if (nRoots === 0) {
  10419. return 0;
  10420. }
  10421. else {
  10422. var w = 0;
  10423. var nExtrema = -1;
  10424. var y0_ = void 0;
  10425. var y1_ = void 0;
  10426. for (var i = 0; i < nRoots; i++) {
  10427. var t = roots[i];
  10428. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10429. var x_ = cubicAt(x0, x1, x2, x3, t);
  10430. if (x_ < x) {
  10431. continue;
  10432. }
  10433. if (nExtrema < 0) {
  10434. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10435. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10436. swapExtrema();
  10437. }
  10438. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10439. if (nExtrema > 1) {
  10440. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10441. }
  10442. }
  10443. if (nExtrema === 2) {
  10444. if (t < extrema[0]) {
  10445. w += y0_ < y0 ? unit : -unit;
  10446. }
  10447. else if (t < extrema[1]) {
  10448. w += y1_ < y0_ ? unit : -unit;
  10449. }
  10450. else {
  10451. w += y3 < y1_ ? unit : -unit;
  10452. }
  10453. }
  10454. else {
  10455. if (t < extrema[0]) {
  10456. w += y0_ < y0 ? unit : -unit;
  10457. }
  10458. else {
  10459. w += y3 < y0_ ? unit : -unit;
  10460. }
  10461. }
  10462. }
  10463. return w;
  10464. }
  10465. }
  10466. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10467. if ((y > y0 && y > y1 && y > y2)
  10468. || (y < y0 && y < y1 && y < y2)) {
  10469. return 0;
  10470. }
  10471. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10472. if (nRoots === 0) {
  10473. return 0;
  10474. }
  10475. else {
  10476. var t = quadraticExtremum(y0, y1, y2);
  10477. if (t >= 0 && t <= 1) {
  10478. var w = 0;
  10479. var y_ = quadraticAt(y0, y1, y2, t);
  10480. for (var i = 0; i < nRoots; i++) {
  10481. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10482. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10483. if (x_ < x) {
  10484. continue;
  10485. }
  10486. if (roots[i] < t) {
  10487. w += y_ < y0 ? unit : -unit;
  10488. }
  10489. else {
  10490. w += y2 < y_ ? unit : -unit;
  10491. }
  10492. }
  10493. return w;
  10494. }
  10495. else {
  10496. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10497. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10498. if (x_ < x) {
  10499. return 0;
  10500. }
  10501. return y2 < y0 ? unit : -unit;
  10502. }
  10503. }
  10504. }
  10505. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10506. y -= cy;
  10507. if (y > r || y < -r) {
  10508. return 0;
  10509. }
  10510. var tmp = Math.sqrt(r * r - y * y);
  10511. roots[0] = -tmp;
  10512. roots[1] = tmp;
  10513. var dTheta = Math.abs(startAngle - endAngle);
  10514. if (dTheta < 1e-4) {
  10515. return 0;
  10516. }
  10517. if (dTheta >= PI2$4 - 1e-4) {
  10518. startAngle = 0;
  10519. endAngle = PI2$4;
  10520. var dir = anticlockwise ? 1 : -1;
  10521. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10522. return dir;
  10523. }
  10524. else {
  10525. return 0;
  10526. }
  10527. }
  10528. if (startAngle > endAngle) {
  10529. var tmp_1 = startAngle;
  10530. startAngle = endAngle;
  10531. endAngle = tmp_1;
  10532. }
  10533. if (startAngle < 0) {
  10534. startAngle += PI2$4;
  10535. endAngle += PI2$4;
  10536. }
  10537. var w = 0;
  10538. for (var i = 0; i < 2; i++) {
  10539. var x_ = roots[i];
  10540. if (x_ + cx > x) {
  10541. var angle = Math.atan2(y, x_);
  10542. var dir = anticlockwise ? 1 : -1;
  10543. if (angle < 0) {
  10544. angle = PI2$4 + angle;
  10545. }
  10546. if ((angle >= startAngle && angle <= endAngle)
  10547. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10548. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10549. dir = -dir;
  10550. }
  10551. w += dir;
  10552. }
  10553. }
  10554. }
  10555. return w;
  10556. }
  10557. function containPath(path, lineWidth, isStroke, x, y) {
  10558. var data = path.data;
  10559. var len = path.len();
  10560. var w = 0;
  10561. var xi = 0;
  10562. var yi = 0;
  10563. var x0 = 0;
  10564. var y0 = 0;
  10565. var x1;
  10566. var y1;
  10567. for (var i = 0; i < len;) {
  10568. var cmd = data[i++];
  10569. var isFirst = i === 1;
  10570. if (cmd === CMD$1.M && i > 1) {
  10571. if (!isStroke) {
  10572. w += windingLine(xi, yi, x0, y0, x, y);
  10573. }
  10574. }
  10575. if (isFirst) {
  10576. xi = data[i];
  10577. yi = data[i + 1];
  10578. x0 = xi;
  10579. y0 = yi;
  10580. }
  10581. switch (cmd) {
  10582. case CMD$1.M:
  10583. x0 = data[i++];
  10584. y0 = data[i++];
  10585. xi = x0;
  10586. yi = y0;
  10587. break;
  10588. case CMD$1.L:
  10589. if (isStroke) {
  10590. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10591. return true;
  10592. }
  10593. }
  10594. else {
  10595. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10596. }
  10597. xi = data[i++];
  10598. yi = data[i++];
  10599. break;
  10600. case CMD$1.C:
  10601. if (isStroke) {
  10602. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10603. return true;
  10604. }
  10605. }
  10606. else {
  10607. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10608. }
  10609. xi = data[i++];
  10610. yi = data[i++];
  10611. break;
  10612. case CMD$1.Q:
  10613. if (isStroke) {
  10614. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10615. return true;
  10616. }
  10617. }
  10618. else {
  10619. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10620. }
  10621. xi = data[i++];
  10622. yi = data[i++];
  10623. break;
  10624. case CMD$1.A:
  10625. var cx = data[i++];
  10626. var cy = data[i++];
  10627. var rx = data[i++];
  10628. var ry = data[i++];
  10629. var theta = data[i++];
  10630. var dTheta = data[i++];
  10631. i += 1;
  10632. var anticlockwise = !!(1 - data[i++]);
  10633. x1 = Math.cos(theta) * rx + cx;
  10634. y1 = Math.sin(theta) * ry + cy;
  10635. if (!isFirst) {
  10636. w += windingLine(xi, yi, x1, y1, x, y);
  10637. }
  10638. else {
  10639. x0 = x1;
  10640. y0 = y1;
  10641. }
  10642. var _x = (x - cx) * ry / rx + cx;
  10643. if (isStroke) {
  10644. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10645. return true;
  10646. }
  10647. }
  10648. else {
  10649. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10650. }
  10651. xi = Math.cos(theta + dTheta) * rx + cx;
  10652. yi = Math.sin(theta + dTheta) * ry + cy;
  10653. break;
  10654. case CMD$1.R:
  10655. x0 = xi = data[i++];
  10656. y0 = yi = data[i++];
  10657. var width = data[i++];
  10658. var height = data[i++];
  10659. x1 = x0 + width;
  10660. y1 = y0 + height;
  10661. if (isStroke) {
  10662. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10663. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10664. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10665. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10666. return true;
  10667. }
  10668. }
  10669. else {
  10670. w += windingLine(x1, y0, x1, y1, x, y);
  10671. w += windingLine(x0, y1, x0, y0, x, y);
  10672. }
  10673. break;
  10674. case CMD$1.Z:
  10675. if (isStroke) {
  10676. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10677. return true;
  10678. }
  10679. }
  10680. else {
  10681. w += windingLine(xi, yi, x0, y0, x, y);
  10682. }
  10683. xi = x0;
  10684. yi = y0;
  10685. break;
  10686. }
  10687. }
  10688. if (!isStroke && !isAroundEqual(yi, y0)) {
  10689. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10690. }
  10691. return w !== 0;
  10692. }
  10693. function contain(pathProxy, x, y) {
  10694. return containPath(pathProxy, 0, false, x, y);
  10695. }
  10696. function containStroke$4(pathProxy, lineWidth, x, y) {
  10697. return containPath(pathProxy, lineWidth, true, x, y);
  10698. }
  10699. var DEFAULT_PATH_STYLE = defaults({
  10700. fill: '#000',
  10701. stroke: null,
  10702. strokePercent: 1,
  10703. fillOpacity: 1,
  10704. strokeOpacity: 1,
  10705. lineDashOffset: 0,
  10706. lineWidth: 1,
  10707. lineCap: 'butt',
  10708. miterLimit: 10,
  10709. strokeNoScale: false,
  10710. strokeFirst: false
  10711. }, DEFAULT_COMMON_STYLE);
  10712. var DEFAULT_PATH_ANIMATION_PROPS = {
  10713. style: defaults({
  10714. fill: true,
  10715. stroke: true,
  10716. strokePercent: true,
  10717. fillOpacity: true,
  10718. strokeOpacity: true,
  10719. lineDashOffset: true,
  10720. lineWidth: true,
  10721. miterLimit: true
  10722. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10723. };
  10724. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10725. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10726. ]);
  10727. var Path = (function (_super) {
  10728. __extends(Path, _super);
  10729. function Path(opts) {
  10730. return _super.call(this, opts) || this;
  10731. }
  10732. Path.prototype.update = function () {
  10733. var _this = this;
  10734. _super.prototype.update.call(this);
  10735. var style = this.style;
  10736. if (style.decal) {
  10737. var decalEl = this._decalEl = this._decalEl || new Path();
  10738. if (decalEl.buildPath === Path.prototype.buildPath) {
  10739. decalEl.buildPath = function (ctx) {
  10740. _this.buildPath(ctx, _this.shape);
  10741. };
  10742. }
  10743. decalEl.silent = true;
  10744. var decalElStyle = decalEl.style;
  10745. for (var key in style) {
  10746. if (decalElStyle[key] !== style[key]) {
  10747. decalElStyle[key] = style[key];
  10748. }
  10749. }
  10750. decalElStyle.fill = style.fill ? style.decal : null;
  10751. decalElStyle.decal = null;
  10752. decalElStyle.shadowColor = null;
  10753. style.strokeFirst && (decalElStyle.stroke = null);
  10754. for (var i = 0; i < pathCopyParams.length; ++i) {
  10755. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10756. }
  10757. decalEl.__dirty |= REDRAW_BIT;
  10758. }
  10759. else if (this._decalEl) {
  10760. this._decalEl = null;
  10761. }
  10762. };
  10763. Path.prototype.getDecalElement = function () {
  10764. return this._decalEl;
  10765. };
  10766. Path.prototype._init = function (props) {
  10767. var keysArr = keys(props);
  10768. this.shape = this.getDefaultShape();
  10769. var defaultStyle = this.getDefaultStyle();
  10770. if (defaultStyle) {
  10771. this.useStyle(defaultStyle);
  10772. }
  10773. for (var i = 0; i < keysArr.length; i++) {
  10774. var key = keysArr[i];
  10775. var value = props[key];
  10776. if (key === 'style') {
  10777. if (!this.style) {
  10778. this.useStyle(value);
  10779. }
  10780. else {
  10781. extend(this.style, value);
  10782. }
  10783. }
  10784. else if (key === 'shape') {
  10785. extend(this.shape, value);
  10786. }
  10787. else {
  10788. _super.prototype.attrKV.call(this, key, value);
  10789. }
  10790. }
  10791. if (!this.style) {
  10792. this.useStyle({});
  10793. }
  10794. };
  10795. Path.prototype.getDefaultStyle = function () {
  10796. return null;
  10797. };
  10798. Path.prototype.getDefaultShape = function () {
  10799. return {};
  10800. };
  10801. Path.prototype.canBeInsideText = function () {
  10802. return this.hasFill();
  10803. };
  10804. Path.prototype.getInsideTextFill = function () {
  10805. var pathFill = this.style.fill;
  10806. if (pathFill !== 'none') {
  10807. if (isString(pathFill)) {
  10808. var fillLum = lum(pathFill, 0);
  10809. if (fillLum > 0.5) {
  10810. return DARK_LABEL_COLOR;
  10811. }
  10812. else if (fillLum > 0.2) {
  10813. return LIGHTER_LABEL_COLOR;
  10814. }
  10815. return LIGHT_LABEL_COLOR;
  10816. }
  10817. else if (pathFill) {
  10818. return LIGHT_LABEL_COLOR;
  10819. }
  10820. }
  10821. return DARK_LABEL_COLOR;
  10822. };
  10823. Path.prototype.getInsideTextStroke = function (textFill) {
  10824. var pathFill = this.style.fill;
  10825. if (isString(pathFill)) {
  10826. var zr = this.__zr;
  10827. var isDarkMode = !!(zr && zr.isDarkMode());
  10828. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10829. if (isDarkMode === isDarkLabel) {
  10830. return pathFill;
  10831. }
  10832. }
  10833. };
  10834. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10835. Path.prototype.pathUpdated = function () {
  10836. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10837. };
  10838. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10839. !this.path && this.createPathProxy();
  10840. this.path.beginPath();
  10841. this.buildPath(this.path, this.shape, inBatch);
  10842. return this.path;
  10843. };
  10844. Path.prototype.createPathProxy = function () {
  10845. this.path = new PathProxy(false);
  10846. };
  10847. Path.prototype.hasStroke = function () {
  10848. var style = this.style;
  10849. var stroke = style.stroke;
  10850. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10851. };
  10852. Path.prototype.hasFill = function () {
  10853. var style = this.style;
  10854. var fill = style.fill;
  10855. return fill != null && fill !== 'none';
  10856. };
  10857. Path.prototype.getBoundingRect = function () {
  10858. var rect = this._rect;
  10859. var style = this.style;
  10860. var needsUpdateRect = !rect;
  10861. if (needsUpdateRect) {
  10862. var firstInvoke = false;
  10863. if (!this.path) {
  10864. firstInvoke = true;
  10865. this.createPathProxy();
  10866. }
  10867. var path = this.path;
  10868. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10869. path.beginPath();
  10870. this.buildPath(path, this.shape, false);
  10871. this.pathUpdated();
  10872. }
  10873. rect = path.getBoundingRect();
  10874. }
  10875. this._rect = rect;
  10876. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10877. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  10878. if (this.__dirty || needsUpdateRect) {
  10879. rectStroke.copy(rect);
  10880. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10881. var w = style.lineWidth;
  10882. if (!this.hasFill()) {
  10883. var strokeContainThreshold = this.strokeContainThreshold;
  10884. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10885. }
  10886. if (lineScale > 1e-10) {
  10887. rectStroke.width += w / lineScale;
  10888. rectStroke.height += w / lineScale;
  10889. rectStroke.x -= w / lineScale / 2;
  10890. rectStroke.y -= w / lineScale / 2;
  10891. }
  10892. }
  10893. return rectStroke;
  10894. }
  10895. return rect;
  10896. };
  10897. Path.prototype.contain = function (x, y) {
  10898. var localPos = this.transformCoordToLocal(x, y);
  10899. var rect = this.getBoundingRect();
  10900. var style = this.style;
  10901. x = localPos[0];
  10902. y = localPos[1];
  10903. if (rect.contain(x, y)) {
  10904. var pathProxy = this.path;
  10905. if (this.hasStroke()) {
  10906. var lineWidth = style.lineWidth;
  10907. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10908. if (lineScale > 1e-10) {
  10909. if (!this.hasFill()) {
  10910. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10911. }
  10912. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10913. return true;
  10914. }
  10915. }
  10916. }
  10917. if (this.hasFill()) {
  10918. return contain(pathProxy, x, y);
  10919. }
  10920. }
  10921. return false;
  10922. };
  10923. Path.prototype.dirtyShape = function () {
  10924. this.__dirty |= SHAPE_CHANGED_BIT;
  10925. if (this._rect) {
  10926. this._rect = null;
  10927. }
  10928. if (this._decalEl) {
  10929. this._decalEl.dirtyShape();
  10930. }
  10931. this.markRedraw();
  10932. };
  10933. Path.prototype.dirty = function () {
  10934. this.dirtyStyle();
  10935. this.dirtyShape();
  10936. };
  10937. Path.prototype.animateShape = function (loop) {
  10938. return this.animate('shape', loop);
  10939. };
  10940. Path.prototype.updateDuringAnimation = function (targetKey) {
  10941. if (targetKey === 'style') {
  10942. this.dirtyStyle();
  10943. }
  10944. else if (targetKey === 'shape') {
  10945. this.dirtyShape();
  10946. }
  10947. else {
  10948. this.markRedraw();
  10949. }
  10950. };
  10951. Path.prototype.attrKV = function (key, value) {
  10952. if (key === 'shape') {
  10953. this.setShape(value);
  10954. }
  10955. else {
  10956. _super.prototype.attrKV.call(this, key, value);
  10957. }
  10958. };
  10959. Path.prototype.setShape = function (keyOrObj, value) {
  10960. var shape = this.shape;
  10961. if (!shape) {
  10962. shape = this.shape = {};
  10963. }
  10964. if (typeof keyOrObj === 'string') {
  10965. shape[keyOrObj] = value;
  10966. }
  10967. else {
  10968. extend(shape, keyOrObj);
  10969. }
  10970. this.dirtyShape();
  10971. return this;
  10972. };
  10973. Path.prototype.shapeChanged = function () {
  10974. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  10975. };
  10976. Path.prototype.createStyle = function (obj) {
  10977. return createObject(DEFAULT_PATH_STYLE, obj);
  10978. };
  10979. Path.prototype._innerSaveToNormal = function (toState) {
  10980. _super.prototype._innerSaveToNormal.call(this, toState);
  10981. var normalState = this._normalState;
  10982. if (toState.shape && !normalState.shape) {
  10983. normalState.shape = extend({}, this.shape);
  10984. }
  10985. };
  10986. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10987. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10988. var needsRestoreToNormal = !(state && keepCurrentStates);
  10989. var targetShape;
  10990. if (state && state.shape) {
  10991. if (transition) {
  10992. if (keepCurrentStates) {
  10993. targetShape = state.shape;
  10994. }
  10995. else {
  10996. targetShape = extend({}, normalState.shape);
  10997. extend(targetShape, state.shape);
  10998. }
  10999. }
  11000. else {
  11001. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11002. extend(targetShape, state.shape);
  11003. }
  11004. }
  11005. else if (needsRestoreToNormal) {
  11006. targetShape = normalState.shape;
  11007. }
  11008. if (targetShape) {
  11009. if (transition) {
  11010. this.shape = extend({}, this.shape);
  11011. var targetShapePrimaryProps = {};
  11012. var shapeKeys = keys(targetShape);
  11013. for (var i = 0; i < shapeKeys.length; i++) {
  11014. var key = shapeKeys[i];
  11015. if (typeof targetShape[key] === 'object') {
  11016. this.shape[key] = targetShape[key];
  11017. }
  11018. else {
  11019. targetShapePrimaryProps[key] = targetShape[key];
  11020. }
  11021. }
  11022. this._transitionState(stateName, {
  11023. shape: targetShapePrimaryProps
  11024. }, animationCfg);
  11025. }
  11026. else {
  11027. this.shape = targetShape;
  11028. this.dirtyShape();
  11029. }
  11030. }
  11031. };
  11032. Path.prototype._mergeStates = function (states) {
  11033. var mergedState = _super.prototype._mergeStates.call(this, states);
  11034. var mergedShape;
  11035. for (var i = 0; i < states.length; i++) {
  11036. var state = states[i];
  11037. if (state.shape) {
  11038. mergedShape = mergedShape || {};
  11039. this._mergeStyle(mergedShape, state.shape);
  11040. }
  11041. }
  11042. if (mergedShape) {
  11043. mergedState.shape = mergedShape;
  11044. }
  11045. return mergedState;
  11046. };
  11047. Path.prototype.getAnimationStyleProps = function () {
  11048. return DEFAULT_PATH_ANIMATION_PROPS;
  11049. };
  11050. Path.prototype.isZeroArea = function () {
  11051. return false;
  11052. };
  11053. Path.extend = function (defaultProps) {
  11054. var Sub = (function (_super) {
  11055. __extends(Sub, _super);
  11056. function Sub(opts) {
  11057. var _this = _super.call(this, opts) || this;
  11058. defaultProps.init && defaultProps.init.call(_this, opts);
  11059. return _this;
  11060. }
  11061. Sub.prototype.getDefaultStyle = function () {
  11062. return clone(defaultProps.style);
  11063. };
  11064. Sub.prototype.getDefaultShape = function () {
  11065. return clone(defaultProps.shape);
  11066. };
  11067. return Sub;
  11068. }(Path));
  11069. for (var key in defaultProps) {
  11070. if (typeof defaultProps[key] === 'function') {
  11071. Sub.prototype[key] = defaultProps[key];
  11072. }
  11073. }
  11074. return Sub;
  11075. };
  11076. Path.initDefaultProps = (function () {
  11077. var pathProto = Path.prototype;
  11078. pathProto.type = 'path';
  11079. pathProto.strokeContainThreshold = 5;
  11080. pathProto.segmentIgnoreThreshold = 0;
  11081. pathProto.subPixelOptimize = false;
  11082. pathProto.autoBatch = false;
  11083. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11084. })();
  11085. return Path;
  11086. }(Displayable));
  11087. var DEFAULT_TSPAN_STYLE = defaults({
  11088. strokeFirst: true,
  11089. font: DEFAULT_FONT,
  11090. x: 0,
  11091. y: 0,
  11092. textAlign: 'left',
  11093. textBaseline: 'top',
  11094. miterLimit: 2
  11095. }, DEFAULT_PATH_STYLE);
  11096. var TSpan = (function (_super) {
  11097. __extends(TSpan, _super);
  11098. function TSpan() {
  11099. return _super !== null && _super.apply(this, arguments) || this;
  11100. }
  11101. TSpan.prototype.hasStroke = function () {
  11102. var style = this.style;
  11103. var stroke = style.stroke;
  11104. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  11105. };
  11106. TSpan.prototype.hasFill = function () {
  11107. var style = this.style;
  11108. var fill = style.fill;
  11109. return fill != null && fill !== 'none';
  11110. };
  11111. TSpan.prototype.createStyle = function (obj) {
  11112. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11113. };
  11114. TSpan.prototype.setBoundingRect = function (rect) {
  11115. this._rect = rect;
  11116. };
  11117. TSpan.prototype.getBoundingRect = function () {
  11118. var style = this.style;
  11119. if (!this._rect) {
  11120. var text = style.text;
  11121. text != null ? (text += '') : (text = '');
  11122. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11123. rect.x += style.x || 0;
  11124. rect.y += style.y || 0;
  11125. if (this.hasStroke()) {
  11126. var w = style.lineWidth;
  11127. rect.x -= w / 2;
  11128. rect.y -= w / 2;
  11129. rect.width += w;
  11130. rect.height += w;
  11131. }
  11132. this._rect = rect;
  11133. }
  11134. return this._rect;
  11135. };
  11136. TSpan.initDefaultProps = (function () {
  11137. var tspanProto = TSpan.prototype;
  11138. tspanProto.dirtyRectTolerance = 10;
  11139. })();
  11140. return TSpan;
  11141. }(Displayable));
  11142. TSpan.prototype.type = 'tspan';
  11143. var DEFAULT_IMAGE_STYLE = defaults({
  11144. x: 0,
  11145. y: 0
  11146. }, DEFAULT_COMMON_STYLE);
  11147. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11148. style: defaults({
  11149. x: true,
  11150. y: true,
  11151. width: true,
  11152. height: true,
  11153. sx: true,
  11154. sy: true,
  11155. sWidth: true,
  11156. sHeight: true
  11157. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11158. };
  11159. function isImageLike(source) {
  11160. return !!(source
  11161. && typeof source !== 'string'
  11162. && source.width && source.height);
  11163. }
  11164. var ZRImage = (function (_super) {
  11165. __extends(ZRImage, _super);
  11166. function ZRImage() {
  11167. return _super !== null && _super.apply(this, arguments) || this;
  11168. }
  11169. ZRImage.prototype.createStyle = function (obj) {
  11170. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11171. };
  11172. ZRImage.prototype._getSize = function (dim) {
  11173. var style = this.style;
  11174. var size = style[dim];
  11175. if (size != null) {
  11176. return size;
  11177. }
  11178. var imageSource = isImageLike(style.image)
  11179. ? style.image : this.__image;
  11180. if (!imageSource) {
  11181. return 0;
  11182. }
  11183. var otherDim = dim === 'width' ? 'height' : 'width';
  11184. var otherDimSize = style[otherDim];
  11185. if (otherDimSize == null) {
  11186. return imageSource[dim];
  11187. }
  11188. else {
  11189. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11190. }
  11191. };
  11192. ZRImage.prototype.getWidth = function () {
  11193. return this._getSize('width');
  11194. };
  11195. ZRImage.prototype.getHeight = function () {
  11196. return this._getSize('height');
  11197. };
  11198. ZRImage.prototype.getAnimationStyleProps = function () {
  11199. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11200. };
  11201. ZRImage.prototype.getBoundingRect = function () {
  11202. var style = this.style;
  11203. if (!this._rect) {
  11204. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11205. }
  11206. return this._rect;
  11207. };
  11208. return ZRImage;
  11209. }(Displayable));
  11210. ZRImage.prototype.type = 'image';
  11211. function buildPath(ctx, shape) {
  11212. var x = shape.x;
  11213. var y = shape.y;
  11214. var width = shape.width;
  11215. var height = shape.height;
  11216. var r = shape.r;
  11217. var r1;
  11218. var r2;
  11219. var r3;
  11220. var r4;
  11221. if (width < 0) {
  11222. x = x + width;
  11223. width = -width;
  11224. }
  11225. if (height < 0) {
  11226. y = y + height;
  11227. height = -height;
  11228. }
  11229. if (typeof r === 'number') {
  11230. r1 = r2 = r3 = r4 = r;
  11231. }
  11232. else if (r instanceof Array) {
  11233. if (r.length === 1) {
  11234. r1 = r2 = r3 = r4 = r[0];
  11235. }
  11236. else if (r.length === 2) {
  11237. r1 = r3 = r[0];
  11238. r2 = r4 = r[1];
  11239. }
  11240. else if (r.length === 3) {
  11241. r1 = r[0];
  11242. r2 = r4 = r[1];
  11243. r3 = r[2];
  11244. }
  11245. else {
  11246. r1 = r[0];
  11247. r2 = r[1];
  11248. r3 = r[2];
  11249. r4 = r[3];
  11250. }
  11251. }
  11252. else {
  11253. r1 = r2 = r3 = r4 = 0;
  11254. }
  11255. var total;
  11256. if (r1 + r2 > width) {
  11257. total = r1 + r2;
  11258. r1 *= width / total;
  11259. r2 *= width / total;
  11260. }
  11261. if (r3 + r4 > width) {
  11262. total = r3 + r4;
  11263. r3 *= width / total;
  11264. r4 *= width / total;
  11265. }
  11266. if (r2 + r3 > height) {
  11267. total = r2 + r3;
  11268. r2 *= height / total;
  11269. r3 *= height / total;
  11270. }
  11271. if (r1 + r4 > height) {
  11272. total = r1 + r4;
  11273. r1 *= height / total;
  11274. r4 *= height / total;
  11275. }
  11276. ctx.moveTo(x + r1, y);
  11277. ctx.lineTo(x + width - r2, y);
  11278. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11279. ctx.lineTo(x + width, y + height - r3);
  11280. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11281. ctx.lineTo(x + r4, y + height);
  11282. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11283. ctx.lineTo(x, y + r1);
  11284. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11285. }
  11286. var round$1 = Math.round;
  11287. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11288. if (!inputShape) {
  11289. return;
  11290. }
  11291. var x1 = inputShape.x1;
  11292. var x2 = inputShape.x2;
  11293. var y1 = inputShape.y1;
  11294. var y2 = inputShape.y2;
  11295. outputShape.x1 = x1;
  11296. outputShape.x2 = x2;
  11297. outputShape.y1 = y1;
  11298. outputShape.y2 = y2;
  11299. var lineWidth = style && style.lineWidth;
  11300. if (!lineWidth) {
  11301. return outputShape;
  11302. }
  11303. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11304. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11305. }
  11306. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11307. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11308. }
  11309. return outputShape;
  11310. }
  11311. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11312. if (!inputShape) {
  11313. return;
  11314. }
  11315. var originX = inputShape.x;
  11316. var originY = inputShape.y;
  11317. var originWidth = inputShape.width;
  11318. var originHeight = inputShape.height;
  11319. outputShape.x = originX;
  11320. outputShape.y = originY;
  11321. outputShape.width = originWidth;
  11322. outputShape.height = originHeight;
  11323. var lineWidth = style && style.lineWidth;
  11324. if (!lineWidth) {
  11325. return outputShape;
  11326. }
  11327. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11328. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11329. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11330. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11331. return outputShape;
  11332. }
  11333. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11334. if (!lineWidth) {
  11335. return position;
  11336. }
  11337. var doubledPosition = round$1(position * 2);
  11338. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11339. ? doubledPosition / 2
  11340. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11341. }
  11342. var RectShape = (function () {
  11343. function RectShape() {
  11344. this.x = 0;
  11345. this.y = 0;
  11346. this.width = 0;
  11347. this.height = 0;
  11348. }
  11349. return RectShape;
  11350. }());
  11351. var subPixelOptimizeOutputShape = {};
  11352. var Rect = (function (_super) {
  11353. __extends(Rect, _super);
  11354. function Rect(opts) {
  11355. return _super.call(this, opts) || this;
  11356. }
  11357. Rect.prototype.getDefaultShape = function () {
  11358. return new RectShape();
  11359. };
  11360. Rect.prototype.buildPath = function (ctx, shape) {
  11361. var x;
  11362. var y;
  11363. var width;
  11364. var height;
  11365. if (this.subPixelOptimize) {
  11366. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11367. x = optimizedShape.x;
  11368. y = optimizedShape.y;
  11369. width = optimizedShape.width;
  11370. height = optimizedShape.height;
  11371. optimizedShape.r = shape.r;
  11372. shape = optimizedShape;
  11373. }
  11374. else {
  11375. x = shape.x;
  11376. y = shape.y;
  11377. width = shape.width;
  11378. height = shape.height;
  11379. }
  11380. if (!shape.r) {
  11381. ctx.rect(x, y, width, height);
  11382. }
  11383. else {
  11384. buildPath(ctx, shape);
  11385. }
  11386. };
  11387. Rect.prototype.isZeroArea = function () {
  11388. return !this.shape.width || !this.shape.height;
  11389. };
  11390. return Rect;
  11391. }(Path));
  11392. Rect.prototype.type = 'rect';
  11393. var DEFAULT_RICH_TEXT_COLOR = {
  11394. fill: '#000'
  11395. };
  11396. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11397. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11398. style: defaults({
  11399. fill: true,
  11400. stroke: true,
  11401. fillOpacity: true,
  11402. strokeOpacity: true,
  11403. lineWidth: true,
  11404. fontSize: true,
  11405. lineHeight: true,
  11406. width: true,
  11407. height: true,
  11408. textShadowColor: true,
  11409. textShadowBlur: true,
  11410. textShadowOffsetX: true,
  11411. textShadowOffsetY: true,
  11412. backgroundColor: true,
  11413. padding: true,
  11414. borderColor: true,
  11415. borderWidth: true,
  11416. borderRadius: true
  11417. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11418. };
  11419. var ZRText = (function (_super) {
  11420. __extends(ZRText, _super);
  11421. function ZRText(opts) {
  11422. var _this = _super.call(this) || this;
  11423. _this.type = 'text';
  11424. _this._children = [];
  11425. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11426. _this.attr(opts);
  11427. return _this;
  11428. }
  11429. ZRText.prototype.childrenRef = function () {
  11430. return this._children;
  11431. };
  11432. ZRText.prototype.update = function () {
  11433. _super.prototype.update.call(this);
  11434. if (this.styleChanged()) {
  11435. this._updateSubTexts();
  11436. }
  11437. for (var i = 0; i < this._children.length; i++) {
  11438. var child = this._children[i];
  11439. child.zlevel = this.zlevel;
  11440. child.z = this.z;
  11441. child.z2 = this.z2;
  11442. child.culling = this.culling;
  11443. child.cursor = this.cursor;
  11444. child.invisible = this.invisible;
  11445. }
  11446. };
  11447. ZRText.prototype.updateTransform = function () {
  11448. var innerTransformable = this.innerTransformable;
  11449. if (innerTransformable) {
  11450. innerTransformable.updateTransform();
  11451. if (innerTransformable.transform) {
  11452. this.transform = innerTransformable.transform;
  11453. }
  11454. }
  11455. else {
  11456. _super.prototype.updateTransform.call(this);
  11457. }
  11458. };
  11459. ZRText.prototype.getLocalTransform = function (m) {
  11460. var innerTransformable = this.innerTransformable;
  11461. return innerTransformable
  11462. ? innerTransformable.getLocalTransform(m)
  11463. : _super.prototype.getLocalTransform.call(this, m);
  11464. };
  11465. ZRText.prototype.getComputedTransform = function () {
  11466. if (this.__hostTarget) {
  11467. this.__hostTarget.getComputedTransform();
  11468. this.__hostTarget.updateInnerText(true);
  11469. }
  11470. return _super.prototype.getComputedTransform.call(this);
  11471. };
  11472. ZRText.prototype._updateSubTexts = function () {
  11473. this._childCursor = 0;
  11474. normalizeTextStyle(this.style);
  11475. this.style.rich
  11476. ? this._updateRichTexts()
  11477. : this._updatePlainTexts();
  11478. this._children.length = this._childCursor;
  11479. this.styleUpdated();
  11480. };
  11481. ZRText.prototype.addSelfToZr = function (zr) {
  11482. _super.prototype.addSelfToZr.call(this, zr);
  11483. for (var i = 0; i < this._children.length; i++) {
  11484. this._children[i].__zr = zr;
  11485. }
  11486. };
  11487. ZRText.prototype.removeSelfFromZr = function (zr) {
  11488. _super.prototype.removeSelfFromZr.call(this, zr);
  11489. for (var i = 0; i < this._children.length; i++) {
  11490. this._children[i].__zr = null;
  11491. }
  11492. };
  11493. ZRText.prototype.getBoundingRect = function () {
  11494. if (this.styleChanged()) {
  11495. this._updateSubTexts();
  11496. }
  11497. if (!this._rect) {
  11498. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11499. var children = this._children;
  11500. var tmpMat = [];
  11501. var rect = null;
  11502. for (var i = 0; i < children.length; i++) {
  11503. var child = children[i];
  11504. var childRect = child.getBoundingRect();
  11505. var transform = child.getLocalTransform(tmpMat);
  11506. if (transform) {
  11507. tmpRect.copy(childRect);
  11508. tmpRect.applyTransform(transform);
  11509. rect = rect || tmpRect.clone();
  11510. rect.union(tmpRect);
  11511. }
  11512. else {
  11513. rect = rect || childRect.clone();
  11514. rect.union(childRect);
  11515. }
  11516. }
  11517. this._rect = rect || tmpRect;
  11518. }
  11519. return this._rect;
  11520. };
  11521. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11522. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11523. };
  11524. ZRText.prototype.setTextContent = function (textContent) {
  11525. if ("development" !== 'production') {
  11526. throw new Error('Can\'t attach text on another text');
  11527. }
  11528. };
  11529. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11530. if (!sourceStyle) {
  11531. return targetStyle;
  11532. }
  11533. var sourceRich = sourceStyle.rich;
  11534. var targetRich = targetStyle.rich || (sourceRich && {});
  11535. extend(targetStyle, sourceStyle);
  11536. if (sourceRich && targetRich) {
  11537. this._mergeRich(targetRich, sourceRich);
  11538. targetStyle.rich = targetRich;
  11539. }
  11540. else if (targetRich) {
  11541. targetStyle.rich = targetRich;
  11542. }
  11543. return targetStyle;
  11544. };
  11545. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11546. var richNames = keys(sourceRich);
  11547. for (var i = 0; i < richNames.length; i++) {
  11548. var richName = richNames[i];
  11549. targetRich[richName] = targetRich[richName] || {};
  11550. extend(targetRich[richName], sourceRich[richName]);
  11551. }
  11552. };
  11553. ZRText.prototype.getAnimationStyleProps = function () {
  11554. return DEFAULT_TEXT_ANIMATION_PROPS;
  11555. };
  11556. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11557. var child = this._children[this._childCursor];
  11558. if (!child || !(child instanceof Ctor)) {
  11559. child = new Ctor();
  11560. }
  11561. this._children[this._childCursor++] = child;
  11562. child.__zr = this.__zr;
  11563. child.parent = this;
  11564. return child;
  11565. };
  11566. ZRText.prototype._updatePlainTexts = function () {
  11567. var style = this.style;
  11568. var textFont = style.font || DEFAULT_FONT;
  11569. var textPadding = style.padding;
  11570. var text = getStyleText(style);
  11571. var contentBlock = parsePlainText(text, style);
  11572. var needDrawBg = needDrawBackground(style);
  11573. var bgColorDrawn = !!(style.backgroundColor);
  11574. var outerHeight = contentBlock.outerHeight;
  11575. var outerWidth = contentBlock.outerWidth;
  11576. var contentWidth = contentBlock.contentWidth;
  11577. var textLines = contentBlock.lines;
  11578. var lineHeight = contentBlock.lineHeight;
  11579. var defaultStyle = this._defaultStyle;
  11580. var baseX = style.x || 0;
  11581. var baseY = style.y || 0;
  11582. var textAlign = style.align || defaultStyle.align || 'left';
  11583. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11584. var textX = baseX;
  11585. var textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign);
  11586. if (needDrawBg || textPadding) {
  11587. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11588. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11589. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11590. }
  11591. textY += lineHeight / 2;
  11592. if (textPadding) {
  11593. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11594. if (verticalAlign === 'top') {
  11595. textY += textPadding[0];
  11596. }
  11597. else if (verticalAlign === 'bottom') {
  11598. textY -= textPadding[2];
  11599. }
  11600. }
  11601. var defaultLineWidth = 0;
  11602. var useDefaultFill = false;
  11603. var textFill = getFill('fill' in style
  11604. ? style.fill
  11605. : (useDefaultFill = true, defaultStyle.fill));
  11606. var textStroke = getStroke('stroke' in style
  11607. ? style.stroke
  11608. : (!bgColorDrawn
  11609. && (!defaultStyle.autoStroke || useDefaultFill))
  11610. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11611. : null);
  11612. var hasShadow = style.textShadowBlur > 0;
  11613. var fixedBoundingRect = style.width != null
  11614. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11615. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11616. for (var i = 0; i < textLines.length; i++) {
  11617. var el = this._getOrCreateChild(TSpan);
  11618. var subElStyle = el.createStyle();
  11619. el.useStyle(subElStyle);
  11620. subElStyle.text = textLines[i];
  11621. subElStyle.x = textX;
  11622. subElStyle.y = textY;
  11623. if (textAlign) {
  11624. subElStyle.textAlign = textAlign;
  11625. }
  11626. subElStyle.textBaseline = 'middle';
  11627. subElStyle.opacity = style.opacity;
  11628. subElStyle.strokeFirst = true;
  11629. if (hasShadow) {
  11630. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11631. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11632. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11633. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11634. }
  11635. subElStyle.stroke = textStroke;
  11636. subElStyle.fill = textFill;
  11637. if (textStroke) {
  11638. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11639. subElStyle.lineDash = style.lineDash;
  11640. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11641. }
  11642. subElStyle.font = textFont;
  11643. setSeparateFont(subElStyle, style);
  11644. textY += lineHeight;
  11645. if (fixedBoundingRect) {
  11646. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11647. }
  11648. }
  11649. };
  11650. ZRText.prototype._updateRichTexts = function () {
  11651. var style = this.style;
  11652. var text = getStyleText(style);
  11653. var contentBlock = parseRichText(text, style);
  11654. var contentWidth = contentBlock.width;
  11655. var outerWidth = contentBlock.outerWidth;
  11656. var outerHeight = contentBlock.outerHeight;
  11657. var textPadding = style.padding;
  11658. var baseX = style.x || 0;
  11659. var baseY = style.y || 0;
  11660. var defaultStyle = this._defaultStyle;
  11661. var textAlign = style.align || defaultStyle.align;
  11662. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11663. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11664. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11665. var xLeft = boxX;
  11666. var lineTop = boxY;
  11667. if (textPadding) {
  11668. xLeft += textPadding[3];
  11669. lineTop += textPadding[0];
  11670. }
  11671. var xRight = xLeft + contentWidth;
  11672. if (needDrawBackground(style)) {
  11673. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11674. }
  11675. var bgColorDrawn = !!(style.backgroundColor);
  11676. for (var i = 0; i < contentBlock.lines.length; i++) {
  11677. var line = contentBlock.lines[i];
  11678. var tokens = line.tokens;
  11679. var tokenCount = tokens.length;
  11680. var lineHeight = line.lineHeight;
  11681. var remainedWidth = line.width;
  11682. var leftIndex = 0;
  11683. var lineXLeft = xLeft;
  11684. var lineXRight = xRight;
  11685. var rightIndex = tokenCount - 1;
  11686. var token = void 0;
  11687. while (leftIndex < tokenCount
  11688. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11689. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11690. remainedWidth -= token.width;
  11691. lineXLeft += token.width;
  11692. leftIndex++;
  11693. }
  11694. while (rightIndex >= 0
  11695. && (token = tokens[rightIndex], token.align === 'right')) {
  11696. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11697. remainedWidth -= token.width;
  11698. lineXRight -= token.width;
  11699. rightIndex--;
  11700. }
  11701. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11702. while (leftIndex <= rightIndex) {
  11703. token = tokens[leftIndex];
  11704. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11705. lineXLeft += token.width;
  11706. leftIndex++;
  11707. }
  11708. lineTop += lineHeight;
  11709. }
  11710. };
  11711. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11712. var tokenStyle = style.rich[token.styleName] || {};
  11713. tokenStyle.text = token.text;
  11714. var verticalAlign = token.verticalAlign;
  11715. var y = lineTop + lineHeight / 2;
  11716. if (verticalAlign === 'top') {
  11717. y = lineTop + token.height / 2;
  11718. }
  11719. else if (verticalAlign === 'bottom') {
  11720. y = lineTop + lineHeight - token.height / 2;
  11721. }
  11722. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11723. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11724. ? x - token.width
  11725. : textAlign === 'center'
  11726. ? x - token.width / 2
  11727. : x, y - token.height / 2, token.width, token.height);
  11728. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11729. var textPadding = token.textPadding;
  11730. if (textPadding) {
  11731. x = getTextXForPadding(x, textAlign, textPadding);
  11732. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11733. }
  11734. var el = this._getOrCreateChild(TSpan);
  11735. var subElStyle = el.createStyle();
  11736. el.useStyle(subElStyle);
  11737. var defaultStyle = this._defaultStyle;
  11738. var useDefaultFill = false;
  11739. var defaultLineWidth = 0;
  11740. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11741. : 'fill' in style ? style.fill
  11742. : (useDefaultFill = true, defaultStyle.fill));
  11743. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11744. : 'stroke' in style ? style.stroke
  11745. : (!bgColorDrawn
  11746. && !parentBgColorDrawn
  11747. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11748. : null);
  11749. var hasShadow = tokenStyle.textShadowBlur > 0
  11750. || style.textShadowBlur > 0;
  11751. subElStyle.text = token.text;
  11752. subElStyle.x = x;
  11753. subElStyle.y = y;
  11754. if (hasShadow) {
  11755. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11756. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11757. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11758. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11759. }
  11760. subElStyle.textAlign = textAlign;
  11761. subElStyle.textBaseline = 'middle';
  11762. subElStyle.font = token.font || DEFAULT_FONT;
  11763. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11764. setSeparateFont(subElStyle, tokenStyle);
  11765. if (textStroke) {
  11766. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11767. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11768. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11769. subElStyle.stroke = textStroke;
  11770. }
  11771. if (textFill) {
  11772. subElStyle.fill = textFill;
  11773. }
  11774. var textWidth = token.contentWidth;
  11775. var textHeight = token.contentHeight;
  11776. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11777. };
  11778. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11779. var textBackgroundColor = style.backgroundColor;
  11780. var textBorderWidth = style.borderWidth;
  11781. var textBorderColor = style.borderColor;
  11782. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11783. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11784. var textBorderRadius = style.borderRadius;
  11785. var self = this;
  11786. var rectEl;
  11787. var imgEl;
  11788. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11789. rectEl = this._getOrCreateChild(Rect);
  11790. rectEl.useStyle(rectEl.createStyle());
  11791. rectEl.style.fill = null;
  11792. var rectShape = rectEl.shape;
  11793. rectShape.x = x;
  11794. rectShape.y = y;
  11795. rectShape.width = width;
  11796. rectShape.height = height;
  11797. rectShape.r = textBorderRadius;
  11798. rectEl.dirtyShape();
  11799. }
  11800. if (isPlainOrGradientBg) {
  11801. var rectStyle = rectEl.style;
  11802. rectStyle.fill = textBackgroundColor || null;
  11803. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11804. }
  11805. else if (isImageBg) {
  11806. imgEl = this._getOrCreateChild(ZRImage);
  11807. imgEl.onload = function () {
  11808. self.dirtyStyle();
  11809. };
  11810. var imgStyle = imgEl.style;
  11811. imgStyle.image = textBackgroundColor.image;
  11812. imgStyle.x = x;
  11813. imgStyle.y = y;
  11814. imgStyle.width = width;
  11815. imgStyle.height = height;
  11816. }
  11817. if (textBorderWidth && textBorderColor) {
  11818. var rectStyle = rectEl.style;
  11819. rectStyle.lineWidth = textBorderWidth;
  11820. rectStyle.stroke = textBorderColor;
  11821. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11822. rectStyle.lineDash = style.borderDash;
  11823. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11824. rectEl.strokeContainThreshold = 0;
  11825. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11826. rectStyle.strokeFirst = true;
  11827. rectStyle.lineWidth *= 2;
  11828. }
  11829. }
  11830. var commonStyle = (rectEl || imgEl).style;
  11831. commonStyle.shadowBlur = style.shadowBlur || 0;
  11832. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11833. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11834. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11835. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11836. };
  11837. ZRText.makeFont = function (style) {
  11838. var font = '';
  11839. if (hasSeparateFont(style)) {
  11840. font = [
  11841. style.fontStyle,
  11842. style.fontWeight,
  11843. parseFontSize(style.fontSize),
  11844. style.fontFamily || 'sans-serif'
  11845. ].join(' ');
  11846. }
  11847. return font && trim(font) || style.textFont || style.font;
  11848. };
  11849. return ZRText;
  11850. }(Displayable));
  11851. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11852. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11853. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  11854. function parseFontSize(fontSize) {
  11855. if (typeof fontSize === 'string'
  11856. && (fontSize.indexOf('px') !== -1
  11857. || fontSize.indexOf('rem') !== -1
  11858. || fontSize.indexOf('em') !== -1)) {
  11859. return fontSize;
  11860. }
  11861. else if (!isNaN(+fontSize)) {
  11862. return fontSize + 'px';
  11863. }
  11864. else {
  11865. return DEFAULT_FONT_SIZE + 'px';
  11866. }
  11867. }
  11868. function setSeparateFont(targetStyle, sourceStyle) {
  11869. for (var i = 0; i < FONT_PARTS.length; i++) {
  11870. var fontProp = FONT_PARTS[i];
  11871. var val = sourceStyle[fontProp];
  11872. if (val != null) {
  11873. targetStyle[fontProp] = val;
  11874. }
  11875. }
  11876. }
  11877. function hasSeparateFont(style) {
  11878. return style.fontSize != null || style.fontFamily || style.fontWeight;
  11879. }
  11880. function normalizeTextStyle(style) {
  11881. normalizeStyle(style);
  11882. each(style.rich, normalizeStyle);
  11883. return style;
  11884. }
  11885. function normalizeStyle(style) {
  11886. if (style) {
  11887. style.font = ZRText.makeFont(style);
  11888. var textAlign = style.align;
  11889. textAlign === 'middle' && (textAlign = 'center');
  11890. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11891. var verticalAlign = style.verticalAlign;
  11892. verticalAlign === 'center' && (verticalAlign = 'middle');
  11893. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11894. var textPadding = style.padding;
  11895. if (textPadding) {
  11896. style.padding = normalizeCssArray(style.padding);
  11897. }
  11898. }
  11899. }
  11900. function getStroke(stroke, lineWidth) {
  11901. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11902. ? null
  11903. : (stroke.image || stroke.colorStops)
  11904. ? '#000'
  11905. : stroke;
  11906. }
  11907. function getFill(fill) {
  11908. return (fill == null || fill === 'none')
  11909. ? null
  11910. : (fill.image || fill.colorStops)
  11911. ? '#000'
  11912. : fill;
  11913. }
  11914. function getTextXForPadding(x, textAlign, textPadding) {
  11915. return textAlign === 'right'
  11916. ? (x - textPadding[1])
  11917. : textAlign === 'center'
  11918. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11919. : (x + textPadding[3]);
  11920. }
  11921. function getStyleText(style) {
  11922. var text = style.text;
  11923. text != null && (text += '');
  11924. return text;
  11925. }
  11926. function needDrawBackground(style) {
  11927. return !!(style.backgroundColor
  11928. || style.lineHeight
  11929. || (style.borderWidth && style.borderColor));
  11930. }
  11931. var getECData = makeInner();
  11932. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  11933. if (el) {
  11934. var ecData = getECData(el);
  11935. // Add data index and series index for indexing the data by element
  11936. // Useful in tooltip
  11937. ecData.dataIndex = dataIdx;
  11938. ecData.dataType = dataType;
  11939. ecData.seriesIndex = seriesIndex;
  11940. ecData.ssrType = 'chart';
  11941. // TODO: not store dataIndex on children.
  11942. if (el.type === 'group') {
  11943. el.traverse(function (child) {
  11944. var childECData = getECData(child);
  11945. childECData.seriesIndex = seriesIndex;
  11946. childECData.dataIndex = dataIdx;
  11947. childECData.dataType = dataType;
  11948. childECData.ssrType = 'chart';
  11949. });
  11950. }
  11951. }
  11952. };
  11953. // Reserve 0 as default.
  11954. var _highlightNextDigit = 1;
  11955. var _highlightKeyMap = {};
  11956. var getSavedStates = makeInner();
  11957. var getComponentStates = makeInner();
  11958. var HOVER_STATE_NORMAL = 0;
  11959. var HOVER_STATE_BLUR = 1;
  11960. var HOVER_STATE_EMPHASIS = 2;
  11961. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11962. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11963. var Z2_EMPHASIS_LIFT = 10;
  11964. var Z2_SELECT_LIFT = 9;
  11965. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11966. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11967. var SELECT_ACTION_TYPE = 'select';
  11968. var UNSELECT_ACTION_TYPE = 'unselect';
  11969. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11970. function hasFillOrStroke(fillOrStroke) {
  11971. return fillOrStroke != null && fillOrStroke !== 'none';
  11972. }
  11973. function doChangeHoverState(el, stateName, hoverStateEnum) {
  11974. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  11975. el.onHoverStateChange(stateName);
  11976. }
  11977. el.hoverState = hoverStateEnum;
  11978. }
  11979. function singleEnterEmphasis(el) {
  11980. // Only mark the flag.
  11981. // States will be applied in the echarts.ts in next frame.
  11982. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  11983. }
  11984. function singleLeaveEmphasis(el) {
  11985. // Only mark the flag.
  11986. // States will be applied in the echarts.ts in next frame.
  11987. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  11988. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11989. }
  11990. }
  11991. function singleEnterBlur(el) {
  11992. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  11993. }
  11994. function singleLeaveBlur(el) {
  11995. if (el.hoverState === HOVER_STATE_BLUR) {
  11996. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11997. }
  11998. }
  11999. function singleEnterSelect(el) {
  12000. el.selected = true;
  12001. }
  12002. function singleLeaveSelect(el) {
  12003. el.selected = false;
  12004. }
  12005. function updateElementState(el, updater, commonParam) {
  12006. updater(el, commonParam);
  12007. }
  12008. function traverseUpdateState(el, updater, commonParam) {
  12009. updateElementState(el, updater, commonParam);
  12010. el.isGroup && el.traverse(function (child) {
  12011. updateElementState(child, updater, commonParam);
  12012. });
  12013. }
  12014. function setStatesFlag(el, stateName) {
  12015. switch (stateName) {
  12016. case 'emphasis':
  12017. el.hoverState = HOVER_STATE_EMPHASIS;
  12018. break;
  12019. case 'normal':
  12020. el.hoverState = HOVER_STATE_NORMAL;
  12021. break;
  12022. case 'blur':
  12023. el.hoverState = HOVER_STATE_BLUR;
  12024. break;
  12025. case 'select':
  12026. el.selected = true;
  12027. }
  12028. }
  12029. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12030. var style = el.style;
  12031. var fromState = {};
  12032. for (var i = 0; i < props.length; i++) {
  12033. var propName = props[i];
  12034. var val = style[propName];
  12035. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12036. }
  12037. for (var i = 0; i < el.animators.length; i++) {
  12038. var animator = el.animators[i];
  12039. if (animator.__fromStateTransition
  12040. // Don't consider the animation to emphasis state.
  12041. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12042. animator.saveTo(fromState, props);
  12043. }
  12044. }
  12045. return fromState;
  12046. }
  12047. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12048. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12049. var cloned = false;
  12050. if (el instanceof Path) {
  12051. var store = getSavedStates(el);
  12052. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12053. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12054. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12055. state = state || {};
  12056. var emphasisStyle = state.style || {};
  12057. // inherit case
  12058. if (emphasisStyle.fill === 'inherit') {
  12059. cloned = true;
  12060. state = extend({}, state);
  12061. emphasisStyle = extend({}, emphasisStyle);
  12062. emphasisStyle.fill = fromFill;
  12063. }
  12064. // Apply default color lift
  12065. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12066. cloned = true;
  12067. // Not modify the original value.
  12068. state = extend({}, state);
  12069. emphasisStyle = extend({}, emphasisStyle);
  12070. // Already being applied 'emphasis'. DON'T lift color multiple times.
  12071. emphasisStyle.fill = liftColor(fromFill);
  12072. }
  12073. // Not highlight stroke if fill has been highlighted.
  12074. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12075. if (!cloned) {
  12076. state = extend({}, state);
  12077. emphasisStyle = extend({}, emphasisStyle);
  12078. }
  12079. emphasisStyle.stroke = liftColor(fromStroke);
  12080. }
  12081. state.style = emphasisStyle;
  12082. }
  12083. }
  12084. if (state) {
  12085. // TODO Share with textContent?
  12086. if (state.z2 == null) {
  12087. if (!cloned) {
  12088. state = extend({}, state);
  12089. }
  12090. var z2EmphasisLift = el.z2EmphasisLift;
  12091. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12092. }
  12093. }
  12094. return state;
  12095. }
  12096. function createSelectDefaultState(el, stateName, state) {
  12097. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12098. if (state) {
  12099. // TODO Share with textContent?
  12100. if (state.z2 == null) {
  12101. state = extend({}, state);
  12102. var z2SelectLift = el.z2SelectLift;
  12103. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12104. }
  12105. }
  12106. return state;
  12107. }
  12108. function createBlurDefaultState(el, stateName, state) {
  12109. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12110. var currentOpacity = el.style.opacity;
  12111. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12112. opacity: 1
  12113. }) : null;
  12114. state = state || {};
  12115. var blurStyle = state.style || {};
  12116. if (blurStyle.opacity == null) {
  12117. // clone state
  12118. state = extend({}, state);
  12119. blurStyle = extend({
  12120. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12121. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12122. }, blurStyle);
  12123. state.style = blurStyle;
  12124. }
  12125. return state;
  12126. }
  12127. function elementStateProxy(stateName, targetStates) {
  12128. var state = this.states[stateName];
  12129. if (this.style) {
  12130. if (stateName === 'emphasis') {
  12131. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12132. } else if (stateName === 'blur') {
  12133. return createBlurDefaultState(this, stateName, state);
  12134. } else if (stateName === 'select') {
  12135. return createSelectDefaultState(this, stateName, state);
  12136. }
  12137. }
  12138. return state;
  12139. }
  12140. /**
  12141. * Set hover style (namely "emphasis style") of element.
  12142. * @param el Should not be `zrender/graphic/Group`.
  12143. * @param focus 'self' | 'selfInSeries' | 'series'
  12144. */
  12145. function setDefaultStateProxy(el) {
  12146. el.stateProxy = elementStateProxy;
  12147. var textContent = el.getTextContent();
  12148. var textGuide = el.getTextGuideLine();
  12149. if (textContent) {
  12150. textContent.stateProxy = elementStateProxy;
  12151. }
  12152. if (textGuide) {
  12153. textGuide.stateProxy = elementStateProxy;
  12154. }
  12155. }
  12156. function enterEmphasisWhenMouseOver(el, e) {
  12157. !shouldSilent(el, e)
  12158. // "emphasis" event highlight has higher priority than mouse highlight.
  12159. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12160. }
  12161. function leaveEmphasisWhenMouseOut(el, e) {
  12162. !shouldSilent(el, e)
  12163. // "emphasis" event highlight has higher priority than mouse highlight.
  12164. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12165. }
  12166. function enterEmphasis(el, highlightDigit) {
  12167. el.__highByOuter |= 1 << (highlightDigit || 0);
  12168. traverseUpdateState(el, singleEnterEmphasis);
  12169. }
  12170. function leaveEmphasis(el, highlightDigit) {
  12171. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12172. }
  12173. function enterBlur(el) {
  12174. traverseUpdateState(el, singleEnterBlur);
  12175. }
  12176. function leaveBlur(el) {
  12177. traverseUpdateState(el, singleLeaveBlur);
  12178. }
  12179. function enterSelect(el) {
  12180. traverseUpdateState(el, singleEnterSelect);
  12181. }
  12182. function leaveSelect(el) {
  12183. traverseUpdateState(el, singleLeaveSelect);
  12184. }
  12185. function shouldSilent(el, e) {
  12186. return el.__highDownSilentOnTouch && e.zrByTouch;
  12187. }
  12188. function allLeaveBlur(api) {
  12189. var model = api.getModel();
  12190. var leaveBlurredSeries = [];
  12191. var allComponentViews = [];
  12192. model.eachComponent(function (componentType, componentModel) {
  12193. var componentStates = getComponentStates(componentModel);
  12194. var isSeries = componentType === 'series';
  12195. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12196. !isSeries && allComponentViews.push(view);
  12197. if (componentStates.isBlured) {
  12198. // Leave blur anyway
  12199. view.group.traverse(function (child) {
  12200. singleLeaveBlur(child);
  12201. });
  12202. isSeries && leaveBlurredSeries.push(componentModel);
  12203. }
  12204. componentStates.isBlured = false;
  12205. });
  12206. each(allComponentViews, function (view) {
  12207. if (view && view.toggleBlurSeries) {
  12208. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12209. }
  12210. });
  12211. }
  12212. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12213. var ecModel = api.getModel();
  12214. blurScope = blurScope || 'coordinateSystem';
  12215. function leaveBlurOfIndices(data, dataIndices) {
  12216. for (var i = 0; i < dataIndices.length; i++) {
  12217. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12218. itemEl && leaveBlur(itemEl);
  12219. }
  12220. }
  12221. if (targetSeriesIndex == null) {
  12222. return;
  12223. }
  12224. if (!focus || focus === 'none') {
  12225. return;
  12226. }
  12227. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12228. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12229. if (targetCoordSys && targetCoordSys.master) {
  12230. targetCoordSys = targetCoordSys.master;
  12231. }
  12232. var blurredSeries = [];
  12233. ecModel.eachSeries(function (seriesModel) {
  12234. var sameSeries = targetSeriesModel === seriesModel;
  12235. var coordSys = seriesModel.coordinateSystem;
  12236. if (coordSys && coordSys.master) {
  12237. coordSys = coordSys.master;
  12238. }
  12239. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12240. if (!(
  12241. // Not blur other series if blurScope series
  12242. blurScope === 'series' && !sameSeries
  12243. // Not blur other coordinate system if blurScope is coordinateSystem
  12244. || blurScope === 'coordinateSystem' && !sameCoordSys
  12245. // Not blur self series if focus is series.
  12246. || focus === 'series' && sameSeries
  12247. // TODO blurScope: coordinate system
  12248. )) {
  12249. var view = api.getViewOfSeriesModel(seriesModel);
  12250. view.group.traverse(function (child) {
  12251. // For the elements that have been triggered by other components,
  12252. // and are still required to be highlighted,
  12253. // because the current is directly forced to blur the element,
  12254. // it will cause the focus self to be unable to highlight, so skip the blur of this element.
  12255. if (child.__highByOuter && sameSeries && focus === 'self') {
  12256. return;
  12257. }
  12258. singleEnterBlur(child);
  12259. });
  12260. if (isArrayLike(focus)) {
  12261. leaveBlurOfIndices(seriesModel.getData(), focus);
  12262. } else if (isObject(focus)) {
  12263. var dataTypes = keys(focus);
  12264. for (var d = 0; d < dataTypes.length; d++) {
  12265. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12266. }
  12267. }
  12268. blurredSeries.push(seriesModel);
  12269. getComponentStates(seriesModel).isBlured = true;
  12270. }
  12271. });
  12272. ecModel.eachComponent(function (componentType, componentModel) {
  12273. if (componentType === 'series') {
  12274. return;
  12275. }
  12276. var view = api.getViewOfComponentModel(componentModel);
  12277. if (view && view.toggleBlurSeries) {
  12278. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12279. }
  12280. });
  12281. }
  12282. function blurComponent(componentMainType, componentIndex, api) {
  12283. if (componentMainType == null || componentIndex == null) {
  12284. return;
  12285. }
  12286. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12287. if (!componentModel) {
  12288. return;
  12289. }
  12290. getComponentStates(componentModel).isBlured = true;
  12291. var view = api.getViewOfComponentModel(componentModel);
  12292. if (!view || !view.focusBlurEnabled) {
  12293. return;
  12294. }
  12295. view.group.traverse(function (child) {
  12296. singleEnterBlur(child);
  12297. });
  12298. }
  12299. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12300. var seriesIndex = seriesModel.seriesIndex;
  12301. var data = seriesModel.getData(payload.dataType);
  12302. if (!data) {
  12303. if ("development" !== 'production') {
  12304. error("Unknown dataType " + payload.dataType);
  12305. }
  12306. return;
  12307. }
  12308. var dataIndex = queryDataIndex(data, payload);
  12309. // Pick the first one if there is multiple/none exists.
  12310. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12311. var el = data.getItemGraphicEl(dataIndex);
  12312. if (!el) {
  12313. var count = data.count();
  12314. var current = 0;
  12315. // If data on dataIndex is NaN.
  12316. while (!el && current < count) {
  12317. el = data.getItemGraphicEl(current++);
  12318. }
  12319. }
  12320. if (el) {
  12321. var ecData = getECData(el);
  12322. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12323. } else {
  12324. // If there is no element put on the data. Try getting it from raw option
  12325. // TODO Should put it on seriesModel?
  12326. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12327. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12328. if (focus_1 != null) {
  12329. blurSeries(seriesIndex, focus_1, blurScope, api);
  12330. }
  12331. }
  12332. }
  12333. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12334. var ret = {
  12335. focusSelf: false,
  12336. dispatchers: null
  12337. };
  12338. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12339. return ret;
  12340. }
  12341. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12342. if (!componentModel) {
  12343. return ret;
  12344. }
  12345. var view = api.getViewOfComponentModel(componentModel);
  12346. if (!view || !view.findHighDownDispatchers) {
  12347. return ret;
  12348. }
  12349. var dispatchers = view.findHighDownDispatchers(name);
  12350. // At presnet, the component (like Geo) only blur inside itself.
  12351. // So we do not use `blurScope` in component.
  12352. var focusSelf;
  12353. for (var i = 0; i < dispatchers.length; i++) {
  12354. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12355. error('param should be highDownDispatcher');
  12356. }
  12357. if (getECData(dispatchers[i]).focus === 'self') {
  12358. focusSelf = true;
  12359. break;
  12360. }
  12361. }
  12362. return {
  12363. focusSelf: focusSelf,
  12364. dispatchers: dispatchers
  12365. };
  12366. }
  12367. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12368. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12369. error('param should be highDownDispatcher');
  12370. }
  12371. var ecData = getECData(dispatcher);
  12372. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12373. dispatchers = _a.dispatchers,
  12374. focusSelf = _a.focusSelf;
  12375. // If `findHighDownDispatchers` is supported on the component,
  12376. // highlight/downplay elements with the same name.
  12377. if (dispatchers) {
  12378. if (focusSelf) {
  12379. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12380. }
  12381. each(dispatchers, function (dispatcher) {
  12382. return enterEmphasisWhenMouseOver(dispatcher, e);
  12383. });
  12384. } else {
  12385. // Try blur all in the related series. Then emphasis the hoverred.
  12386. // TODO. progressive mode.
  12387. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12388. if (ecData.focus === 'self') {
  12389. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12390. }
  12391. // Other than series, component that not support `findHighDownDispatcher` will
  12392. // also use it. But in this case, highlight/downplay are only supported in
  12393. // mouse hover but not in dispatchAction.
  12394. enterEmphasisWhenMouseOver(dispatcher, e);
  12395. }
  12396. }
  12397. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12398. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12399. error('param should be highDownDispatcher');
  12400. }
  12401. allLeaveBlur(api);
  12402. var ecData = getECData(dispatcher);
  12403. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12404. if (dispatchers) {
  12405. each(dispatchers, function (dispatcher) {
  12406. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12407. });
  12408. } else {
  12409. leaveEmphasisWhenMouseOut(dispatcher, e);
  12410. }
  12411. }
  12412. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12413. if (!isSelectChangePayload(payload)) {
  12414. return;
  12415. }
  12416. var dataType = payload.dataType;
  12417. var data = seriesModel.getData(dataType);
  12418. var dataIndex = queryDataIndex(data, payload);
  12419. if (!isArray(dataIndex)) {
  12420. dataIndex = [dataIndex];
  12421. }
  12422. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12423. }
  12424. function updateSeriesElementSelection(seriesModel) {
  12425. var allData = seriesModel.getAllData();
  12426. each(allData, function (_a) {
  12427. var data = _a.data,
  12428. type = _a.type;
  12429. data.eachItemGraphicEl(function (el, idx) {
  12430. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12431. });
  12432. });
  12433. }
  12434. function getAllSelectedIndices(ecModel) {
  12435. var ret = [];
  12436. ecModel.eachSeries(function (seriesModel) {
  12437. var allData = seriesModel.getAllData();
  12438. each(allData, function (_a) {
  12439. var data = _a.data,
  12440. type = _a.type;
  12441. var dataIndices = seriesModel.getSelectedDataIndices();
  12442. if (dataIndices.length > 0) {
  12443. var item = {
  12444. dataIndex: dataIndices,
  12445. seriesIndex: seriesModel.seriesIndex
  12446. };
  12447. if (type != null) {
  12448. item.dataType = type;
  12449. }
  12450. ret.push(item);
  12451. }
  12452. });
  12453. });
  12454. return ret;
  12455. }
  12456. /**
  12457. * Enable the function that mouseover will trigger the emphasis state.
  12458. *
  12459. * NOTE:
  12460. * This function should be used on the element with dataIndex, seriesIndex.
  12461. *
  12462. */
  12463. function enableHoverEmphasis(el, focus, blurScope) {
  12464. setAsHighDownDispatcher(el, true);
  12465. traverseUpdateState(el, setDefaultStateProxy);
  12466. enableHoverFocus(el, focus, blurScope);
  12467. }
  12468. function disableHoverEmphasis(el) {
  12469. setAsHighDownDispatcher(el, false);
  12470. }
  12471. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12472. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12473. }
  12474. function enableHoverFocus(el, focus, blurScope) {
  12475. var ecData = getECData(el);
  12476. if (focus != null) {
  12477. // TODO dataIndex may be set after this function. This check is not useful.
  12478. // if (ecData.dataIndex == null) {
  12479. // if (__DEV__) {
  12480. // console.warn('focus can only been set on element with dataIndex');
  12481. // }
  12482. // }
  12483. // else {
  12484. ecData.focus = focus;
  12485. ecData.blurScope = blurScope;
  12486. // }
  12487. } else if (ecData.focus) {
  12488. ecData.focus = null;
  12489. }
  12490. }
  12491. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12492. var defaultStyleGetterMap = {
  12493. itemStyle: 'getItemStyle',
  12494. lineStyle: 'getLineStyle',
  12495. areaStyle: 'getAreaStyle'
  12496. };
  12497. /**
  12498. * Set emphasis/blur/selected states of element.
  12499. */
  12500. function setStatesStylesFromModel(el, itemModel, styleType,
  12501. // default itemStyle
  12502. getter) {
  12503. styleType = styleType || 'itemStyle';
  12504. for (var i = 0; i < OTHER_STATES.length; i++) {
  12505. var stateName = OTHER_STATES[i];
  12506. var model = itemModel.getModel([stateName, styleType]);
  12507. var state = el.ensureState(stateName);
  12508. // Let it throw error if getterType is not found.
  12509. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12510. }
  12511. }
  12512. /**
  12513. *
  12514. * Set element as highlight / downplay dispatcher.
  12515. * It will be checked when element received mouseover event or from highlight action.
  12516. * It's in change of all highlight/downplay behavior of it's children.
  12517. *
  12518. * @param el
  12519. * @param el.highDownSilentOnTouch
  12520. * In touch device, mouseover event will be trigger on touchstart event
  12521. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12522. * conveniently use hoverStyle when tap on touch screen without additional
  12523. * code for compatibility.
  12524. * But if the chart/component has select feature, which usually also use
  12525. * hoverStyle, there might be conflict between 'select-highlight' and
  12526. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12527. * In this case, `highDownSilentOnTouch` should be used to disable
  12528. * hover-highlight on touch device.
  12529. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12530. */
  12531. function setAsHighDownDispatcher(el, asDispatcher) {
  12532. var disable = asDispatcher === false;
  12533. var extendedEl = el;
  12534. // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12535. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12536. if (el.highDownSilentOnTouch) {
  12537. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12538. }
  12539. // Simple optimize, since this method might be
  12540. // called for each elements of a group in some cases.
  12541. if (!disable || extendedEl.__highDownDispatcher) {
  12542. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12543. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12544. // Also keep previous record.
  12545. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12546. extendedEl.__highDownDispatcher = !disable;
  12547. }
  12548. }
  12549. function isHighDownDispatcher(el) {
  12550. return !!(el && el.__highDownDispatcher);
  12551. }
  12552. /**
  12553. * Support highlight/downplay record on each elements.
  12554. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12555. * user triggered highlight/downplay should not conflict.
  12556. * Only all of the highlightDigit cleared, return to normal.
  12557. * @param {string} highlightKey
  12558. * @return {number} highlightDigit
  12559. */
  12560. function getHighlightDigit(highlightKey) {
  12561. var highlightDigit = _highlightKeyMap[highlightKey];
  12562. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12563. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12564. }
  12565. return highlightDigit;
  12566. }
  12567. function isSelectChangePayload(payload) {
  12568. var payloadType = payload.type;
  12569. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12570. }
  12571. function isHighDownPayload(payload) {
  12572. var payloadType = payload.type;
  12573. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12574. }
  12575. function savePathStates(el) {
  12576. var store = getSavedStates(el);
  12577. store.normalFill = el.style.fill;
  12578. store.normalStroke = el.style.stroke;
  12579. var selectState = el.states.select || {};
  12580. store.selectFill = selectState.style && selectState.style.fill || null;
  12581. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12582. }
  12583. var CMD$2 = PathProxy.CMD;
  12584. var points = [[], [], []];
  12585. var mathSqrt$1 = Math.sqrt;
  12586. var mathAtan2 = Math.atan2;
  12587. function transformPath(path, m) {
  12588. if (!m) {
  12589. return;
  12590. }
  12591. var data = path.data;
  12592. var len = path.len();
  12593. var cmd;
  12594. var nPoint;
  12595. var i;
  12596. var j;
  12597. var k;
  12598. var p;
  12599. var M = CMD$2.M;
  12600. var C = CMD$2.C;
  12601. var L = CMD$2.L;
  12602. var R = CMD$2.R;
  12603. var A = CMD$2.A;
  12604. var Q = CMD$2.Q;
  12605. for (i = 0, j = 0; i < len;) {
  12606. cmd = data[i++];
  12607. j = i;
  12608. nPoint = 0;
  12609. switch (cmd) {
  12610. case M:
  12611. nPoint = 1;
  12612. break;
  12613. case L:
  12614. nPoint = 1;
  12615. break;
  12616. case C:
  12617. nPoint = 3;
  12618. break;
  12619. case Q:
  12620. nPoint = 2;
  12621. break;
  12622. case A:
  12623. var x = m[4];
  12624. var y = m[5];
  12625. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12626. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12627. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12628. data[i] *= sx;
  12629. data[i++] += x;
  12630. data[i] *= sy;
  12631. data[i++] += y;
  12632. data[i++] *= sx;
  12633. data[i++] *= sy;
  12634. data[i++] += angle;
  12635. data[i++] += angle;
  12636. i += 2;
  12637. j = i;
  12638. break;
  12639. case R:
  12640. p[0] = data[i++];
  12641. p[1] = data[i++];
  12642. applyTransform(p, p, m);
  12643. data[j++] = p[0];
  12644. data[j++] = p[1];
  12645. p[0] += data[i++];
  12646. p[1] += data[i++];
  12647. applyTransform(p, p, m);
  12648. data[j++] = p[0];
  12649. data[j++] = p[1];
  12650. }
  12651. for (k = 0; k < nPoint; k++) {
  12652. var p_1 = points[k];
  12653. p_1[0] = data[i++];
  12654. p_1[1] = data[i++];
  12655. applyTransform(p_1, p_1, m);
  12656. data[j++] = p_1[0];
  12657. data[j++] = p_1[1];
  12658. }
  12659. }
  12660. path.increaseVersion();
  12661. }
  12662. var mathSqrt$2 = Math.sqrt;
  12663. var mathSin$2 = Math.sin;
  12664. var mathCos$2 = Math.cos;
  12665. var PI$1 = Math.PI;
  12666. function vMag(v) {
  12667. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12668. }
  12669. function vRatio(u, v) {
  12670. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12671. }
  12672. function vAngle(u, v) {
  12673. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12674. * Math.acos(vRatio(u, v));
  12675. }
  12676. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12677. var psi = psiDeg * (PI$1 / 180.0);
  12678. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12679. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12680. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12681. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12682. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12683. if (lambda > 1) {
  12684. rx *= mathSqrt$2(lambda);
  12685. ry *= mathSqrt$2(lambda);
  12686. }
  12687. var f = (fa === fs ? -1 : 1)
  12688. * mathSqrt$2((((rx * rx) * (ry * ry))
  12689. - ((rx * rx) * (yp * yp))
  12690. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12691. + (ry * ry) * (xp * xp))) || 0;
  12692. var cxp = f * rx * yp / ry;
  12693. var cyp = f * -ry * xp / rx;
  12694. var cx = (x1 + x2) / 2.0
  12695. + mathCos$2(psi) * cxp
  12696. - mathSin$2(psi) * cyp;
  12697. var cy = (y1 + y2) / 2.0
  12698. + mathSin$2(psi) * cxp
  12699. + mathCos$2(psi) * cyp;
  12700. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12701. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12702. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12703. var dTheta = vAngle(u, v);
  12704. if (vRatio(u, v) <= -1) {
  12705. dTheta = PI$1;
  12706. }
  12707. if (vRatio(u, v) >= 1) {
  12708. dTheta = 0;
  12709. }
  12710. if (dTheta < 0) {
  12711. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12712. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12713. }
  12714. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12715. }
  12716. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12717. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12718. function createPathProxyFromString(data) {
  12719. var path = new PathProxy();
  12720. if (!data) {
  12721. return path;
  12722. }
  12723. var cpx = 0;
  12724. var cpy = 0;
  12725. var subpathX = cpx;
  12726. var subpathY = cpy;
  12727. var prevCmd;
  12728. var CMD = PathProxy.CMD;
  12729. var cmdList = data.match(commandReg);
  12730. if (!cmdList) {
  12731. return path;
  12732. }
  12733. for (var l = 0; l < cmdList.length; l++) {
  12734. var cmdText = cmdList[l];
  12735. var cmdStr = cmdText.charAt(0);
  12736. var cmd = void 0;
  12737. var p = cmdText.match(numberReg) || [];
  12738. var pLen = p.length;
  12739. for (var i = 0; i < pLen; i++) {
  12740. p[i] = parseFloat(p[i]);
  12741. }
  12742. var off = 0;
  12743. while (off < pLen) {
  12744. var ctlPtx = void 0;
  12745. var ctlPty = void 0;
  12746. var rx = void 0;
  12747. var ry = void 0;
  12748. var psi = void 0;
  12749. var fa = void 0;
  12750. var fs = void 0;
  12751. var x1 = cpx;
  12752. var y1 = cpy;
  12753. var len = void 0;
  12754. var pathData = void 0;
  12755. switch (cmdStr) {
  12756. case 'l':
  12757. cpx += p[off++];
  12758. cpy += p[off++];
  12759. cmd = CMD.L;
  12760. path.addData(cmd, cpx, cpy);
  12761. break;
  12762. case 'L':
  12763. cpx = p[off++];
  12764. cpy = p[off++];
  12765. cmd = CMD.L;
  12766. path.addData(cmd, cpx, cpy);
  12767. break;
  12768. case 'm':
  12769. cpx += p[off++];
  12770. cpy += p[off++];
  12771. cmd = CMD.M;
  12772. path.addData(cmd, cpx, cpy);
  12773. subpathX = cpx;
  12774. subpathY = cpy;
  12775. cmdStr = 'l';
  12776. break;
  12777. case 'M':
  12778. cpx = p[off++];
  12779. cpy = p[off++];
  12780. cmd = CMD.M;
  12781. path.addData(cmd, cpx, cpy);
  12782. subpathX = cpx;
  12783. subpathY = cpy;
  12784. cmdStr = 'L';
  12785. break;
  12786. case 'h':
  12787. cpx += p[off++];
  12788. cmd = CMD.L;
  12789. path.addData(cmd, cpx, cpy);
  12790. break;
  12791. case 'H':
  12792. cpx = p[off++];
  12793. cmd = CMD.L;
  12794. path.addData(cmd, cpx, cpy);
  12795. break;
  12796. case 'v':
  12797. cpy += p[off++];
  12798. cmd = CMD.L;
  12799. path.addData(cmd, cpx, cpy);
  12800. break;
  12801. case 'V':
  12802. cpy = p[off++];
  12803. cmd = CMD.L;
  12804. path.addData(cmd, cpx, cpy);
  12805. break;
  12806. case 'C':
  12807. cmd = CMD.C;
  12808. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12809. cpx = p[off - 2];
  12810. cpy = p[off - 1];
  12811. break;
  12812. case 'c':
  12813. cmd = CMD.C;
  12814. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12815. cpx += p[off - 2];
  12816. cpy += p[off - 1];
  12817. break;
  12818. case 'S':
  12819. ctlPtx = cpx;
  12820. ctlPty = cpy;
  12821. len = path.len();
  12822. pathData = path.data;
  12823. if (prevCmd === CMD.C) {
  12824. ctlPtx += cpx - pathData[len - 4];
  12825. ctlPty += cpy - pathData[len - 3];
  12826. }
  12827. cmd = CMD.C;
  12828. x1 = p[off++];
  12829. y1 = p[off++];
  12830. cpx = p[off++];
  12831. cpy = p[off++];
  12832. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12833. break;
  12834. case 's':
  12835. ctlPtx = cpx;
  12836. ctlPty = cpy;
  12837. len = path.len();
  12838. pathData = path.data;
  12839. if (prevCmd === CMD.C) {
  12840. ctlPtx += cpx - pathData[len - 4];
  12841. ctlPty += cpy - pathData[len - 3];
  12842. }
  12843. cmd = CMD.C;
  12844. x1 = cpx + p[off++];
  12845. y1 = cpy + p[off++];
  12846. cpx += p[off++];
  12847. cpy += p[off++];
  12848. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12849. break;
  12850. case 'Q':
  12851. x1 = p[off++];
  12852. y1 = p[off++];
  12853. cpx = p[off++];
  12854. cpy = p[off++];
  12855. cmd = CMD.Q;
  12856. path.addData(cmd, x1, y1, cpx, cpy);
  12857. break;
  12858. case 'q':
  12859. x1 = p[off++] + cpx;
  12860. y1 = p[off++] + cpy;
  12861. cpx += p[off++];
  12862. cpy += p[off++];
  12863. cmd = CMD.Q;
  12864. path.addData(cmd, x1, y1, cpx, cpy);
  12865. break;
  12866. case 'T':
  12867. ctlPtx = cpx;
  12868. ctlPty = cpy;
  12869. len = path.len();
  12870. pathData = path.data;
  12871. if (prevCmd === CMD.Q) {
  12872. ctlPtx += cpx - pathData[len - 4];
  12873. ctlPty += cpy - pathData[len - 3];
  12874. }
  12875. cpx = p[off++];
  12876. cpy = p[off++];
  12877. cmd = CMD.Q;
  12878. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12879. break;
  12880. case 't':
  12881. ctlPtx = cpx;
  12882. ctlPty = cpy;
  12883. len = path.len();
  12884. pathData = path.data;
  12885. if (prevCmd === CMD.Q) {
  12886. ctlPtx += cpx - pathData[len - 4];
  12887. ctlPty += cpy - pathData[len - 3];
  12888. }
  12889. cpx += p[off++];
  12890. cpy += p[off++];
  12891. cmd = CMD.Q;
  12892. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12893. break;
  12894. case 'A':
  12895. rx = p[off++];
  12896. ry = p[off++];
  12897. psi = p[off++];
  12898. fa = p[off++];
  12899. fs = p[off++];
  12900. x1 = cpx, y1 = cpy;
  12901. cpx = p[off++];
  12902. cpy = p[off++];
  12903. cmd = CMD.A;
  12904. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12905. break;
  12906. case 'a':
  12907. rx = p[off++];
  12908. ry = p[off++];
  12909. psi = p[off++];
  12910. fa = p[off++];
  12911. fs = p[off++];
  12912. x1 = cpx, y1 = cpy;
  12913. cpx += p[off++];
  12914. cpy += p[off++];
  12915. cmd = CMD.A;
  12916. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12917. break;
  12918. }
  12919. }
  12920. if (cmdStr === 'z' || cmdStr === 'Z') {
  12921. cmd = CMD.Z;
  12922. path.addData(cmd);
  12923. cpx = subpathX;
  12924. cpy = subpathY;
  12925. }
  12926. prevCmd = cmd;
  12927. }
  12928. path.toStatic();
  12929. return path;
  12930. }
  12931. var SVGPath = (function (_super) {
  12932. __extends(SVGPath, _super);
  12933. function SVGPath() {
  12934. return _super !== null && _super.apply(this, arguments) || this;
  12935. }
  12936. SVGPath.prototype.applyTransform = function (m) { };
  12937. return SVGPath;
  12938. }(Path));
  12939. function isPathProxy(path) {
  12940. return path.setData != null;
  12941. }
  12942. function createPathOptions(str, opts) {
  12943. var pathProxy = createPathProxyFromString(str);
  12944. var innerOpts = extend({}, opts);
  12945. innerOpts.buildPath = function (path) {
  12946. if (isPathProxy(path)) {
  12947. path.setData(pathProxy.data);
  12948. var ctx = path.getContext();
  12949. if (ctx) {
  12950. path.rebuildPath(ctx, 1);
  12951. }
  12952. }
  12953. else {
  12954. var ctx = path;
  12955. pathProxy.rebuildPath(ctx, 1);
  12956. }
  12957. };
  12958. innerOpts.applyTransform = function (m) {
  12959. transformPath(pathProxy, m);
  12960. this.dirtyShape();
  12961. };
  12962. return innerOpts;
  12963. }
  12964. function createFromString(str, opts) {
  12965. return new SVGPath(createPathOptions(str, opts));
  12966. }
  12967. function extendFromString(str, defaultOpts) {
  12968. var innerOpts = createPathOptions(str, defaultOpts);
  12969. var Sub = (function (_super) {
  12970. __extends(Sub, _super);
  12971. function Sub(opts) {
  12972. var _this = _super.call(this, opts) || this;
  12973. _this.applyTransform = innerOpts.applyTransform;
  12974. _this.buildPath = innerOpts.buildPath;
  12975. return _this;
  12976. }
  12977. return Sub;
  12978. }(SVGPath));
  12979. return Sub;
  12980. }
  12981. function mergePath(pathEls, opts) {
  12982. var pathList = [];
  12983. var len = pathEls.length;
  12984. for (var i = 0; i < len; i++) {
  12985. var pathEl = pathEls[i];
  12986. pathList.push(pathEl.getUpdatedPathProxy(true));
  12987. }
  12988. var pathBundle = new Path(opts);
  12989. pathBundle.createPathProxy();
  12990. pathBundle.buildPath = function (path) {
  12991. if (isPathProxy(path)) {
  12992. path.appendPath(pathList);
  12993. var ctx = path.getContext();
  12994. if (ctx) {
  12995. path.rebuildPath(ctx, 1);
  12996. }
  12997. }
  12998. };
  12999. return pathBundle;
  13000. }
  13001. var CircleShape = (function () {
  13002. function CircleShape() {
  13003. this.cx = 0;
  13004. this.cy = 0;
  13005. this.r = 0;
  13006. }
  13007. return CircleShape;
  13008. }());
  13009. var Circle = (function (_super) {
  13010. __extends(Circle, _super);
  13011. function Circle(opts) {
  13012. return _super.call(this, opts) || this;
  13013. }
  13014. Circle.prototype.getDefaultShape = function () {
  13015. return new CircleShape();
  13016. };
  13017. Circle.prototype.buildPath = function (ctx, shape) {
  13018. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13019. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13020. };
  13021. return Circle;
  13022. }(Path));
  13023. Circle.prototype.type = 'circle';
  13024. var EllipseShape = (function () {
  13025. function EllipseShape() {
  13026. this.cx = 0;
  13027. this.cy = 0;
  13028. this.rx = 0;
  13029. this.ry = 0;
  13030. }
  13031. return EllipseShape;
  13032. }());
  13033. var Ellipse = (function (_super) {
  13034. __extends(Ellipse, _super);
  13035. function Ellipse(opts) {
  13036. return _super.call(this, opts) || this;
  13037. }
  13038. Ellipse.prototype.getDefaultShape = function () {
  13039. return new EllipseShape();
  13040. };
  13041. Ellipse.prototype.buildPath = function (ctx, shape) {
  13042. var k = 0.5522848;
  13043. var x = shape.cx;
  13044. var y = shape.cy;
  13045. var a = shape.rx;
  13046. var b = shape.ry;
  13047. var ox = a * k;
  13048. var oy = b * k;
  13049. ctx.moveTo(x - a, y);
  13050. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13051. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13052. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13053. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13054. ctx.closePath();
  13055. };
  13056. return Ellipse;
  13057. }(Path));
  13058. Ellipse.prototype.type = 'ellipse';
  13059. var PI$2 = Math.PI;
  13060. var PI2$5 = PI$2 * 2;
  13061. var mathSin$3 = Math.sin;
  13062. var mathCos$3 = Math.cos;
  13063. var mathACos = Math.acos;
  13064. var mathATan2 = Math.atan2;
  13065. var mathAbs$1 = Math.abs;
  13066. var mathSqrt$3 = Math.sqrt;
  13067. var mathMax$3 = Math.max;
  13068. var mathMin$3 = Math.min;
  13069. var e = 1e-4;
  13070. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13071. var dx10 = x1 - x0;
  13072. var dy10 = y1 - y0;
  13073. var dx32 = x3 - x2;
  13074. var dy32 = y3 - y2;
  13075. var t = dy32 * dx10 - dx32 * dy10;
  13076. if (t * t < e) {
  13077. return;
  13078. }
  13079. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13080. return [x0 + t * dx10, y0 + t * dy10];
  13081. }
  13082. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13083. var x01 = x0 - x1;
  13084. var y01 = y0 - y1;
  13085. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13086. var ox = lo * y01;
  13087. var oy = -lo * x01;
  13088. var x11 = x0 + ox;
  13089. var y11 = y0 + oy;
  13090. var x10 = x1 + ox;
  13091. var y10 = y1 + oy;
  13092. var x00 = (x11 + x10) / 2;
  13093. var y00 = (y11 + y10) / 2;
  13094. var dx = x10 - x11;
  13095. var dy = y10 - y11;
  13096. var d2 = dx * dx + dy * dy;
  13097. var r = radius - cr;
  13098. var s = x11 * y10 - x10 * y11;
  13099. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  13100. var cx0 = (s * dy - dx * d) / d2;
  13101. var cy0 = (-s * dx - dy * d) / d2;
  13102. var cx1 = (s * dy + dx * d) / d2;
  13103. var cy1 = (-s * dx + dy * d) / d2;
  13104. var dx0 = cx0 - x00;
  13105. var dy0 = cy0 - y00;
  13106. var dx1 = cx1 - x00;
  13107. var dy1 = cy1 - y00;
  13108. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13109. cx0 = cx1;
  13110. cy0 = cy1;
  13111. }
  13112. return {
  13113. cx: cx0,
  13114. cy: cy0,
  13115. x0: -ox,
  13116. y0: -oy,
  13117. x1: cx0 * (radius / r - 1),
  13118. y1: cy0 * (radius / r - 1)
  13119. };
  13120. }
  13121. function normalizeCornerRadius(cr) {
  13122. var arr;
  13123. if (isArray(cr)) {
  13124. var len = cr.length;
  13125. if (!len) {
  13126. return cr;
  13127. }
  13128. if (len === 1) {
  13129. arr = [cr[0], cr[0], 0, 0];
  13130. }
  13131. else if (len === 2) {
  13132. arr = [cr[0], cr[0], cr[1], cr[1]];
  13133. }
  13134. else if (len === 3) {
  13135. arr = cr.concat(cr[2]);
  13136. }
  13137. else {
  13138. arr = cr;
  13139. }
  13140. }
  13141. else {
  13142. arr = [cr, cr, cr, cr];
  13143. }
  13144. return arr;
  13145. }
  13146. function buildPath$1(ctx, shape) {
  13147. var _a;
  13148. var radius = mathMax$3(shape.r, 0);
  13149. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13150. var hasRadius = radius > 0;
  13151. var hasInnerRadius = innerRadius > 0;
  13152. if (!hasRadius && !hasInnerRadius) {
  13153. return;
  13154. }
  13155. if (!hasRadius) {
  13156. radius = innerRadius;
  13157. innerRadius = 0;
  13158. }
  13159. if (innerRadius > radius) {
  13160. var tmp = radius;
  13161. radius = innerRadius;
  13162. innerRadius = tmp;
  13163. }
  13164. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13165. if (isNaN(startAngle) || isNaN(endAngle)) {
  13166. return;
  13167. }
  13168. var cx = shape.cx, cy = shape.cy;
  13169. var clockwise = !!shape.clockwise;
  13170. var arc = mathAbs$1(endAngle - startAngle);
  13171. var mod = arc > PI2$5 && arc % PI2$5;
  13172. mod > e && (arc = mod);
  13173. if (!(radius > e)) {
  13174. ctx.moveTo(cx, cy);
  13175. }
  13176. else if (arc > PI2$5 - e) {
  13177. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13178. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13179. if (innerRadius > e) {
  13180. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13181. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13182. }
  13183. }
  13184. else {
  13185. var icrStart = void 0;
  13186. var icrEnd = void 0;
  13187. var ocrStart = void 0;
  13188. var ocrEnd = void 0;
  13189. var ocrs = void 0;
  13190. var ocre = void 0;
  13191. var icrs = void 0;
  13192. var icre = void 0;
  13193. var ocrMax = void 0;
  13194. var icrMax = void 0;
  13195. var limitedOcrMax = void 0;
  13196. var limitedIcrMax = void 0;
  13197. var xre = void 0;
  13198. var yre = void 0;
  13199. var xirs = void 0;
  13200. var yirs = void 0;
  13201. var xrs = radius * mathCos$3(startAngle);
  13202. var yrs = radius * mathSin$3(startAngle);
  13203. var xire = innerRadius * mathCos$3(endAngle);
  13204. var yire = innerRadius * mathSin$3(endAngle);
  13205. var hasArc = arc > e;
  13206. if (hasArc) {
  13207. var cornerRadius = shape.cornerRadius;
  13208. if (cornerRadius) {
  13209. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13210. }
  13211. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13212. ocrs = mathMin$3(halfRd, ocrStart);
  13213. ocre = mathMin$3(halfRd, ocrEnd);
  13214. icrs = mathMin$3(halfRd, icrStart);
  13215. icre = mathMin$3(halfRd, icrEnd);
  13216. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13217. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13218. if (ocrMax > e || icrMax > e) {
  13219. xre = radius * mathCos$3(endAngle);
  13220. yre = radius * mathSin$3(endAngle);
  13221. xirs = innerRadius * mathCos$3(startAngle);
  13222. yirs = innerRadius * mathSin$3(startAngle);
  13223. if (arc < PI$2) {
  13224. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13225. if (it_1) {
  13226. var x0 = xrs - it_1[0];
  13227. var y0 = yrs - it_1[1];
  13228. var x1 = xre - it_1[0];
  13229. var y1 = yre - it_1[1];
  13230. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13231. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13232. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13233. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13234. }
  13235. }
  13236. }
  13237. }
  13238. if (!hasArc) {
  13239. ctx.moveTo(cx + xrs, cy + yrs);
  13240. }
  13241. else if (limitedOcrMax > e) {
  13242. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13243. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13244. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13245. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13246. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13247. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13248. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13249. }
  13250. else {
  13251. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13252. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13253. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13254. }
  13255. }
  13256. else {
  13257. ctx.moveTo(cx + xrs, cy + yrs);
  13258. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13259. }
  13260. if (!(innerRadius > e) || !hasArc) {
  13261. ctx.lineTo(cx + xire, cy + yire);
  13262. }
  13263. else if (limitedIcrMax > e) {
  13264. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13265. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13266. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13267. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13268. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13269. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13270. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13271. }
  13272. else {
  13273. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13274. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13275. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13276. }
  13277. }
  13278. else {
  13279. ctx.lineTo(cx + xire, cy + yire);
  13280. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13281. }
  13282. }
  13283. ctx.closePath();
  13284. }
  13285. var SectorShape = (function () {
  13286. function SectorShape() {
  13287. this.cx = 0;
  13288. this.cy = 0;
  13289. this.r0 = 0;
  13290. this.r = 0;
  13291. this.startAngle = 0;
  13292. this.endAngle = Math.PI * 2;
  13293. this.clockwise = true;
  13294. this.cornerRadius = 0;
  13295. }
  13296. return SectorShape;
  13297. }());
  13298. var Sector = (function (_super) {
  13299. __extends(Sector, _super);
  13300. function Sector(opts) {
  13301. return _super.call(this, opts) || this;
  13302. }
  13303. Sector.prototype.getDefaultShape = function () {
  13304. return new SectorShape();
  13305. };
  13306. Sector.prototype.buildPath = function (ctx, shape) {
  13307. buildPath$1(ctx, shape);
  13308. };
  13309. Sector.prototype.isZeroArea = function () {
  13310. return this.shape.startAngle === this.shape.endAngle
  13311. || this.shape.r === this.shape.r0;
  13312. };
  13313. return Sector;
  13314. }(Path));
  13315. Sector.prototype.type = 'sector';
  13316. var RingShape = (function () {
  13317. function RingShape() {
  13318. this.cx = 0;
  13319. this.cy = 0;
  13320. this.r = 0;
  13321. this.r0 = 0;
  13322. }
  13323. return RingShape;
  13324. }());
  13325. var Ring = (function (_super) {
  13326. __extends(Ring, _super);
  13327. function Ring(opts) {
  13328. return _super.call(this, opts) || this;
  13329. }
  13330. Ring.prototype.getDefaultShape = function () {
  13331. return new RingShape();
  13332. };
  13333. Ring.prototype.buildPath = function (ctx, shape) {
  13334. var x = shape.cx;
  13335. var y = shape.cy;
  13336. var PI2 = Math.PI * 2;
  13337. ctx.moveTo(x + shape.r, y);
  13338. ctx.arc(x, y, shape.r, 0, PI2, false);
  13339. ctx.moveTo(x + shape.r0, y);
  13340. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13341. };
  13342. return Ring;
  13343. }(Path));
  13344. Ring.prototype.type = 'ring';
  13345. function smoothBezier(points, smooth, isLoop, constraint) {
  13346. var cps = [];
  13347. var v = [];
  13348. var v1 = [];
  13349. var v2 = [];
  13350. var prevPoint;
  13351. var nextPoint;
  13352. var min$1;
  13353. var max$1;
  13354. if (constraint) {
  13355. min$1 = [Infinity, Infinity];
  13356. max$1 = [-Infinity, -Infinity];
  13357. for (var i = 0, len = points.length; i < len; i++) {
  13358. min(min$1, min$1, points[i]);
  13359. max(max$1, max$1, points[i]);
  13360. }
  13361. min(min$1, min$1, constraint[0]);
  13362. max(max$1, max$1, constraint[1]);
  13363. }
  13364. for (var i = 0, len = points.length; i < len; i++) {
  13365. var point = points[i];
  13366. if (isLoop) {
  13367. prevPoint = points[i ? i - 1 : len - 1];
  13368. nextPoint = points[(i + 1) % len];
  13369. }
  13370. else {
  13371. if (i === 0 || i === len - 1) {
  13372. cps.push(clone$1(points[i]));
  13373. continue;
  13374. }
  13375. else {
  13376. prevPoint = points[i - 1];
  13377. nextPoint = points[i + 1];
  13378. }
  13379. }
  13380. sub(v, nextPoint, prevPoint);
  13381. scale(v, v, smooth);
  13382. var d0 = distance(point, prevPoint);
  13383. var d1 = distance(point, nextPoint);
  13384. var sum = d0 + d1;
  13385. if (sum !== 0) {
  13386. d0 /= sum;
  13387. d1 /= sum;
  13388. }
  13389. scale(v1, v, -d0);
  13390. scale(v2, v, d1);
  13391. var cp0 = add([], point, v1);
  13392. var cp1 = add([], point, v2);
  13393. if (constraint) {
  13394. max(cp0, cp0, min$1);
  13395. min(cp0, cp0, max$1);
  13396. max(cp1, cp1, min$1);
  13397. min(cp1, cp1, max$1);
  13398. }
  13399. cps.push(cp0);
  13400. cps.push(cp1);
  13401. }
  13402. if (isLoop) {
  13403. cps.push(cps.shift());
  13404. }
  13405. return cps;
  13406. }
  13407. function buildPath$2(ctx, shape, closePath) {
  13408. var smooth = shape.smooth;
  13409. var points = shape.points;
  13410. if (points && points.length >= 2) {
  13411. if (smooth) {
  13412. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13413. ctx.moveTo(points[0][0], points[0][1]);
  13414. var len = points.length;
  13415. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13416. var cp1 = controlPoints[i * 2];
  13417. var cp2 = controlPoints[i * 2 + 1];
  13418. var p = points[(i + 1) % len];
  13419. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13420. }
  13421. }
  13422. else {
  13423. ctx.moveTo(points[0][0], points[0][1]);
  13424. for (var i = 1, l = points.length; i < l; i++) {
  13425. ctx.lineTo(points[i][0], points[i][1]);
  13426. }
  13427. }
  13428. closePath && ctx.closePath();
  13429. }
  13430. }
  13431. var PolygonShape = (function () {
  13432. function PolygonShape() {
  13433. this.points = null;
  13434. this.smooth = 0;
  13435. this.smoothConstraint = null;
  13436. }
  13437. return PolygonShape;
  13438. }());
  13439. var Polygon = (function (_super) {
  13440. __extends(Polygon, _super);
  13441. function Polygon(opts) {
  13442. return _super.call(this, opts) || this;
  13443. }
  13444. Polygon.prototype.getDefaultShape = function () {
  13445. return new PolygonShape();
  13446. };
  13447. Polygon.prototype.buildPath = function (ctx, shape) {
  13448. buildPath$2(ctx, shape, true);
  13449. };
  13450. return Polygon;
  13451. }(Path));
  13452. Polygon.prototype.type = 'polygon';
  13453. var PolylineShape = (function () {
  13454. function PolylineShape() {
  13455. this.points = null;
  13456. this.percent = 1;
  13457. this.smooth = 0;
  13458. this.smoothConstraint = null;
  13459. }
  13460. return PolylineShape;
  13461. }());
  13462. var Polyline = (function (_super) {
  13463. __extends(Polyline, _super);
  13464. function Polyline(opts) {
  13465. return _super.call(this, opts) || this;
  13466. }
  13467. Polyline.prototype.getDefaultStyle = function () {
  13468. return {
  13469. stroke: '#000',
  13470. fill: null
  13471. };
  13472. };
  13473. Polyline.prototype.getDefaultShape = function () {
  13474. return new PolylineShape();
  13475. };
  13476. Polyline.prototype.buildPath = function (ctx, shape) {
  13477. buildPath$2(ctx, shape, false);
  13478. };
  13479. return Polyline;
  13480. }(Path));
  13481. Polyline.prototype.type = 'polyline';
  13482. var subPixelOptimizeOutputShape$1 = {};
  13483. var LineShape = (function () {
  13484. function LineShape() {
  13485. this.x1 = 0;
  13486. this.y1 = 0;
  13487. this.x2 = 0;
  13488. this.y2 = 0;
  13489. this.percent = 1;
  13490. }
  13491. return LineShape;
  13492. }());
  13493. var Line = (function (_super) {
  13494. __extends(Line, _super);
  13495. function Line(opts) {
  13496. return _super.call(this, opts) || this;
  13497. }
  13498. Line.prototype.getDefaultStyle = function () {
  13499. return {
  13500. stroke: '#000',
  13501. fill: null
  13502. };
  13503. };
  13504. Line.prototype.getDefaultShape = function () {
  13505. return new LineShape();
  13506. };
  13507. Line.prototype.buildPath = function (ctx, shape) {
  13508. var x1;
  13509. var y1;
  13510. var x2;
  13511. var y2;
  13512. if (this.subPixelOptimize) {
  13513. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13514. x1 = optimizedShape.x1;
  13515. y1 = optimizedShape.y1;
  13516. x2 = optimizedShape.x2;
  13517. y2 = optimizedShape.y2;
  13518. }
  13519. else {
  13520. x1 = shape.x1;
  13521. y1 = shape.y1;
  13522. x2 = shape.x2;
  13523. y2 = shape.y2;
  13524. }
  13525. var percent = shape.percent;
  13526. if (percent === 0) {
  13527. return;
  13528. }
  13529. ctx.moveTo(x1, y1);
  13530. if (percent < 1) {
  13531. x2 = x1 * (1 - percent) + x2 * percent;
  13532. y2 = y1 * (1 - percent) + y2 * percent;
  13533. }
  13534. ctx.lineTo(x2, y2);
  13535. };
  13536. Line.prototype.pointAt = function (p) {
  13537. var shape = this.shape;
  13538. return [
  13539. shape.x1 * (1 - p) + shape.x2 * p,
  13540. shape.y1 * (1 - p) + shape.y2 * p
  13541. ];
  13542. };
  13543. return Line;
  13544. }(Path));
  13545. Line.prototype.type = 'line';
  13546. var out = [];
  13547. var BezierCurveShape = (function () {
  13548. function BezierCurveShape() {
  13549. this.x1 = 0;
  13550. this.y1 = 0;
  13551. this.x2 = 0;
  13552. this.y2 = 0;
  13553. this.cpx1 = 0;
  13554. this.cpy1 = 0;
  13555. this.percent = 1;
  13556. }
  13557. return BezierCurveShape;
  13558. }());
  13559. function someVectorAt(shape, t, isTangent) {
  13560. var cpx2 = shape.cpx2;
  13561. var cpy2 = shape.cpy2;
  13562. if (cpx2 != null || cpy2 != null) {
  13563. return [
  13564. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13565. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13566. ];
  13567. }
  13568. else {
  13569. return [
  13570. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13571. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13572. ];
  13573. }
  13574. }
  13575. var BezierCurve = (function (_super) {
  13576. __extends(BezierCurve, _super);
  13577. function BezierCurve(opts) {
  13578. return _super.call(this, opts) || this;
  13579. }
  13580. BezierCurve.prototype.getDefaultStyle = function () {
  13581. return {
  13582. stroke: '#000',
  13583. fill: null
  13584. };
  13585. };
  13586. BezierCurve.prototype.getDefaultShape = function () {
  13587. return new BezierCurveShape();
  13588. };
  13589. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13590. var x1 = shape.x1;
  13591. var y1 = shape.y1;
  13592. var x2 = shape.x2;
  13593. var y2 = shape.y2;
  13594. var cpx1 = shape.cpx1;
  13595. var cpy1 = shape.cpy1;
  13596. var cpx2 = shape.cpx2;
  13597. var cpy2 = shape.cpy2;
  13598. var percent = shape.percent;
  13599. if (percent === 0) {
  13600. return;
  13601. }
  13602. ctx.moveTo(x1, y1);
  13603. if (cpx2 == null || cpy2 == null) {
  13604. if (percent < 1) {
  13605. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13606. cpx1 = out[1];
  13607. x2 = out[2];
  13608. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13609. cpy1 = out[1];
  13610. y2 = out[2];
  13611. }
  13612. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13613. }
  13614. else {
  13615. if (percent < 1) {
  13616. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13617. cpx1 = out[1];
  13618. cpx2 = out[2];
  13619. x2 = out[3];
  13620. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13621. cpy1 = out[1];
  13622. cpy2 = out[2];
  13623. y2 = out[3];
  13624. }
  13625. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13626. }
  13627. };
  13628. BezierCurve.prototype.pointAt = function (t) {
  13629. return someVectorAt(this.shape, t, false);
  13630. };
  13631. BezierCurve.prototype.tangentAt = function (t) {
  13632. var p = someVectorAt(this.shape, t, true);
  13633. return normalize(p, p);
  13634. };
  13635. return BezierCurve;
  13636. }(Path));
  13637. BezierCurve.prototype.type = 'bezier-curve';
  13638. var ArcShape = (function () {
  13639. function ArcShape() {
  13640. this.cx = 0;
  13641. this.cy = 0;
  13642. this.r = 0;
  13643. this.startAngle = 0;
  13644. this.endAngle = Math.PI * 2;
  13645. this.clockwise = true;
  13646. }
  13647. return ArcShape;
  13648. }());
  13649. var Arc = (function (_super) {
  13650. __extends(Arc, _super);
  13651. function Arc(opts) {
  13652. return _super.call(this, opts) || this;
  13653. }
  13654. Arc.prototype.getDefaultStyle = function () {
  13655. return {
  13656. stroke: '#000',
  13657. fill: null
  13658. };
  13659. };
  13660. Arc.prototype.getDefaultShape = function () {
  13661. return new ArcShape();
  13662. };
  13663. Arc.prototype.buildPath = function (ctx, shape) {
  13664. var x = shape.cx;
  13665. var y = shape.cy;
  13666. var r = Math.max(shape.r, 0);
  13667. var startAngle = shape.startAngle;
  13668. var endAngle = shape.endAngle;
  13669. var clockwise = shape.clockwise;
  13670. var unitX = Math.cos(startAngle);
  13671. var unitY = Math.sin(startAngle);
  13672. ctx.moveTo(unitX * r + x, unitY * r + y);
  13673. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13674. };
  13675. return Arc;
  13676. }(Path));
  13677. Arc.prototype.type = 'arc';
  13678. var CompoundPath = (function (_super) {
  13679. __extends(CompoundPath, _super);
  13680. function CompoundPath() {
  13681. var _this = _super !== null && _super.apply(this, arguments) || this;
  13682. _this.type = 'compound';
  13683. return _this;
  13684. }
  13685. CompoundPath.prototype._updatePathDirty = function () {
  13686. var paths = this.shape.paths;
  13687. var dirtyPath = this.shapeChanged();
  13688. for (var i = 0; i < paths.length; i++) {
  13689. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13690. }
  13691. if (dirtyPath) {
  13692. this.dirtyShape();
  13693. }
  13694. };
  13695. CompoundPath.prototype.beforeBrush = function () {
  13696. this._updatePathDirty();
  13697. var paths = this.shape.paths || [];
  13698. var scale = this.getGlobalScale();
  13699. for (var i = 0; i < paths.length; i++) {
  13700. if (!paths[i].path) {
  13701. paths[i].createPathProxy();
  13702. }
  13703. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13704. }
  13705. };
  13706. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13707. var paths = shape.paths || [];
  13708. for (var i = 0; i < paths.length; i++) {
  13709. paths[i].buildPath(ctx, paths[i].shape, true);
  13710. }
  13711. };
  13712. CompoundPath.prototype.afterBrush = function () {
  13713. var paths = this.shape.paths || [];
  13714. for (var i = 0; i < paths.length; i++) {
  13715. paths[i].pathUpdated();
  13716. }
  13717. };
  13718. CompoundPath.prototype.getBoundingRect = function () {
  13719. this._updatePathDirty.call(this);
  13720. return Path.prototype.getBoundingRect.call(this);
  13721. };
  13722. return CompoundPath;
  13723. }(Path));
  13724. var Gradient = (function () {
  13725. function Gradient(colorStops) {
  13726. this.colorStops = colorStops || [];
  13727. }
  13728. Gradient.prototype.addColorStop = function (offset, color) {
  13729. this.colorStops.push({
  13730. offset: offset,
  13731. color: color
  13732. });
  13733. };
  13734. return Gradient;
  13735. }());
  13736. var LinearGradient = (function (_super) {
  13737. __extends(LinearGradient, _super);
  13738. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13739. var _this = _super.call(this, colorStops) || this;
  13740. _this.x = x == null ? 0 : x;
  13741. _this.y = y == null ? 0 : y;
  13742. _this.x2 = x2 == null ? 1 : x2;
  13743. _this.y2 = y2 == null ? 0 : y2;
  13744. _this.type = 'linear';
  13745. _this.global = globalCoord || false;
  13746. return _this;
  13747. }
  13748. return LinearGradient;
  13749. }(Gradient));
  13750. var RadialGradient = (function (_super) {
  13751. __extends(RadialGradient, _super);
  13752. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13753. var _this = _super.call(this, colorStops) || this;
  13754. _this.x = x == null ? 0.5 : x;
  13755. _this.y = y == null ? 0.5 : y;
  13756. _this.r = r == null ? 0.5 : r;
  13757. _this.type = 'radial';
  13758. _this.global = globalCoord || false;
  13759. return _this;
  13760. }
  13761. return RadialGradient;
  13762. }(Gradient));
  13763. var extent = [0, 0];
  13764. var extent2 = [0, 0];
  13765. var minTv$1 = new Point();
  13766. var maxTv$1 = new Point();
  13767. var OrientedBoundingRect = (function () {
  13768. function OrientedBoundingRect(rect, transform) {
  13769. this._corners = [];
  13770. this._axes = [];
  13771. this._origin = [0, 0];
  13772. for (var i = 0; i < 4; i++) {
  13773. this._corners[i] = new Point();
  13774. }
  13775. for (var i = 0; i < 2; i++) {
  13776. this._axes[i] = new Point();
  13777. }
  13778. if (rect) {
  13779. this.fromBoundingRect(rect, transform);
  13780. }
  13781. }
  13782. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13783. var corners = this._corners;
  13784. var axes = this._axes;
  13785. var x = rect.x;
  13786. var y = rect.y;
  13787. var x2 = x + rect.width;
  13788. var y2 = y + rect.height;
  13789. corners[0].set(x, y);
  13790. corners[1].set(x2, y);
  13791. corners[2].set(x2, y2);
  13792. corners[3].set(x, y2);
  13793. if (transform) {
  13794. for (var i = 0; i < 4; i++) {
  13795. corners[i].transform(transform);
  13796. }
  13797. }
  13798. Point.sub(axes[0], corners[1], corners[0]);
  13799. Point.sub(axes[1], corners[3], corners[0]);
  13800. axes[0].normalize();
  13801. axes[1].normalize();
  13802. for (var i = 0; i < 2; i++) {
  13803. this._origin[i] = axes[i].dot(corners[0]);
  13804. }
  13805. };
  13806. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13807. var overlapped = true;
  13808. var noMtv = !mtv;
  13809. minTv$1.set(Infinity, Infinity);
  13810. maxTv$1.set(0, 0);
  13811. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13812. overlapped = false;
  13813. if (noMtv) {
  13814. return overlapped;
  13815. }
  13816. }
  13817. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13818. overlapped = false;
  13819. if (noMtv) {
  13820. return overlapped;
  13821. }
  13822. }
  13823. if (!noMtv) {
  13824. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13825. }
  13826. return overlapped;
  13827. };
  13828. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13829. var overlapped = true;
  13830. for (var i = 0; i < 2; i++) {
  13831. var axis = this._axes[i];
  13832. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13833. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13834. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13835. overlapped = false;
  13836. if (noMtv) {
  13837. return overlapped;
  13838. }
  13839. var dist0 = Math.abs(extent2[0] - extent[1]);
  13840. var dist1 = Math.abs(extent[0] - extent2[1]);
  13841. if (Math.min(dist0, dist1) > maxTv.len()) {
  13842. if (dist0 < dist1) {
  13843. Point.scale(maxTv, axis, -dist0 * inverse);
  13844. }
  13845. else {
  13846. Point.scale(maxTv, axis, dist1 * inverse);
  13847. }
  13848. }
  13849. }
  13850. else if (minTv) {
  13851. var dist0 = Math.abs(extent2[0] - extent[1]);
  13852. var dist1 = Math.abs(extent[0] - extent2[1]);
  13853. if (Math.min(dist0, dist1) < minTv.len()) {
  13854. if (dist0 < dist1) {
  13855. Point.scale(minTv, axis, dist0 * inverse);
  13856. }
  13857. else {
  13858. Point.scale(minTv, axis, -dist1 * inverse);
  13859. }
  13860. }
  13861. }
  13862. }
  13863. return overlapped;
  13864. };
  13865. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13866. var axis = this._axes[dim];
  13867. var origin = this._origin;
  13868. var proj = corners[0].dot(axis) + origin[dim];
  13869. var min = proj;
  13870. var max = proj;
  13871. for (var i = 1; i < corners.length; i++) {
  13872. var proj_1 = corners[i].dot(axis) + origin[dim];
  13873. min = Math.min(proj_1, min);
  13874. max = Math.max(proj_1, max);
  13875. }
  13876. out[0] = min;
  13877. out[1] = max;
  13878. };
  13879. return OrientedBoundingRect;
  13880. }());
  13881. var m = [];
  13882. var IncrementalDisplayable = (function (_super) {
  13883. __extends(IncrementalDisplayable, _super);
  13884. function IncrementalDisplayable() {
  13885. var _this = _super !== null && _super.apply(this, arguments) || this;
  13886. _this.notClear = true;
  13887. _this.incremental = true;
  13888. _this._displayables = [];
  13889. _this._temporaryDisplayables = [];
  13890. _this._cursor = 0;
  13891. return _this;
  13892. }
  13893. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13894. cb.call(context, this);
  13895. };
  13896. IncrementalDisplayable.prototype.useStyle = function () {
  13897. this.style = {};
  13898. };
  13899. IncrementalDisplayable.prototype.getCursor = function () {
  13900. return this._cursor;
  13901. };
  13902. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13903. this._cursor = this._displayables.length;
  13904. };
  13905. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13906. this._displayables = [];
  13907. this._temporaryDisplayables = [];
  13908. this._cursor = 0;
  13909. this.markRedraw();
  13910. this.notClear = false;
  13911. };
  13912. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13913. this._temporaryDisplayables = [];
  13914. };
  13915. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13916. if (notPersistent) {
  13917. this._temporaryDisplayables.push(displayable);
  13918. }
  13919. else {
  13920. this._displayables.push(displayable);
  13921. }
  13922. this.markRedraw();
  13923. };
  13924. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13925. notPersistent = notPersistent || false;
  13926. for (var i = 0; i < displayables.length; i++) {
  13927. this.addDisplayable(displayables[i], notPersistent);
  13928. }
  13929. };
  13930. IncrementalDisplayable.prototype.getDisplayables = function () {
  13931. return this._displayables;
  13932. };
  13933. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13934. return this._temporaryDisplayables;
  13935. };
  13936. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13937. for (var i = this._cursor; i < this._displayables.length; i++) {
  13938. cb && cb(this._displayables[i]);
  13939. }
  13940. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13941. cb && cb(this._temporaryDisplayables[i]);
  13942. }
  13943. };
  13944. IncrementalDisplayable.prototype.update = function () {
  13945. this.updateTransform();
  13946. for (var i = this._cursor; i < this._displayables.length; i++) {
  13947. var displayable = this._displayables[i];
  13948. displayable.parent = this;
  13949. displayable.update();
  13950. displayable.parent = null;
  13951. }
  13952. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13953. var displayable = this._temporaryDisplayables[i];
  13954. displayable.parent = this;
  13955. displayable.update();
  13956. displayable.parent = null;
  13957. }
  13958. };
  13959. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13960. if (!this._rect) {
  13961. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13962. for (var i = 0; i < this._displayables.length; i++) {
  13963. var displayable = this._displayables[i];
  13964. var childRect = displayable.getBoundingRect().clone();
  13965. if (displayable.needLocalTransform()) {
  13966. childRect.applyTransform(displayable.getLocalTransform(m));
  13967. }
  13968. rect.union(childRect);
  13969. }
  13970. this._rect = rect;
  13971. }
  13972. return this._rect;
  13973. };
  13974. IncrementalDisplayable.prototype.contain = function (x, y) {
  13975. var localPos = this.transformCoordToLocal(x, y);
  13976. var rect = this.getBoundingRect();
  13977. if (rect.contain(localPos[0], localPos[1])) {
  13978. for (var i = 0; i < this._displayables.length; i++) {
  13979. var displayable = this._displayables[i];
  13980. if (displayable.contain(x, y)) {
  13981. return true;
  13982. }
  13983. }
  13984. }
  13985. return false;
  13986. };
  13987. return IncrementalDisplayable;
  13988. }(Displayable));
  13989. // Stored properties for further transition.
  13990. var transitionStore = makeInner();
  13991. /**
  13992. * Return null if animation is disabled.
  13993. */
  13994. function getAnimationConfig(animationType, animatableModel, dataIndex,
  13995. // Extra opts can override the option in animatable model.
  13996. extraOpts,
  13997. // TODO It's only for pictorial bar now.
  13998. extraDelayParams) {
  13999. var animationPayload;
  14000. // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  14001. // If animation is enabled. Will use this animation config in payload.
  14002. // If animation is disabled. Just ignore it.
  14003. if (animatableModel && animatableModel.ecModel) {
  14004. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  14005. animationPayload = updatePayload && updatePayload.animation;
  14006. }
  14007. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14008. var isUpdate = animationType === 'update';
  14009. if (animationEnabled) {
  14010. var duration = void 0;
  14011. var easing = void 0;
  14012. var delay = void 0;
  14013. if (extraOpts) {
  14014. duration = retrieve2(extraOpts.duration, 200);
  14015. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14016. delay = 0;
  14017. } else {
  14018. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14019. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14020. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14021. }
  14022. // animation from payload has highest priority.
  14023. if (animationPayload) {
  14024. animationPayload.duration != null && (duration = animationPayload.duration);
  14025. animationPayload.easing != null && (easing = animationPayload.easing);
  14026. animationPayload.delay != null && (delay = animationPayload.delay);
  14027. }
  14028. if (isFunction(delay)) {
  14029. delay = delay(dataIndex, extraDelayParams);
  14030. }
  14031. if (isFunction(duration)) {
  14032. duration = duration(dataIndex);
  14033. }
  14034. var config = {
  14035. duration: duration || 0,
  14036. delay: delay,
  14037. easing: easing
  14038. };
  14039. return config;
  14040. } else {
  14041. return null;
  14042. }
  14043. }
  14044. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14045. var isFrom = false;
  14046. var removeOpt;
  14047. if (isFunction(dataIndex)) {
  14048. during = cb;
  14049. cb = dataIndex;
  14050. dataIndex = null;
  14051. } else if (isObject(dataIndex)) {
  14052. cb = dataIndex.cb;
  14053. during = dataIndex.during;
  14054. isFrom = dataIndex.isFrom;
  14055. removeOpt = dataIndex.removeOpt;
  14056. dataIndex = dataIndex.dataIndex;
  14057. }
  14058. var isRemove = animationType === 'leave';
  14059. if (!isRemove) {
  14060. // Must stop the remove animation.
  14061. el.stopAnimation('leave');
  14062. }
  14063. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14064. if (animationConfig && animationConfig.duration > 0) {
  14065. var duration = animationConfig.duration;
  14066. var animationDelay = animationConfig.delay;
  14067. var animationEasing = animationConfig.easing;
  14068. var animateConfig = {
  14069. duration: duration,
  14070. delay: animationDelay || 0,
  14071. easing: animationEasing,
  14072. done: cb,
  14073. force: !!cb || !!during,
  14074. // Set to final state in update/init animation.
  14075. // So the post processing based on the path shape can be done correctly.
  14076. setToFinal: !isRemove,
  14077. scope: animationType,
  14078. during: during
  14079. };
  14080. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14081. } else {
  14082. el.stopAnimation();
  14083. // If `isFrom`, the props is the "from" props.
  14084. !isFrom && el.attr(props);
  14085. // Call during at least once.
  14086. during && during(1);
  14087. cb && cb();
  14088. }
  14089. }
  14090. /**
  14091. * Update graphic element properties with or without animation according to the
  14092. * configuration in series.
  14093. *
  14094. * Caution: this method will stop previous animation.
  14095. * So do not use this method to one element twice before
  14096. * animation starts, unless you know what you are doing.
  14097. * @example
  14098. * graphic.updateProps(el, {
  14099. * position: [100, 100]
  14100. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14101. * // Or
  14102. * graphic.updateProps(el, {
  14103. * position: [100, 100]
  14104. * }, seriesModel, function () { console.log('Animation done!'); });
  14105. */
  14106. function updateProps(el, props,
  14107. // TODO: TYPE AnimatableModel
  14108. animatableModel, dataIndex, cb, during) {
  14109. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14110. }
  14111. /**
  14112. * Init graphic element properties with or without animation according to the
  14113. * configuration in series.
  14114. *
  14115. * Caution: this method will stop previous animation.
  14116. * So do not use this method to one element twice before
  14117. * animation starts, unless you know what you are doing.
  14118. */
  14119. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14120. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14121. }
  14122. /**
  14123. * If element is removed.
  14124. * It can determine if element is having remove animation.
  14125. */
  14126. function isElementRemoved(el) {
  14127. if (!el.__zr) {
  14128. return true;
  14129. }
  14130. for (var i = 0; i < el.animators.length; i++) {
  14131. var animator = el.animators[i];
  14132. if (animator.scope === 'leave') {
  14133. return true;
  14134. }
  14135. }
  14136. return false;
  14137. }
  14138. /**
  14139. * Remove graphic element
  14140. */
  14141. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14142. // Don't do remove animation twice.
  14143. if (isElementRemoved(el)) {
  14144. return;
  14145. }
  14146. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14147. }
  14148. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14149. el.removeTextContent();
  14150. el.removeTextGuideLine();
  14151. removeElement(el, {
  14152. style: {
  14153. opacity: 0
  14154. }
  14155. }, animatableModel, dataIndex, done);
  14156. }
  14157. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14158. function doRemove() {
  14159. el.parent && el.parent.remove(el);
  14160. }
  14161. // Hide label and labelLine first
  14162. // TODO Also use fade out animation?
  14163. if (!el.isGroup) {
  14164. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14165. } else {
  14166. el.traverse(function (disp) {
  14167. if (!disp.isGroup) {
  14168. // Can invoke doRemove multiple times.
  14169. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14170. }
  14171. });
  14172. }
  14173. }
  14174. /**
  14175. * Save old style for style transition in universalTransition module.
  14176. * It's used when element will be reused in each render.
  14177. * For chart like map, heatmap, which will always create new element.
  14178. * We don't need to save this because universalTransition can get old style from the old element
  14179. */
  14180. function saveOldStyle(el) {
  14181. transitionStore(el).oldStyle = el.style;
  14182. }
  14183. var mathMax$4 = Math.max;
  14184. var mathMin$4 = Math.min;
  14185. var _customShapeMap = {};
  14186. /**
  14187. * Extend shape with parameters
  14188. */
  14189. function extendShape(opts) {
  14190. return Path.extend(opts);
  14191. }
  14192. var extendPathFromString = extendFromString;
  14193. /**
  14194. * Extend path
  14195. */
  14196. function extendPath(pathData, opts) {
  14197. return extendPathFromString(pathData, opts);
  14198. }
  14199. /**
  14200. * Register a user defined shape.
  14201. * The shape class can be fetched by `getShapeClass`
  14202. * This method will overwrite the registered shapes, including
  14203. * the registered built-in shapes, if using the same `name`.
  14204. * The shape can be used in `custom series` and
  14205. * `graphic component` by declaring `{type: name}`.
  14206. *
  14207. * @param name
  14208. * @param ShapeClass Can be generated by `extendShape`.
  14209. */
  14210. function registerShape(name, ShapeClass) {
  14211. _customShapeMap[name] = ShapeClass;
  14212. }
  14213. /**
  14214. * Find shape class registered by `registerShape`. Usually used in
  14215. * fetching user defined shape.
  14216. *
  14217. * [Caution]:
  14218. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14219. * to use user registered shapes.
  14220. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14221. * `registerShape` by default. That enables users to get both built-in
  14222. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14223. * the built-in shapes by using names like 'circle', 'rect' via calling
  14224. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14225. * in case that it is overwritten by users, except that some features, like
  14226. * `custom series`, `graphic component`, do it deliberately.
  14227. *
  14228. * (2) In the features like `custom series`, `graphic component`, the user input
  14229. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14230. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14231. * are reserved names, that is, if some user registers a shape named `'image'`,
  14232. * the shape will not be used. If we intending to add some more reserved names
  14233. * in feature, that might bring break changes (disable some existing user shape
  14234. * names). But that case probably rarely happens. So we don't make more mechanism
  14235. * to resolve this issue here.
  14236. *
  14237. * @param name
  14238. * @return The shape class. If not found, return nothing.
  14239. */
  14240. function getShapeClass(name) {
  14241. if (_customShapeMap.hasOwnProperty(name)) {
  14242. return _customShapeMap[name];
  14243. }
  14244. }
  14245. /**
  14246. * Create a path element from path data string
  14247. * @param pathData
  14248. * @param opts
  14249. * @param rect
  14250. * @param layout 'center' or 'cover' default to be cover
  14251. */
  14252. function makePath(pathData, opts, rect, layout) {
  14253. var path = createFromString(pathData, opts);
  14254. if (rect) {
  14255. if (layout === 'center') {
  14256. rect = centerGraphic(rect, path.getBoundingRect());
  14257. }
  14258. resizePath(path, rect);
  14259. }
  14260. return path;
  14261. }
  14262. /**
  14263. * Create a image element from image url
  14264. * @param imageUrl image url
  14265. * @param opts options
  14266. * @param rect constrain rect
  14267. * @param layout 'center' or 'cover'. Default to be 'cover'
  14268. */
  14269. function makeImage(imageUrl, rect, layout) {
  14270. var zrImg = new ZRImage({
  14271. style: {
  14272. image: imageUrl,
  14273. x: rect.x,
  14274. y: rect.y,
  14275. width: rect.width,
  14276. height: rect.height
  14277. },
  14278. onload: function (img) {
  14279. if (layout === 'center') {
  14280. var boundingRect = {
  14281. width: img.width,
  14282. height: img.height
  14283. };
  14284. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14285. }
  14286. }
  14287. });
  14288. return zrImg;
  14289. }
  14290. /**
  14291. * Get position of centered element in bounding box.
  14292. *
  14293. * @param rect element local bounding box
  14294. * @param boundingRect constraint bounding box
  14295. * @return element position containing x, y, width, and height
  14296. */
  14297. function centerGraphic(rect, boundingRect) {
  14298. // Set rect to center, keep width / height ratio.
  14299. var aspect = boundingRect.width / boundingRect.height;
  14300. var width = rect.height * aspect;
  14301. var height;
  14302. if (width <= rect.width) {
  14303. height = rect.height;
  14304. } else {
  14305. width = rect.width;
  14306. height = width / aspect;
  14307. }
  14308. var cx = rect.x + rect.width / 2;
  14309. var cy = rect.y + rect.height / 2;
  14310. return {
  14311. x: cx - width / 2,
  14312. y: cy - height / 2,
  14313. width: width,
  14314. height: height
  14315. };
  14316. }
  14317. var mergePath$1 = mergePath;
  14318. /**
  14319. * Resize a path to fit the rect
  14320. * @param path
  14321. * @param rect
  14322. */
  14323. function resizePath(path, rect) {
  14324. if (!path.applyTransform) {
  14325. return;
  14326. }
  14327. var pathRect = path.getBoundingRect();
  14328. var m = pathRect.calculateTransform(rect);
  14329. path.applyTransform(m);
  14330. }
  14331. /**
  14332. * Sub pixel optimize line for canvas
  14333. */
  14334. function subPixelOptimizeLine$1(shape, lineWidth) {
  14335. subPixelOptimizeLine(shape, shape, {
  14336. lineWidth: lineWidth
  14337. });
  14338. return shape;
  14339. }
  14340. /**
  14341. * Get transform matrix of target (param target),
  14342. * in coordinate of its ancestor (param ancestor)
  14343. *
  14344. * @param target
  14345. * @param [ancestor]
  14346. */
  14347. function getTransform(target, ancestor) {
  14348. var mat = identity([]);
  14349. while (target && target !== ancestor) {
  14350. mul$1(mat, target.getLocalTransform(), mat);
  14351. target = target.parent;
  14352. }
  14353. return mat;
  14354. }
  14355. function isNotGroup(el) {
  14356. return !el.isGroup;
  14357. }
  14358. function isPath(el) {
  14359. return el.shape != null;
  14360. }
  14361. /**
  14362. * Apply group transition animation from g1 to g2.
  14363. * If no animatableModel, no animation.
  14364. */
  14365. function groupTransition(g1, g2, animatableModel) {
  14366. if (!g1 || !g2) {
  14367. return;
  14368. }
  14369. function getElMap(g) {
  14370. var elMap = {};
  14371. g.traverse(function (el) {
  14372. if (isNotGroup(el) && el.anid) {
  14373. elMap[el.anid] = el;
  14374. }
  14375. });
  14376. return elMap;
  14377. }
  14378. function getAnimatableProps(el) {
  14379. var obj = {
  14380. x: el.x,
  14381. y: el.y,
  14382. rotation: el.rotation
  14383. };
  14384. if (isPath(el)) {
  14385. obj.shape = extend({}, el.shape);
  14386. }
  14387. return obj;
  14388. }
  14389. var elMap1 = getElMap(g1);
  14390. g2.traverse(function (el) {
  14391. if (isNotGroup(el) && el.anid) {
  14392. var oldEl = elMap1[el.anid];
  14393. if (oldEl) {
  14394. var newProp = getAnimatableProps(el);
  14395. el.attr(getAnimatableProps(oldEl));
  14396. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14397. }
  14398. }
  14399. });
  14400. }
  14401. function clipPointsByRect(points, rect) {
  14402. // FIXME: This way might be incorrect when graphic clipped by a corner
  14403. // and when element has a border.
  14404. return map(points, function (point) {
  14405. var x = point[0];
  14406. x = mathMax$4(x, rect.x);
  14407. x = mathMin$4(x, rect.x + rect.width);
  14408. var y = point[1];
  14409. y = mathMax$4(y, rect.y);
  14410. y = mathMin$4(y, rect.y + rect.height);
  14411. return [x, y];
  14412. });
  14413. }
  14414. /**
  14415. * Return a new clipped rect. If rect size are negative, return undefined.
  14416. */
  14417. function clipRectByRect(targetRect, rect) {
  14418. var x = mathMax$4(targetRect.x, rect.x);
  14419. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14420. var y = mathMax$4(targetRect.y, rect.y);
  14421. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height);
  14422. // If the total rect is cliped, nothing, including the border,
  14423. // should be painted. So return undefined.
  14424. if (x2 >= x && y2 >= y) {
  14425. return {
  14426. x: x,
  14427. y: y,
  14428. width: x2 - x,
  14429. height: y2 - y
  14430. };
  14431. }
  14432. }
  14433. function createIcon(iconStr,
  14434. // Support 'image://' or 'path://' or direct svg path.
  14435. opt, rect) {
  14436. var innerOpts = extend({
  14437. rectHover: true
  14438. }, opt);
  14439. var style = innerOpts.style = {
  14440. strokeNoScale: true
  14441. };
  14442. rect = rect || {
  14443. x: -1,
  14444. y: -1,
  14445. width: 2,
  14446. height: 2
  14447. };
  14448. if (iconStr) {
  14449. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14450. }
  14451. }
  14452. function setTooltipConfig(opt) {
  14453. var itemTooltipOption = opt.itemTooltipOption;
  14454. var componentModel = opt.componentModel;
  14455. var itemName = opt.itemName;
  14456. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14457. formatter: itemTooltipOption
  14458. } : itemTooltipOption;
  14459. var mainType = componentModel.mainType;
  14460. var componentIndex = componentModel.componentIndex;
  14461. var formatterParams = {
  14462. componentType: mainType,
  14463. name: itemName,
  14464. $vars: ['name']
  14465. };
  14466. formatterParams[mainType + 'Index'] = componentIndex;
  14467. var formatterParamsExtra = opt.formatterParamsExtra;
  14468. if (formatterParamsExtra) {
  14469. each(keys(formatterParamsExtra), function (key) {
  14470. if (!hasOwn(formatterParams, key)) {
  14471. formatterParams[key] = formatterParamsExtra[key];
  14472. formatterParams.$vars.push(key);
  14473. }
  14474. });
  14475. }
  14476. var ecData = getECData(opt.el);
  14477. ecData.componentMainType = mainType;
  14478. ecData.componentIndex = componentIndex;
  14479. ecData.tooltipConfig = {
  14480. name: itemName,
  14481. option: defaults({
  14482. content: itemName,
  14483. encodeHTMLContent: true,
  14484. formatterParams: formatterParams
  14485. }, itemTooltipOptionObj)
  14486. };
  14487. }
  14488. function traverseElement(el, cb) {
  14489. var stopped;
  14490. // TODO
  14491. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14492. if (el.isGroup) {
  14493. stopped = cb(el);
  14494. }
  14495. if (!stopped) {
  14496. el.traverse(cb);
  14497. }
  14498. }
  14499. function traverseElements(els, cb) {
  14500. if (els) {
  14501. if (isArray(els)) {
  14502. for (var i = 0; i < els.length; i++) {
  14503. traverseElement(els[i], cb);
  14504. }
  14505. } else {
  14506. traverseElement(els, cb);
  14507. }
  14508. }
  14509. }
  14510. // Register built-in shapes. These shapes might be overwritten
  14511. // by users, although we do not recommend that.
  14512. registerShape('circle', Circle);
  14513. registerShape('ellipse', Ellipse);
  14514. registerShape('sector', Sector);
  14515. registerShape('ring', Ring);
  14516. registerShape('polygon', Polygon);
  14517. registerShape('polyline', Polyline);
  14518. registerShape('rect', Rect);
  14519. registerShape('line', Line);
  14520. registerShape('bezierCurve', BezierCurve);
  14521. registerShape('arc', Arc);
  14522. var EMPTY_OBJ = {};
  14523. function setLabelText(label, labelTexts) {
  14524. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14525. var stateName = SPECIAL_STATES[i];
  14526. var text = labelTexts[stateName];
  14527. var state = label.ensureState(stateName);
  14528. state.style = state.style || {};
  14529. state.style.text = text;
  14530. }
  14531. var oldStates = label.currentStates.slice();
  14532. label.clearStates(true);
  14533. label.setStyle({
  14534. text: labelTexts.normal
  14535. });
  14536. label.useStates(oldStates, true);
  14537. }
  14538. function getLabelText(opt, stateModels, interpolatedValue) {
  14539. var labelFetcher = opt.labelFetcher;
  14540. var labelDataIndex = opt.labelDataIndex;
  14541. var labelDimIndex = opt.labelDimIndex;
  14542. var normalModel = stateModels.normal;
  14543. var baseText;
  14544. if (labelFetcher) {
  14545. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14546. interpolatedValue: interpolatedValue
  14547. } : null);
  14548. }
  14549. if (baseText == null) {
  14550. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14551. }
  14552. var statesText = {
  14553. normal: baseText
  14554. };
  14555. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14556. var stateName = SPECIAL_STATES[i];
  14557. var stateModel = stateModels[stateName];
  14558. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14559. }
  14560. return statesText;
  14561. }
  14562. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified
  14563. // TODO specified position?
  14564. ) {
  14565. opt = opt || EMPTY_OBJ;
  14566. var isSetOnText = targetEl instanceof ZRText;
  14567. var needsCreateText = false;
  14568. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14569. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14570. if (stateModel && stateModel.getShallow('show')) {
  14571. needsCreateText = true;
  14572. break;
  14573. }
  14574. }
  14575. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14576. if (needsCreateText) {
  14577. if (!isSetOnText) {
  14578. // Reuse the previous
  14579. if (!textContent) {
  14580. textContent = new ZRText();
  14581. targetEl.setTextContent(textContent);
  14582. }
  14583. // Use same state proxy
  14584. if (targetEl.stateProxy) {
  14585. textContent.stateProxy = targetEl.stateProxy;
  14586. }
  14587. }
  14588. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14589. var normalModel = labelStatesModels.normal;
  14590. var showNormal = !!normalModel.getShallow('show');
  14591. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14592. normalStyle.text = labelStatesTexts.normal;
  14593. if (!isSetOnText) {
  14594. // Always create new
  14595. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14596. }
  14597. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14598. var stateName = SPECIAL_STATES[i];
  14599. var stateModel = labelStatesModels[stateName];
  14600. if (stateModel) {
  14601. var stateObj = textContent.ensureState(stateName);
  14602. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14603. if (stateShow !== showNormal) {
  14604. stateObj.ignore = !stateShow;
  14605. }
  14606. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14607. stateObj.style.text = labelStatesTexts[stateName];
  14608. if (!isSetOnText) {
  14609. var targetElEmphasisState = targetEl.ensureState(stateName);
  14610. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14611. }
  14612. }
  14613. }
  14614. // PENDING: if there is many requirements that emphasis position
  14615. // need to be different from normal position, we might consider
  14616. // auto silent is those cases.
  14617. textContent.silent = !!normalModel.getShallow('silent');
  14618. // Keep x and y
  14619. if (textContent.style.x != null) {
  14620. normalStyle.x = textContent.style.x;
  14621. }
  14622. if (textContent.style.y != null) {
  14623. normalStyle.y = textContent.style.y;
  14624. }
  14625. textContent.ignore = !showNormal;
  14626. // Always create new style.
  14627. textContent.useStyle(normalStyle);
  14628. textContent.dirty();
  14629. if (opt.enableTextSetter) {
  14630. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14631. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14632. setLabelText(textContent, labelStatesTexts);
  14633. };
  14634. }
  14635. } else if (textContent) {
  14636. // Not display rich text.
  14637. textContent.ignore = true;
  14638. }
  14639. targetEl.dirty();
  14640. }
  14641. function getLabelStatesModels(itemModel, labelName) {
  14642. labelName = labelName || 'label';
  14643. var statesModels = {
  14644. normal: itemModel.getModel(labelName)
  14645. };
  14646. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14647. var stateName = SPECIAL_STATES[i];
  14648. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14649. }
  14650. return statesModels;
  14651. }
  14652. /**
  14653. * Set basic textStyle properties.
  14654. */
  14655. function createTextStyle(textStyleModel, specifiedTextStyle,
  14656. // Fixed style in the code. Can't be set by model.
  14657. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14658. ) {
  14659. var textStyle = {};
  14660. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14661. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14662. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14663. return textStyle;
  14664. }
  14665. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14666. opt = opt || {};
  14667. var textConfig = {};
  14668. var labelPosition;
  14669. var labelRotate = textStyleModel.getShallow('rotate');
  14670. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14671. var labelOffset = textStyleModel.getShallow('offset');
  14672. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside');
  14673. // 'outside' is not a valid zr textPostion value, but used
  14674. // in bar series, and magric type should be considered.
  14675. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14676. if (labelPosition != null) {
  14677. textConfig.position = labelPosition;
  14678. }
  14679. if (labelOffset != null) {
  14680. textConfig.offset = labelOffset;
  14681. }
  14682. if (labelRotate != null) {
  14683. labelRotate *= Math.PI / 180;
  14684. textConfig.rotation = labelRotate;
  14685. }
  14686. if (labelDistance != null) {
  14687. textConfig.distance = labelDistance;
  14688. }
  14689. // fill and auto is determined by the color of path fill if it's not specified by developers.
  14690. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14691. return textConfig;
  14692. }
  14693. /**
  14694. * The uniform entry of set text style, that is, retrieve style definitions
  14695. * from `model` and set to `textStyle` object.
  14696. *
  14697. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14698. * properties will be set. (Consider the states of normal and emphasis and
  14699. * default value can be adopted, merge would make the logic too complicated
  14700. * to manage.)
  14701. */
  14702. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14703. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14704. opt = opt || EMPTY_OBJ;
  14705. var ecModel = textStyleModel.ecModel;
  14706. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14707. // Consider case:
  14708. // {
  14709. // data: [{
  14710. // value: 12,
  14711. // label: {
  14712. // rich: {
  14713. // // no 'a' here but using parent 'a'.
  14714. // }
  14715. // }
  14716. // }],
  14717. // rich: {
  14718. // a: { ... }
  14719. // }
  14720. // }
  14721. var richItemNames = getRichItemNames(textStyleModel);
  14722. var richResult;
  14723. if (richItemNames) {
  14724. richResult = {};
  14725. for (var name_1 in richItemNames) {
  14726. if (richItemNames.hasOwnProperty(name_1)) {
  14727. // Cascade is supported in rich.
  14728. var richTextStyle = textStyleModel.getModel(['rich', name_1]);
  14729. // In rich, never `disableBox`.
  14730. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14731. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14732. // That might confuses users. So probably we should put `textStyleModel` as the
  14733. // root ancestor of the `richTextStyle`. But that would be a break change.
  14734. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14735. }
  14736. }
  14737. }
  14738. if (richResult) {
  14739. textStyle.rich = richResult;
  14740. }
  14741. var overflow = textStyleModel.get('overflow');
  14742. if (overflow) {
  14743. textStyle.overflow = overflow;
  14744. }
  14745. var margin = textStyleModel.get('minMargin');
  14746. if (margin != null) {
  14747. textStyle.margin = margin;
  14748. }
  14749. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14750. }
  14751. // Consider case:
  14752. // {
  14753. // data: [{
  14754. // value: 12,
  14755. // label: {
  14756. // rich: {
  14757. // // no 'a' here but using parent 'a'.
  14758. // }
  14759. // }
  14760. // }],
  14761. // rich: {
  14762. // a: { ... }
  14763. // }
  14764. // }
  14765. // TODO TextStyleModel
  14766. function getRichItemNames(textStyleModel) {
  14767. // Use object to remove duplicated names.
  14768. var richItemNameMap;
  14769. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14770. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14771. if (rich) {
  14772. richItemNameMap = richItemNameMap || {};
  14773. var richKeys = keys(rich);
  14774. for (var i = 0; i < richKeys.length; i++) {
  14775. var richKey = richKeys[i];
  14776. richItemNameMap[richKey] = 1;
  14777. }
  14778. }
  14779. textStyleModel = textStyleModel.parentModel;
  14780. }
  14781. return richItemNameMap;
  14782. }
  14783. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14784. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign', 'ellipsis'];
  14785. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14786. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14787. // In merge mode, default value should not be given.
  14788. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14789. var inheritColor = opt && opt.inheritColor;
  14790. var fillColor = textStyleModel.getShallow('color');
  14791. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14792. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14793. if (fillColor === 'inherit' || fillColor === 'auto') {
  14794. if ("development" !== 'production') {
  14795. if (fillColor === 'auto') {
  14796. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14797. }
  14798. }
  14799. if (inheritColor) {
  14800. fillColor = inheritColor;
  14801. } else {
  14802. fillColor = null;
  14803. }
  14804. }
  14805. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14806. if ("development" !== 'production') {
  14807. if (strokeColor === 'auto') {
  14808. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14809. }
  14810. }
  14811. if (inheritColor) {
  14812. strokeColor = inheritColor;
  14813. } else {
  14814. strokeColor = null;
  14815. }
  14816. }
  14817. if (!isAttached) {
  14818. // Only use default global textStyle.color if text is individual.
  14819. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14820. fillColor = fillColor || globalTextStyle.color;
  14821. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14822. }
  14823. if (fillColor != null) {
  14824. textStyle.fill = fillColor;
  14825. }
  14826. if (strokeColor != null) {
  14827. textStyle.stroke = strokeColor;
  14828. }
  14829. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14830. if (textBorderWidth != null) {
  14831. textStyle.lineWidth = textBorderWidth;
  14832. }
  14833. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14834. if (textBorderType != null) {
  14835. textStyle.lineDash = textBorderType;
  14836. }
  14837. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14838. if (textBorderDashOffset != null) {
  14839. textStyle.lineDashOffset = textBorderDashOffset;
  14840. }
  14841. if (!isNotNormal && opacity == null && !inRich) {
  14842. opacity = opt && opt.defaultOpacity;
  14843. }
  14844. if (opacity != null) {
  14845. textStyle.opacity = opacity;
  14846. }
  14847. // TODO
  14848. if (!isNotNormal && !isAttached) {
  14849. // Set default finally.
  14850. if (textStyle.fill == null && opt.inheritColor) {
  14851. textStyle.fill = opt.inheritColor;
  14852. }
  14853. }
  14854. // Do not use `getFont` here, because merge should be supported, where
  14855. // part of these properties may be changed in emphasis style, and the
  14856. // others should remain their original value got from normal style.
  14857. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14858. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14859. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14860. if (val != null) {
  14861. textStyle[key] = val;
  14862. }
  14863. }
  14864. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14865. var key = TEXT_PROPS_SELF[i];
  14866. var val = textStyleModel.getShallow(key);
  14867. if (val != null) {
  14868. textStyle[key] = val;
  14869. }
  14870. }
  14871. if (textStyle.verticalAlign == null) {
  14872. var baseline = textStyleModel.getShallow('baseline');
  14873. if (baseline != null) {
  14874. textStyle.verticalAlign = baseline;
  14875. }
  14876. }
  14877. if (!isBlock || !opt.disableBox) {
  14878. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  14879. var key = TEXT_PROPS_BOX[i];
  14880. var val = textStyleModel.getShallow(key);
  14881. if (val != null) {
  14882. textStyle[key] = val;
  14883. }
  14884. }
  14885. var borderType = textStyleModel.getShallow('borderType');
  14886. if (borderType != null) {
  14887. textStyle.borderDash = borderType;
  14888. }
  14889. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  14890. if ("development" !== 'production') {
  14891. if (textStyle.backgroundColor === 'auto') {
  14892. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  14893. }
  14894. }
  14895. textStyle.backgroundColor = inheritColor;
  14896. }
  14897. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  14898. if ("development" !== 'production') {
  14899. if (textStyle.borderColor === 'auto') {
  14900. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  14901. }
  14902. }
  14903. textStyle.borderColor = inheritColor;
  14904. }
  14905. }
  14906. }
  14907. function getFont(opt, ecModel) {
  14908. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14909. return trim([
  14910. // FIXME in node-canvas fontWeight is before fontStyle
  14911. 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(' '));
  14912. }
  14913. var labelInner = makeInner();
  14914. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  14915. if (!label) {
  14916. return;
  14917. }
  14918. var obj = labelInner(label);
  14919. obj.prevValue = obj.value;
  14920. obj.value = value;
  14921. var normalLabelModel = labelStatesModels.normal;
  14922. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  14923. if (obj.valueAnimation) {
  14924. obj.precision = normalLabelModel.get('precision');
  14925. obj.defaultInterpolatedText = getDefaultText;
  14926. obj.statesModels = labelStatesModels;
  14927. }
  14928. }
  14929. var PATH_COLOR = ['textStyle', 'color'];
  14930. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow'];
  14931. // TODO Performance improvement?
  14932. var tmpText = new ZRText();
  14933. var TextStyleMixin = /** @class */function () {
  14934. function TextStyleMixin() {}
  14935. /**
  14936. * Get color property or get color from option.textStyle.color
  14937. */
  14938. // TODO Callback
  14939. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  14940. var ecModel = this.ecModel;
  14941. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  14942. };
  14943. /**
  14944. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14945. * @return {string}
  14946. */
  14947. TextStyleMixin.prototype.getFont = function () {
  14948. return getFont({
  14949. fontStyle: this.getShallow('fontStyle'),
  14950. fontWeight: this.getShallow('fontWeight'),
  14951. fontSize: this.getShallow('fontSize'),
  14952. fontFamily: this.getShallow('fontFamily')
  14953. }, this.ecModel);
  14954. };
  14955. TextStyleMixin.prototype.getTextRect = function (text) {
  14956. var style = {
  14957. text: text,
  14958. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  14959. };
  14960. for (var i = 0; i < textStyleParams.length; i++) {
  14961. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  14962. }
  14963. tmpText.useStyle(style);
  14964. tmpText.update();
  14965. return tmpText.getBoundingRect();
  14966. };
  14967. return TextStyleMixin;
  14968. }();
  14969. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit']
  14970. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  14971. // So do not transfer decal directly.
  14972. ];
  14973. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  14974. var LineStyleMixin = /** @class */function () {
  14975. function LineStyleMixin() {}
  14976. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  14977. return getLineStyle(this, excludes);
  14978. };
  14979. return LineStyleMixin;
  14980. }();
  14981. 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']
  14982. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  14983. // So do not transfer decal directly.
  14984. ];
  14985. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  14986. var ItemStyleMixin = /** @class */function () {
  14987. function ItemStyleMixin() {}
  14988. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  14989. return getItemStyle(this, excludes, includes);
  14990. };
  14991. return ItemStyleMixin;
  14992. }();
  14993. var Model = /** @class */function () {
  14994. function Model(option, parentModel, ecModel) {
  14995. this.parentModel = parentModel;
  14996. this.ecModel = ecModel;
  14997. this.option = option;
  14998. // Simple optimization
  14999. // if (this.init) {
  15000. // if (arguments.length <= 4) {
  15001. // this.init(option, parentModel, ecModel, extraOpt);
  15002. // }
  15003. // else {
  15004. // this.init.apply(this, arguments);
  15005. // }
  15006. // }
  15007. }
  15008. Model.prototype.init = function (option, parentModel, ecModel) {
  15009. var rest = [];
  15010. for (var _i = 3; _i < arguments.length; _i++) {
  15011. rest[_i - 3] = arguments[_i];
  15012. }
  15013. };
  15014. /**
  15015. * Merge the input option to me.
  15016. */
  15017. Model.prototype.mergeOption = function (option, ecModel) {
  15018. merge(this.option, option, true);
  15019. };
  15020. // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15021. // TODO: TYPE strict key check?
  15022. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15023. Model.prototype.get = function (path, ignoreParent) {
  15024. if (path == null) {
  15025. return this.option;
  15026. }
  15027. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15028. };
  15029. Model.prototype.getShallow = function (key, ignoreParent) {
  15030. var option = this.option;
  15031. var val = option == null ? option : option[key];
  15032. if (val == null && !ignoreParent) {
  15033. var parentModel = this.parentModel;
  15034. if (parentModel) {
  15035. // FIXME:TS do not know how to make it works
  15036. val = parentModel.getShallow(key);
  15037. }
  15038. }
  15039. return val;
  15040. };
  15041. // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15042. // getModel(path: string | string[], parentModel?: Model): Model;
  15043. // TODO 'a.b.c' is deprecated
  15044. Model.prototype.getModel = function (path, parentModel) {
  15045. var hasPath = path != null;
  15046. var pathFinal = hasPath ? this.parsePath(path) : null;
  15047. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15048. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15049. return new Model(obj, parentModel, this.ecModel);
  15050. };
  15051. /**
  15052. * If model has option
  15053. */
  15054. Model.prototype.isEmpty = function () {
  15055. return this.option == null;
  15056. };
  15057. Model.prototype.restoreData = function () {};
  15058. // Pending
  15059. Model.prototype.clone = function () {
  15060. var Ctor = this.constructor;
  15061. return new Ctor(clone(this.option));
  15062. };
  15063. // setReadOnly(properties): void {
  15064. // clazzUtil.setReadOnly(this, properties);
  15065. // }
  15066. // If path is null/undefined, return null/undefined.
  15067. Model.prototype.parsePath = function (path) {
  15068. if (typeof path === 'string') {
  15069. return path.split('.');
  15070. }
  15071. return path;
  15072. };
  15073. // Resolve path for parent. Perhaps useful when parent use a different property.
  15074. // Default to be a identity resolver.
  15075. // Can be modified to a different resolver.
  15076. Model.prototype.resolveParentPath = function (path) {
  15077. return path;
  15078. };
  15079. // FIXME:TS check whether put this method here
  15080. Model.prototype.isAnimationEnabled = function () {
  15081. if (!env.node && this.option) {
  15082. if (this.option.animation != null) {
  15083. return !!this.option.animation;
  15084. } else if (this.parentModel) {
  15085. return this.parentModel.isAnimationEnabled();
  15086. }
  15087. }
  15088. };
  15089. Model.prototype._doGet = function (pathArr, parentModel) {
  15090. var obj = this.option;
  15091. if (!pathArr) {
  15092. return obj;
  15093. }
  15094. for (var i = 0; i < pathArr.length; i++) {
  15095. // Ignore empty
  15096. if (!pathArr[i]) {
  15097. continue;
  15098. }
  15099. // obj could be number/string/... (like 0)
  15100. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15101. if (obj == null) {
  15102. break;
  15103. }
  15104. }
  15105. if (obj == null && parentModel) {
  15106. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15107. }
  15108. return obj;
  15109. };
  15110. return Model;
  15111. }();
  15112. // Enable Model.extend.
  15113. enableClassExtend(Model);
  15114. enableClassCheck(Model);
  15115. mixin(Model, LineStyleMixin);
  15116. mixin(Model, ItemStyleMixin);
  15117. mixin(Model, AreaStyleMixin);
  15118. mixin(Model, TextStyleMixin);
  15119. // A random offset
  15120. var base = Math.round(Math.random() * 10);
  15121. /**
  15122. * @public
  15123. * @param {string} type
  15124. * @return {string}
  15125. */
  15126. function getUID(type) {
  15127. // Considering the case of crossing js context,
  15128. // use Math.random to make id as unique as possible.
  15129. return [type || '', base++].join('_');
  15130. }
  15131. /**
  15132. * Implements `SubTypeDefaulterManager` for `target`.
  15133. */
  15134. function enableSubTypeDefaulter(target) {
  15135. var subTypeDefaulters = {};
  15136. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15137. var componentTypeInfo = parseClassType(componentType);
  15138. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15139. };
  15140. target.determineSubType = function (componentType, option) {
  15141. var type = option.type;
  15142. if (!type) {
  15143. var componentTypeMain = parseClassType(componentType).main;
  15144. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15145. type = subTypeDefaulters[componentTypeMain](option);
  15146. }
  15147. }
  15148. return type;
  15149. };
  15150. }
  15151. /**
  15152. * Implements `TopologicalTravelable<any>` for `entity`.
  15153. *
  15154. * Topological travel on Activity Network (Activity On Vertices).
  15155. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15156. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15157. * If there is circular dependencey, Error will be thrown.
  15158. */
  15159. function enableTopologicalTravel(entity, dependencyGetter) {
  15160. /**
  15161. * @param targetNameList Target Component type list.
  15162. * Can be ['aa', 'bb', 'aa.xx']
  15163. * @param fullNameList By which we can build dependency graph.
  15164. * @param callback Params: componentType, dependencies.
  15165. * @param context Scope of callback.
  15166. */
  15167. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15168. if (!targetNameList.length) {
  15169. return;
  15170. }
  15171. var result = makeDepndencyGraph(fullNameList);
  15172. var graph = result.graph;
  15173. var noEntryList = result.noEntryList;
  15174. var targetNameSet = {};
  15175. each(targetNameList, function (name) {
  15176. targetNameSet[name] = true;
  15177. });
  15178. while (noEntryList.length) {
  15179. var currComponentType = noEntryList.pop();
  15180. var currVertex = graph[currComponentType];
  15181. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15182. if (isInTargetNameSet) {
  15183. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15184. delete targetNameSet[currComponentType];
  15185. }
  15186. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15187. }
  15188. each(targetNameSet, function () {
  15189. var errMsg = '';
  15190. if ("development" !== 'production') {
  15191. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15192. }
  15193. throw new Error(errMsg);
  15194. });
  15195. function removeEdge(succComponentType) {
  15196. graph[succComponentType].entryCount--;
  15197. if (graph[succComponentType].entryCount === 0) {
  15198. noEntryList.push(succComponentType);
  15199. }
  15200. }
  15201. // Consider this case: legend depends on series, and we call
  15202. // chart.setOption({series: [...]}), where only series is in option.
  15203. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15204. // not be called, but only sereis.mergeOption is called. Thus legend
  15205. // have no chance to update its local record about series (like which
  15206. // name of series is available in legend).
  15207. function removeEdgeAndAdd(succComponentType) {
  15208. targetNameSet[succComponentType] = true;
  15209. removeEdge(succComponentType);
  15210. }
  15211. };
  15212. function makeDepndencyGraph(fullNameList) {
  15213. var graph = {};
  15214. var noEntryList = [];
  15215. each(fullNameList, function (name) {
  15216. var thisItem = createDependencyGraphItem(graph, name);
  15217. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15218. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15219. thisItem.entryCount = availableDeps.length;
  15220. if (thisItem.entryCount === 0) {
  15221. noEntryList.push(name);
  15222. }
  15223. each(availableDeps, function (dependentName) {
  15224. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15225. thisItem.predecessor.push(dependentName);
  15226. }
  15227. var thatItem = createDependencyGraphItem(graph, dependentName);
  15228. if (indexOf(thatItem.successor, dependentName) < 0) {
  15229. thatItem.successor.push(name);
  15230. }
  15231. });
  15232. });
  15233. return {
  15234. graph: graph,
  15235. noEntryList: noEntryList
  15236. };
  15237. }
  15238. function createDependencyGraphItem(graph, name) {
  15239. if (!graph[name]) {
  15240. graph[name] = {
  15241. predecessor: [],
  15242. successor: []
  15243. };
  15244. }
  15245. return graph[name];
  15246. }
  15247. function getAvailableDependencies(originalDeps, fullNameList) {
  15248. var availableDeps = [];
  15249. each(originalDeps, function (dep) {
  15250. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15251. });
  15252. return availableDeps;
  15253. }
  15254. }
  15255. function inheritDefaultOption(superOption, subOption) {
  15256. // See also `model/Component.ts#getDefaultOption`
  15257. return merge(merge({}, superOption, true), subOption, true);
  15258. }
  15259. /*
  15260. * Licensed to the Apache Software Foundation (ASF) under one
  15261. * or more contributor license agreements. See the NOTICE file
  15262. * distributed with this work for additional information
  15263. * regarding copyright ownership. The ASF licenses this file
  15264. * to you under the Apache License, Version 2.0 (the
  15265. * "License"); you may not use this file except in compliance
  15266. * with the License. You may obtain a copy of the License at
  15267. *
  15268. * http://www.apache.org/licenses/LICENSE-2.0
  15269. *
  15270. * Unless required by applicable law or agreed to in writing,
  15271. * software distributed under the License is distributed on an
  15272. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15273. * KIND, either express or implied. See the License for the
  15274. * specific language governing permissions and limitations
  15275. * under the License.
  15276. */
  15277. /**
  15278. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15279. */
  15280. /*
  15281. * Licensed to the Apache Software Foundation (ASF) under one
  15282. * or more contributor license agreements. See the NOTICE file
  15283. * distributed with this work for additional information
  15284. * regarding copyright ownership. The ASF licenses this file
  15285. * to you under the Apache License, Version 2.0 (the
  15286. * "License"); you may not use this file except in compliance
  15287. * with the License. You may obtain a copy of the License at
  15288. *
  15289. * http://www.apache.org/licenses/LICENSE-2.0
  15290. *
  15291. * Unless required by applicable law or agreed to in writing,
  15292. * software distributed under the License is distributed on an
  15293. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15294. * KIND, either express or implied. See the License for the
  15295. * specific language governing permissions and limitations
  15296. * under the License.
  15297. */
  15298. /**
  15299. * Language: English.
  15300. */
  15301. var langEN = {
  15302. time: {
  15303. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15304. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15305. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15306. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15307. },
  15308. legend: {
  15309. selector: {
  15310. all: 'All',
  15311. inverse: 'Inv'
  15312. }
  15313. },
  15314. toolbox: {
  15315. brush: {
  15316. title: {
  15317. rect: 'Box Select',
  15318. polygon: 'Lasso Select',
  15319. lineX: 'Horizontally Select',
  15320. lineY: 'Vertically Select',
  15321. keep: 'Keep Selections',
  15322. clear: 'Clear Selections'
  15323. }
  15324. },
  15325. dataView: {
  15326. title: 'Data View',
  15327. lang: ['Data View', 'Close', 'Refresh']
  15328. },
  15329. dataZoom: {
  15330. title: {
  15331. zoom: 'Zoom',
  15332. back: 'Zoom Reset'
  15333. }
  15334. },
  15335. magicType: {
  15336. title: {
  15337. line: 'Switch to Line Chart',
  15338. bar: 'Switch to Bar Chart',
  15339. stack: 'Stack',
  15340. tiled: 'Tile'
  15341. }
  15342. },
  15343. restore: {
  15344. title: 'Restore'
  15345. },
  15346. saveAsImage: {
  15347. title: 'Save as Image',
  15348. lang: ['Right Click to Save Image']
  15349. }
  15350. },
  15351. series: {
  15352. typeNames: {
  15353. pie: 'Pie chart',
  15354. bar: 'Bar chart',
  15355. line: 'Line chart',
  15356. scatter: 'Scatter plot',
  15357. effectScatter: 'Ripple scatter plot',
  15358. radar: 'Radar chart',
  15359. tree: 'Tree',
  15360. treemap: 'Treemap',
  15361. boxplot: 'Boxplot',
  15362. candlestick: 'Candlestick',
  15363. k: 'K line chart',
  15364. heatmap: 'Heat map',
  15365. map: 'Map',
  15366. parallel: 'Parallel coordinate map',
  15367. lines: 'Line graph',
  15368. graph: 'Relationship graph',
  15369. sankey: 'Sankey diagram',
  15370. funnel: 'Funnel chart',
  15371. gauge: 'Gauge',
  15372. pictorialBar: 'Pictorial bar',
  15373. themeRiver: 'Theme River Map',
  15374. sunburst: 'Sunburst',
  15375. custom: 'Custom chart',
  15376. chart: 'Chart'
  15377. }
  15378. },
  15379. aria: {
  15380. general: {
  15381. withTitle: 'This is a chart about "{title}"',
  15382. withoutTitle: 'This is a chart'
  15383. },
  15384. series: {
  15385. single: {
  15386. prefix: '',
  15387. withName: ' with type {seriesType} named {seriesName}.',
  15388. withoutName: ' with type {seriesType}.'
  15389. },
  15390. multiple: {
  15391. prefix: '. It consists of {seriesCount} series count.',
  15392. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15393. withoutName: ' The {seriesId} series is a {seriesType}.',
  15394. separator: {
  15395. middle: '',
  15396. end: ''
  15397. }
  15398. }
  15399. },
  15400. data: {
  15401. allData: 'The data is as follows: ',
  15402. partialData: 'The first {displayCnt} items are: ',
  15403. withName: 'the data for {name} is {value}',
  15404. withoutName: '{value}',
  15405. separator: {
  15406. middle: ', ',
  15407. end: '. '
  15408. }
  15409. }
  15410. }
  15411. };
  15412. /*
  15413. * Licensed to the Apache Software Foundation (ASF) under one
  15414. * or more contributor license agreements. See the NOTICE file
  15415. * distributed with this work for additional information
  15416. * regarding copyright ownership. The ASF licenses this file
  15417. * to you under the Apache License, Version 2.0 (the
  15418. * "License"); you may not use this file except in compliance
  15419. * with the License. You may obtain a copy of the License at
  15420. *
  15421. * http://www.apache.org/licenses/LICENSE-2.0
  15422. *
  15423. * Unless required by applicable law or agreed to in writing,
  15424. * software distributed under the License is distributed on an
  15425. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15426. * KIND, either express or implied. See the License for the
  15427. * specific language governing permissions and limitations
  15428. * under the License.
  15429. */
  15430. /**
  15431. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15432. */
  15433. /*
  15434. * Licensed to the Apache Software Foundation (ASF) under one
  15435. * or more contributor license agreements. See the NOTICE file
  15436. * distributed with this work for additional information
  15437. * regarding copyright ownership. The ASF licenses this file
  15438. * to you under the Apache License, Version 2.0 (the
  15439. * "License"); you may not use this file except in compliance
  15440. * with the License. You may obtain a copy of the License at
  15441. *
  15442. * http://www.apache.org/licenses/LICENSE-2.0
  15443. *
  15444. * Unless required by applicable law or agreed to in writing,
  15445. * software distributed under the License is distributed on an
  15446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15447. * KIND, either express or implied. See the License for the
  15448. * specific language governing permissions and limitations
  15449. * under the License.
  15450. */
  15451. var langZH = {
  15452. time: {
  15453. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15454. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15455. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15456. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15457. },
  15458. legend: {
  15459. selector: {
  15460. all: '全选',
  15461. inverse: '反选'
  15462. }
  15463. },
  15464. toolbox: {
  15465. brush: {
  15466. title: {
  15467. rect: '矩形选择',
  15468. polygon: '圈选',
  15469. lineX: '横向选择',
  15470. lineY: '纵向选择',
  15471. keep: '保持选择',
  15472. clear: '清除选择'
  15473. }
  15474. },
  15475. dataView: {
  15476. title: '数据视图',
  15477. lang: ['数据视图', '关闭', '刷新']
  15478. },
  15479. dataZoom: {
  15480. title: {
  15481. zoom: '区域缩放',
  15482. back: '区域缩放还原'
  15483. }
  15484. },
  15485. magicType: {
  15486. title: {
  15487. line: '切换为折线图',
  15488. bar: '切换为柱状图',
  15489. stack: '切换为堆叠',
  15490. tiled: '切换为平铺'
  15491. }
  15492. },
  15493. restore: {
  15494. title: '还原'
  15495. },
  15496. saveAsImage: {
  15497. title: '保存为图片',
  15498. lang: ['右键另存为图片']
  15499. }
  15500. },
  15501. series: {
  15502. typeNames: {
  15503. pie: '饼图',
  15504. bar: '柱状图',
  15505. line: '折线图',
  15506. scatter: '散点图',
  15507. effectScatter: '涟漪散点图',
  15508. radar: '雷达图',
  15509. tree: '树图',
  15510. treemap: '矩形树图',
  15511. boxplot: '箱型图',
  15512. candlestick: 'K线图',
  15513. k: 'K线图',
  15514. heatmap: '热力图',
  15515. map: '地图',
  15516. parallel: '平行坐标图',
  15517. lines: '线图',
  15518. graph: '关系图',
  15519. sankey: '桑基图',
  15520. funnel: '漏斗图',
  15521. gauge: '仪表盘图',
  15522. pictorialBar: '象形柱图',
  15523. themeRiver: '主题河流图',
  15524. sunburst: '旭日图',
  15525. custom: '自定义图表',
  15526. chart: '图表'
  15527. }
  15528. },
  15529. aria: {
  15530. general: {
  15531. withTitle: '这是一个关于“{title}”的图表。',
  15532. withoutTitle: '这是一个图表,'
  15533. },
  15534. series: {
  15535. single: {
  15536. prefix: '',
  15537. withName: '图表类型是{seriesType},表示{seriesName}。',
  15538. withoutName: '图表类型是{seriesType}。'
  15539. },
  15540. multiple: {
  15541. prefix: '它由{seriesCount}个图表系列组成。',
  15542. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15543. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15544. separator: {
  15545. middle: ';',
  15546. end: '。'
  15547. }
  15548. }
  15549. },
  15550. data: {
  15551. allData: '其数据是——',
  15552. partialData: '其中,前{displayCnt}项是——',
  15553. withName: '{name}的数据是{value}',
  15554. withoutName: '{value}',
  15555. separator: {
  15556. middle: ',',
  15557. end: ''
  15558. }
  15559. }
  15560. }
  15561. };
  15562. var LOCALE_ZH = 'ZH';
  15563. var LOCALE_EN = 'EN';
  15564. var DEFAULT_LOCALE = LOCALE_EN;
  15565. var localeStorage = {};
  15566. var localeModels = {};
  15567. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15568. var langStr = ( /* eslint-disable-next-line */
  15569. document.documentElement.lang || navigator.language || navigator.browserLanguage || DEFAULT_LOCALE).toUpperCase();
  15570. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15571. }();
  15572. function registerLocale(locale, localeObj) {
  15573. locale = locale.toUpperCase();
  15574. localeModels[locale] = new Model(localeObj);
  15575. localeStorage[locale] = localeObj;
  15576. }
  15577. // export function getLocale(locale: string) {
  15578. // return localeStorage[locale];
  15579. // }
  15580. function createLocaleObject(locale) {
  15581. if (isString(locale)) {
  15582. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15583. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15584. return clone(localeObj);
  15585. } else {
  15586. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15587. }
  15588. } else {
  15589. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15590. }
  15591. }
  15592. function getLocaleModel(lang) {
  15593. return localeModels[lang];
  15594. }
  15595. function getDefaultLocaleModel() {
  15596. return localeModels[DEFAULT_LOCALE];
  15597. }
  15598. // Default locale
  15599. registerLocale(LOCALE_EN, langEN);
  15600. registerLocale(LOCALE_ZH, langZH);
  15601. var ONE_SECOND = 1000;
  15602. var ONE_MINUTE = ONE_SECOND * 60;
  15603. var ONE_HOUR = ONE_MINUTE * 60;
  15604. var ONE_DAY = ONE_HOUR * 24;
  15605. var ONE_YEAR = ONE_DAY * 365;
  15606. var defaultLeveledFormatter = {
  15607. year: '{yyyy}',
  15608. month: '{MMM}',
  15609. day: '{d}',
  15610. hour: '{HH}:{mm}',
  15611. minute: '{HH}:{mm}',
  15612. second: '{HH}:{mm}:{ss}',
  15613. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15614. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15615. };
  15616. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15617. var fullLeveledFormatter = {
  15618. year: '{yyyy}',
  15619. month: '{yyyy}-{MM}',
  15620. day: fullDayFormatter,
  15621. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15622. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15623. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15624. millisecond: defaultLeveledFormatter.none
  15625. };
  15626. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15627. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15628. function pad(str, len) {
  15629. str += '';
  15630. return '0000'.substr(0, len - str.length) + str;
  15631. }
  15632. function getPrimaryTimeUnit(timeUnit) {
  15633. switch (timeUnit) {
  15634. case 'half-year':
  15635. case 'quarter':
  15636. return 'month';
  15637. case 'week':
  15638. case 'half-week':
  15639. return 'day';
  15640. case 'half-day':
  15641. case 'quarter-day':
  15642. return 'hour';
  15643. default:
  15644. // year, minutes, second, milliseconds
  15645. return timeUnit;
  15646. }
  15647. }
  15648. function isPrimaryTimeUnit(timeUnit) {
  15649. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15650. }
  15651. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15652. switch (timeUnit) {
  15653. case 'year':
  15654. case 'month':
  15655. return 'day';
  15656. case 'millisecond':
  15657. return 'millisecond';
  15658. default:
  15659. // Also for day, hour, minute, second
  15660. return 'second';
  15661. }
  15662. }
  15663. function format(
  15664. // Note: The result based on `isUTC` are totally different, which can not be just simply
  15665. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15666. time, template, isUTC, lang) {
  15667. var date = parseDate(time);
  15668. var y = date[fullYearGetterName(isUTC)]();
  15669. var M = date[monthGetterName(isUTC)]() + 1;
  15670. var q = Math.floor((M - 1) / 3) + 1;
  15671. var d = date[dateGetterName(isUTC)]();
  15672. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15673. var H = date[hoursGetterName(isUTC)]();
  15674. var h = (H - 1) % 12 + 1;
  15675. var m = date[minutesGetterName(isUTC)]();
  15676. var s = date[secondsGetterName(isUTC)]();
  15677. var S = date[millisecondsGetterName(isUTC)]();
  15678. var a = H >= 12 ? 'pm' : 'am';
  15679. var A = a.toUpperCase();
  15680. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15681. var timeModel = localeModel.getModel('time');
  15682. var month = timeModel.get('month');
  15683. var monthAbbr = timeModel.get('monthAbbr');
  15684. var dayOfWeek = timeModel.get('dayOfWeek');
  15685. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15686. return (template || '').replace(/{a}/g, a + '').replace(/{A}/g, A + '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, pad(y % 100 + '', 2)).replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  15687. }
  15688. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15689. var template = null;
  15690. if (isString(formatter)) {
  15691. // Single formatter for all units at all levels
  15692. template = formatter;
  15693. } else if (isFunction(formatter)) {
  15694. // Callback formatter
  15695. template = formatter(tick.value, idx, {
  15696. level: tick.level
  15697. });
  15698. } else {
  15699. var defaults$1 = extend({}, defaultLeveledFormatter);
  15700. if (tick.level > 0) {
  15701. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15702. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15703. }
  15704. }
  15705. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15706. : defaults(formatter, defaults$1) : defaults$1;
  15707. var unit = getUnitFromValue(tick.value, isUTC);
  15708. if (mergedFormatter[unit]) {
  15709. template = mergedFormatter[unit];
  15710. } else if (mergedFormatter.inherit) {
  15711. // Unit formatter is not defined and should inherit from bigger units
  15712. var targetId = timeUnits.indexOf(unit);
  15713. for (var i = targetId - 1; i >= 0; --i) {
  15714. if (mergedFormatter[unit]) {
  15715. template = mergedFormatter[unit];
  15716. break;
  15717. }
  15718. }
  15719. template = template || defaults$1.none;
  15720. }
  15721. if (isArray(template)) {
  15722. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15723. levelId = Math.min(levelId, template.length - 1);
  15724. template = template[levelId];
  15725. }
  15726. }
  15727. return format(new Date(tick.value), template, isUTC, lang);
  15728. }
  15729. function getUnitFromValue(value, isUTC) {
  15730. var date = parseDate(value);
  15731. var M = date[monthGetterName(isUTC)]() + 1;
  15732. var d = date[dateGetterName(isUTC)]();
  15733. var h = date[hoursGetterName(isUTC)]();
  15734. var m = date[minutesGetterName(isUTC)]();
  15735. var s = date[secondsGetterName(isUTC)]();
  15736. var S = date[millisecondsGetterName(isUTC)]();
  15737. var isSecond = S === 0;
  15738. var isMinute = isSecond && s === 0;
  15739. var isHour = isMinute && m === 0;
  15740. var isDay = isHour && h === 0;
  15741. var isMonth = isDay && d === 1;
  15742. var isYear = isMonth && M === 1;
  15743. if (isYear) {
  15744. return 'year';
  15745. } else if (isMonth) {
  15746. return 'month';
  15747. } else if (isDay) {
  15748. return 'day';
  15749. } else if (isHour) {
  15750. return 'hour';
  15751. } else if (isMinute) {
  15752. return 'minute';
  15753. } else if (isSecond) {
  15754. return 'second';
  15755. } else {
  15756. return 'millisecond';
  15757. }
  15758. }
  15759. function getUnitValue(value, unit, isUTC) {
  15760. var date = isNumber(value) ? parseDate(value) : value;
  15761. unit = unit || getUnitFromValue(value, isUTC);
  15762. switch (unit) {
  15763. case 'year':
  15764. return date[fullYearGetterName(isUTC)]();
  15765. case 'half-year':
  15766. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15767. case 'quarter':
  15768. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15769. case 'month':
  15770. return date[monthGetterName(isUTC)]();
  15771. case 'day':
  15772. return date[dateGetterName(isUTC)]();
  15773. case 'half-day':
  15774. return date[hoursGetterName(isUTC)]() / 24;
  15775. case 'hour':
  15776. return date[hoursGetterName(isUTC)]();
  15777. case 'minute':
  15778. return date[minutesGetterName(isUTC)]();
  15779. case 'second':
  15780. return date[secondsGetterName(isUTC)]();
  15781. case 'millisecond':
  15782. return date[millisecondsGetterName(isUTC)]();
  15783. }
  15784. }
  15785. function fullYearGetterName(isUTC) {
  15786. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15787. }
  15788. function monthGetterName(isUTC) {
  15789. return isUTC ? 'getUTCMonth' : 'getMonth';
  15790. }
  15791. function dateGetterName(isUTC) {
  15792. return isUTC ? 'getUTCDate' : 'getDate';
  15793. }
  15794. function hoursGetterName(isUTC) {
  15795. return isUTC ? 'getUTCHours' : 'getHours';
  15796. }
  15797. function minutesGetterName(isUTC) {
  15798. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15799. }
  15800. function secondsGetterName(isUTC) {
  15801. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15802. }
  15803. function millisecondsGetterName(isUTC) {
  15804. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  15805. }
  15806. function fullYearSetterName(isUTC) {
  15807. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15808. }
  15809. function monthSetterName(isUTC) {
  15810. return isUTC ? 'setUTCMonth' : 'setMonth';
  15811. }
  15812. function dateSetterName(isUTC) {
  15813. return isUTC ? 'setUTCDate' : 'setDate';
  15814. }
  15815. function hoursSetterName(isUTC) {
  15816. return isUTC ? 'setUTCHours' : 'setHours';
  15817. }
  15818. function minutesSetterName(isUTC) {
  15819. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15820. }
  15821. function secondsSetterName(isUTC) {
  15822. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15823. }
  15824. function millisecondsSetterName(isUTC) {
  15825. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  15826. }
  15827. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15828. var textEl = new ZRText({
  15829. style: {
  15830. text: text,
  15831. font: font,
  15832. align: align,
  15833. verticalAlign: verticalAlign,
  15834. padding: padding,
  15835. rich: rich,
  15836. overflow: truncate ? 'truncate' : null,
  15837. lineHeight: lineHeight
  15838. }
  15839. });
  15840. return textEl.getBoundingRect();
  15841. }
  15842. /**
  15843. * Add a comma each three digit.
  15844. */
  15845. function addCommas(x) {
  15846. if (!isNumeric(x)) {
  15847. return isString(x) ? x : '-';
  15848. }
  15849. var parts = (x + '').split('.');
  15850. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15851. }
  15852. function toCamelCase(str, upperCaseFirst) {
  15853. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15854. return group1.toUpperCase();
  15855. });
  15856. if (upperCaseFirst && str) {
  15857. str = str.charAt(0).toUpperCase() + str.slice(1);
  15858. }
  15859. return str;
  15860. }
  15861. var normalizeCssArray$1 = normalizeCssArray;
  15862. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15863. var wrapVar = function (varName, seriesIdx) {
  15864. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15865. };
  15866. /**
  15867. * Template formatter
  15868. * @param {Array.<Object>|Object} paramsList
  15869. */
  15870. function formatTpl(tpl, paramsList, encode) {
  15871. if (!isArray(paramsList)) {
  15872. paramsList = [paramsList];
  15873. }
  15874. var seriesLen = paramsList.length;
  15875. if (!seriesLen) {
  15876. return '';
  15877. }
  15878. var $vars = paramsList[0].$vars || [];
  15879. for (var i = 0; i < $vars.length; i++) {
  15880. var alias = TPL_VAR_ALIAS[i];
  15881. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15882. }
  15883. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15884. for (var k = 0; k < $vars.length; k++) {
  15885. var val = paramsList[seriesIdx][$vars[k]];
  15886. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  15887. }
  15888. }
  15889. return tpl;
  15890. }
  15891. function getTooltipMarker(inOpt, extraCssText) {
  15892. var opt = isString(inOpt) ? {
  15893. color: inOpt,
  15894. extraCssText: extraCssText
  15895. } : inOpt || {};
  15896. var color = opt.color;
  15897. var type = opt.type;
  15898. extraCssText = opt.extraCssText;
  15899. var renderMode = opt.renderMode || 'html';
  15900. if (!color) {
  15901. return '';
  15902. }
  15903. if (renderMode === 'html') {
  15904. 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:'
  15905. // Only support string
  15906. + 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>';
  15907. } else {
  15908. // Should better not to auto generate style name by auto-increment number here.
  15909. // Because this util is usually called in tooltip formatter, which is probably
  15910. // called repeatedly when mouse move and the auto-increment number increases fast.
  15911. // Users can make their own style name by theirselves, make it unique and readable.
  15912. var markerId = opt.markerId || 'markerX';
  15913. return {
  15914. renderMode: renderMode,
  15915. content: '{' + markerId + '|} ',
  15916. style: type === 'subItem' ? {
  15917. width: 4,
  15918. height: 4,
  15919. borderRadius: 2,
  15920. backgroundColor: color
  15921. } : {
  15922. width: 10,
  15923. height: 10,
  15924. borderRadius: 5,
  15925. backgroundColor: color
  15926. }
  15927. };
  15928. }
  15929. }
  15930. /**
  15931. * @deprecated Use `time/format` instead.
  15932. * ISO Date format
  15933. * @param {string} tpl
  15934. * @param {number} value
  15935. * @param {boolean} [isUTC=false] Default in local time.
  15936. * see `module:echarts/scale/Time`
  15937. * and `module:echarts/util/number#parseDate`.
  15938. * @inner
  15939. */
  15940. function formatTime(tpl, value, isUTC) {
  15941. if ("development" !== 'production') {
  15942. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  15943. }
  15944. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  15945. tpl = 'MM-dd\nyyyy';
  15946. }
  15947. var date = parseDate(value);
  15948. var getUTC = isUTC ? 'getUTC' : 'get';
  15949. var y = date[getUTC + 'FullYear']();
  15950. var M = date[getUTC + 'Month']() + 1;
  15951. var d = date[getUTC + 'Date']();
  15952. var h = date[getUTC + 'Hours']();
  15953. var m = date[getUTC + 'Minutes']();
  15954. var s = date[getUTC + 'Seconds']();
  15955. var S = date[getUTC + 'Milliseconds']();
  15956. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', pad(y % 100 + '', 2)).replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  15957. return tpl;
  15958. }
  15959. /**
  15960. * Capital first
  15961. * @param {string} str
  15962. * @return {string}
  15963. */
  15964. function capitalFirst(str) {
  15965. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15966. }
  15967. /**
  15968. * @return Never be null/undefined.
  15969. */
  15970. function convertToColorString(color, defaultColor) {
  15971. defaultColor = defaultColor || 'transparent';
  15972. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  15973. }
  15974. var each$1 = each;
  15975. /**
  15976. * @public
  15977. */
  15978. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  15979. /**
  15980. * @public
  15981. */
  15982. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  15983. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15984. var x = 0;
  15985. var y = 0;
  15986. if (maxWidth == null) {
  15987. maxWidth = Infinity;
  15988. }
  15989. if (maxHeight == null) {
  15990. maxHeight = Infinity;
  15991. }
  15992. var currentLineMaxSize = 0;
  15993. group.eachChild(function (child, idx) {
  15994. var rect = child.getBoundingRect();
  15995. var nextChild = group.childAt(idx + 1);
  15996. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15997. var nextX;
  15998. var nextY;
  15999. if (orient === 'horizontal') {
  16000. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16001. nextX = x + moveX;
  16002. // Wrap when width exceeds maxWidth or meet a `newline` group
  16003. // FIXME compare before adding gap?
  16004. if (nextX > maxWidth || child.newline) {
  16005. x = 0;
  16006. nextX = moveX;
  16007. y += currentLineMaxSize + gap;
  16008. currentLineMaxSize = rect.height;
  16009. } else {
  16010. // FIXME: consider rect.y is not `0`?
  16011. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16012. }
  16013. } else {
  16014. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16015. nextY = y + moveY;
  16016. // Wrap when width exceeds maxHeight or meet a `newline` group
  16017. if (nextY > maxHeight || child.newline) {
  16018. x += currentLineMaxSize + gap;
  16019. y = 0;
  16020. nextY = moveY;
  16021. currentLineMaxSize = rect.width;
  16022. } else {
  16023. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16024. }
  16025. }
  16026. if (child.newline) {
  16027. return;
  16028. }
  16029. child.x = x;
  16030. child.y = y;
  16031. child.markRedraw();
  16032. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16033. });
  16034. }
  16035. /**
  16036. * VBox layouting
  16037. * @param {module:zrender/graphic/Group} group
  16038. * @param {number} gap
  16039. * @param {number} [width=Infinity]
  16040. * @param {number} [height=Infinity]
  16041. */
  16042. var vbox = curry(boxLayout, 'vertical');
  16043. /**
  16044. * HBox layouting
  16045. * @param {module:zrender/graphic/Group} group
  16046. * @param {number} gap
  16047. * @param {number} [width=Infinity]
  16048. * @param {number} [height=Infinity]
  16049. */
  16050. var hbox = curry(boxLayout, 'horizontal');
  16051. /**
  16052. * Parse position info.
  16053. */
  16054. function getLayoutRect(positionInfo, containerRect, margin) {
  16055. margin = normalizeCssArray$1(margin || 0);
  16056. var containerWidth = containerRect.width;
  16057. var containerHeight = containerRect.height;
  16058. var left = parsePercent$1(positionInfo.left, containerWidth);
  16059. var top = parsePercent$1(positionInfo.top, containerHeight);
  16060. var right = parsePercent$1(positionInfo.right, containerWidth);
  16061. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16062. var width = parsePercent$1(positionInfo.width, containerWidth);
  16063. var height = parsePercent$1(positionInfo.height, containerHeight);
  16064. var verticalMargin = margin[2] + margin[0];
  16065. var horizontalMargin = margin[1] + margin[3];
  16066. var aspect = positionInfo.aspect;
  16067. // If width is not specified, calculate width from left and right
  16068. if (isNaN(width)) {
  16069. width = containerWidth - right - horizontalMargin - left;
  16070. }
  16071. if (isNaN(height)) {
  16072. height = containerHeight - bottom - verticalMargin - top;
  16073. }
  16074. if (aspect != null) {
  16075. // If width and height are not given
  16076. // 1. Graph should not exceeds the container
  16077. // 2. Aspect must be keeped
  16078. // 3. Graph should take the space as more as possible
  16079. // FIXME
  16080. // Margin is not considered, because there is no case that both
  16081. // using margin and aspect so far.
  16082. if (isNaN(width) && isNaN(height)) {
  16083. if (aspect > containerWidth / containerHeight) {
  16084. width = containerWidth * 0.8;
  16085. } else {
  16086. height = containerHeight * 0.8;
  16087. }
  16088. }
  16089. // Calculate width or height with given aspect
  16090. if (isNaN(width)) {
  16091. width = aspect * height;
  16092. }
  16093. if (isNaN(height)) {
  16094. height = width / aspect;
  16095. }
  16096. }
  16097. // If left is not specified, calculate left from right and width
  16098. if (isNaN(left)) {
  16099. left = containerWidth - right - width - horizontalMargin;
  16100. }
  16101. if (isNaN(top)) {
  16102. top = containerHeight - bottom - height - verticalMargin;
  16103. }
  16104. // Align left and top
  16105. switch (positionInfo.left || positionInfo.right) {
  16106. case 'center':
  16107. left = containerWidth / 2 - width / 2 - margin[3];
  16108. break;
  16109. case 'right':
  16110. left = containerWidth - width - horizontalMargin;
  16111. break;
  16112. }
  16113. switch (positionInfo.top || positionInfo.bottom) {
  16114. case 'middle':
  16115. case 'center':
  16116. top = containerHeight / 2 - height / 2 - margin[0];
  16117. break;
  16118. case 'bottom':
  16119. top = containerHeight - height - verticalMargin;
  16120. break;
  16121. }
  16122. // If something is wrong and left, top, width, height are calculated as NaN
  16123. left = left || 0;
  16124. top = top || 0;
  16125. if (isNaN(width)) {
  16126. // Width may be NaN if only one value is given except width
  16127. width = containerWidth - horizontalMargin - left - (right || 0);
  16128. }
  16129. if (isNaN(height)) {
  16130. // Height may be NaN if only one value is given except height
  16131. height = containerHeight - verticalMargin - top - (bottom || 0);
  16132. }
  16133. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16134. rect.margin = margin;
  16135. return rect;
  16136. }
  16137. function fetchLayoutMode(ins) {
  16138. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16139. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16140. type: layoutMode
  16141. } : null;
  16142. }
  16143. /**
  16144. * Consider Case:
  16145. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16146. * through setOption or media query, using normal zrUtil.merge will cause
  16147. * {right: 0} does not take effect.
  16148. *
  16149. * @example
  16150. * ComponentModel.extend({
  16151. * init: function () {
  16152. * ...
  16153. * let inputPositionParams = layout.getLayoutParams(option);
  16154. * this.mergeOption(inputPositionParams);
  16155. * },
  16156. * mergeOption: function (newOption) {
  16157. * newOption && zrUtil.merge(thisOption, newOption, true);
  16158. * layout.mergeLayoutParam(thisOption, newOption);
  16159. * }
  16160. * });
  16161. *
  16162. * @param targetOption
  16163. * @param newOption
  16164. * @param opt
  16165. */
  16166. function mergeLayoutParam(targetOption, newOption, opt) {
  16167. var ignoreSize = opt && opt.ignoreSize;
  16168. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16169. var hResult = merge(HV_NAMES[0], 0);
  16170. var vResult = merge(HV_NAMES[1], 1);
  16171. copy(HV_NAMES[0], targetOption, hResult);
  16172. copy(HV_NAMES[1], targetOption, vResult);
  16173. function merge(names, hvIdx) {
  16174. var newParams = {};
  16175. var newValueCount = 0;
  16176. var merged = {};
  16177. var mergedValueCount = 0;
  16178. var enoughParamNumber = 2;
  16179. each$1(names, function (name) {
  16180. merged[name] = targetOption[name];
  16181. });
  16182. each$1(names, function (name) {
  16183. // Consider case: newOption.width is null, which is
  16184. // set by user for removing width setting.
  16185. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16186. hasValue(newParams, name) && newValueCount++;
  16187. hasValue(merged, name) && mergedValueCount++;
  16188. });
  16189. if (ignoreSize[hvIdx]) {
  16190. // Only one of left/right is premitted to exist.
  16191. if (hasValue(newOption, names[1])) {
  16192. merged[names[2]] = null;
  16193. } else if (hasValue(newOption, names[2])) {
  16194. merged[names[1]] = null;
  16195. }
  16196. return merged;
  16197. }
  16198. // Case: newOption: {width: ..., right: ...},
  16199. // or targetOption: {right: ...} and newOption: {width: ...},
  16200. // There is no conflict when merged only has params count
  16201. // little than enoughParamNumber.
  16202. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16203. return merged;
  16204. }
  16205. // Case: newOption: {width: ..., right: ...},
  16206. // Than we can make sure user only want those two, and ignore
  16207. // all origin params in targetOption.
  16208. else if (newValueCount >= enoughParamNumber) {
  16209. return newParams;
  16210. } else {
  16211. // Chose another param from targetOption by priority.
  16212. for (var i = 0; i < names.length; i++) {
  16213. var name_1 = names[i];
  16214. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16215. newParams[name_1] = targetOption[name_1];
  16216. break;
  16217. }
  16218. }
  16219. return newParams;
  16220. }
  16221. }
  16222. function hasProp(obj, name) {
  16223. return obj.hasOwnProperty(name);
  16224. }
  16225. function hasValue(obj, name) {
  16226. return obj[name] != null && obj[name] !== 'auto';
  16227. }
  16228. function copy(names, target, source) {
  16229. each$1(names, function (name) {
  16230. target[name] = source[name];
  16231. });
  16232. }
  16233. }
  16234. /**
  16235. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16236. */
  16237. function getLayoutParams(source) {
  16238. return copyLayoutParams({}, source);
  16239. }
  16240. /**
  16241. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16242. * @param {Object} source
  16243. * @return {Object} Result contains those props.
  16244. */
  16245. function copyLayoutParams(target, source) {
  16246. source && target && each$1(LOCATION_PARAMS, function (name) {
  16247. source.hasOwnProperty(name) && (target[name] = source[name]);
  16248. });
  16249. return target;
  16250. }
  16251. var inner = makeInner();
  16252. var ComponentModel = /** @class */function (_super) {
  16253. __extends(ComponentModel, _super);
  16254. function ComponentModel(option, parentModel, ecModel) {
  16255. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16256. _this.uid = getUID('ec_cpt_model');
  16257. return _this;
  16258. }
  16259. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16260. this.mergeDefaultAndTheme(option, ecModel);
  16261. };
  16262. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16263. var layoutMode = fetchLayoutMode(this);
  16264. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16265. var themeModel = ecModel.getTheme();
  16266. merge(option, themeModel.get(this.mainType));
  16267. merge(option, this.getDefaultOption());
  16268. if (layoutMode) {
  16269. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16270. }
  16271. };
  16272. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16273. merge(this.option, option, true);
  16274. var layoutMode = fetchLayoutMode(this);
  16275. if (layoutMode) {
  16276. mergeLayoutParam(this.option, option, layoutMode);
  16277. }
  16278. };
  16279. /**
  16280. * Called immediately after `init` or `mergeOption` of this instance called.
  16281. */
  16282. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16283. /**
  16284. * [How to declare defaultOption]:
  16285. *
  16286. * (A) If using class declaration in typescript (since echarts 5):
  16287. * ```ts
  16288. * import {ComponentOption} from '../model/option.js';
  16289. * export interface XxxOption extends ComponentOption {
  16290. * aaa: number
  16291. * }
  16292. * export class XxxModel extends Component {
  16293. * static type = 'xxx';
  16294. * static defaultOption: XxxOption = {
  16295. * aaa: 123
  16296. * }
  16297. * }
  16298. * Component.registerClass(XxxModel);
  16299. * ```
  16300. * ```ts
  16301. * import {inheritDefaultOption} from '../util/component.js';
  16302. * import {XxxModel, XxxOption} from './XxxModel.js';
  16303. * export interface XxxSubOption extends XxxOption {
  16304. * bbb: number
  16305. * }
  16306. * class XxxSubModel extends XxxModel {
  16307. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16308. * bbb: 456
  16309. * })
  16310. * fn() {
  16311. * let opt = this.getDefaultOption();
  16312. * // opt is {aaa: 123, bbb: 456}
  16313. * }
  16314. * }
  16315. * ```
  16316. *
  16317. * (B) If using class extend (previous approach in echarts 3 & 4):
  16318. * ```js
  16319. * let XxxComponent = Component.extend({
  16320. * defaultOption: {
  16321. * xx: 123
  16322. * }
  16323. * })
  16324. * ```
  16325. * ```js
  16326. * let XxxSubComponent = XxxComponent.extend({
  16327. * defaultOption: {
  16328. * yy: 456
  16329. * },
  16330. * fn: function () {
  16331. * let opt = this.getDefaultOption();
  16332. * // opt is {xx: 123, yy: 456}
  16333. * }
  16334. * })
  16335. * ```
  16336. */
  16337. ComponentModel.prototype.getDefaultOption = function () {
  16338. var ctor = this.constructor;
  16339. // If using class declaration, it is different to travel super class
  16340. // in legacy env and auto merge defaultOption. So if using class
  16341. // declaration, defaultOption should be merged manually.
  16342. if (!isExtendedClass(ctor)) {
  16343. // When using ts class, defaultOption must be declared as static.
  16344. return ctor.defaultOption;
  16345. }
  16346. // FIXME: remove this approach?
  16347. var fields = inner(this);
  16348. if (!fields.defaultOption) {
  16349. var optList = [];
  16350. var clz = ctor;
  16351. while (clz) {
  16352. var opt = clz.prototype.defaultOption;
  16353. opt && optList.push(opt);
  16354. clz = clz.superClass;
  16355. }
  16356. var defaultOption = {};
  16357. for (var i = optList.length - 1; i >= 0; i--) {
  16358. defaultOption = merge(defaultOption, optList[i], true);
  16359. }
  16360. fields.defaultOption = defaultOption;
  16361. }
  16362. return fields.defaultOption;
  16363. };
  16364. /**
  16365. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16366. * The same behavior as `modelUtil.parseFinder`.
  16367. *
  16368. * @param useDefault In many cases like series refer axis and axis refer grid,
  16369. * If axis index / axis id not specified, use the first target as default.
  16370. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16371. */
  16372. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16373. var indexKey = mainType + 'Index';
  16374. var idKey = mainType + 'Id';
  16375. return queryReferringComponents(this.ecModel, mainType, {
  16376. index: this.get(indexKey, true),
  16377. id: this.get(idKey, true)
  16378. }, opt);
  16379. };
  16380. ComponentModel.prototype.getBoxLayoutParams = function () {
  16381. // Consider itself having box layout configs.
  16382. var boxLayoutModel = this;
  16383. return {
  16384. left: boxLayoutModel.get('left'),
  16385. top: boxLayoutModel.get('top'),
  16386. right: boxLayoutModel.get('right'),
  16387. bottom: boxLayoutModel.get('bottom'),
  16388. width: boxLayoutModel.get('width'),
  16389. height: boxLayoutModel.get('height')
  16390. };
  16391. };
  16392. /**
  16393. * Get key for zlevel.
  16394. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16395. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16396. */
  16397. ComponentModel.prototype.getZLevelKey = function () {
  16398. return '';
  16399. };
  16400. ComponentModel.prototype.setZLevel = function (zlevel) {
  16401. this.option.zlevel = zlevel;
  16402. };
  16403. ComponentModel.protoInitialize = function () {
  16404. var proto = ComponentModel.prototype;
  16405. proto.type = 'component';
  16406. proto.id = '';
  16407. proto.name = '';
  16408. proto.mainType = '';
  16409. proto.subType = '';
  16410. proto.componentIndex = 0;
  16411. }();
  16412. return ComponentModel;
  16413. }(Model);
  16414. mountExtend(ComponentModel, Model);
  16415. enableClassManagement(ComponentModel);
  16416. enableSubTypeDefaulter(ComponentModel);
  16417. enableTopologicalTravel(ComponentModel, getDependencies);
  16418. function getDependencies(componentType) {
  16419. var deps = [];
  16420. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16421. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16422. });
  16423. // Ensure main type.
  16424. deps = map(deps, function (type) {
  16425. return parseClassType(type).main;
  16426. });
  16427. // Hack dataset for convenience.
  16428. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16429. deps.unshift('dataset');
  16430. }
  16431. return deps;
  16432. }
  16433. /*
  16434. * Licensed to the Apache Software Foundation (ASF) under one
  16435. * or more contributor license agreements. See the NOTICE file
  16436. * distributed with this work for additional information
  16437. * regarding copyright ownership. The ASF licenses this file
  16438. * to you under the Apache License, Version 2.0 (the
  16439. * "License"); you may not use this file except in compliance
  16440. * with the License. You may obtain a copy of the License at
  16441. *
  16442. * http://www.apache.org/licenses/LICENSE-2.0
  16443. *
  16444. * Unless required by applicable law or agreed to in writing,
  16445. * software distributed under the License is distributed on an
  16446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16447. * KIND, either express or implied. See the License for the
  16448. * specific language governing permissions and limitations
  16449. * under the License.
  16450. */
  16451. /**
  16452. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16453. */
  16454. /*
  16455. * Licensed to the Apache Software Foundation (ASF) under one
  16456. * or more contributor license agreements. See the NOTICE file
  16457. * distributed with this work for additional information
  16458. * regarding copyright ownership. The ASF licenses this file
  16459. * to you under the Apache License, Version 2.0 (the
  16460. * "License"); you may not use this file except in compliance
  16461. * with the License. You may obtain a copy of the License at
  16462. *
  16463. * http://www.apache.org/licenses/LICENSE-2.0
  16464. *
  16465. * Unless required by applicable law or agreed to in writing,
  16466. * software distributed under the License is distributed on an
  16467. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16468. * KIND, either express or implied. See the License for the
  16469. * specific language governing permissions and limitations
  16470. * under the License.
  16471. */
  16472. var platform = '';
  16473. // Navigator not exists in node
  16474. if (typeof navigator !== 'undefined') {
  16475. /* global navigator */
  16476. platform = navigator.platform || '';
  16477. }
  16478. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16479. var globalDefault = {
  16480. darkMode: 'auto',
  16481. // backgroundColor: 'rgba(0,0,0,0)',
  16482. colorBy: 'series',
  16483. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16484. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16485. aria: {
  16486. decal: {
  16487. decals: [{
  16488. color: decalColor,
  16489. dashArrayX: [1, 0],
  16490. dashArrayY: [2, 5],
  16491. symbolSize: 1,
  16492. rotation: Math.PI / 6
  16493. }, {
  16494. color: decalColor,
  16495. symbol: 'circle',
  16496. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16497. dashArrayY: [6, 0],
  16498. symbolSize: 0.8
  16499. }, {
  16500. color: decalColor,
  16501. dashArrayX: [1, 0],
  16502. dashArrayY: [4, 3],
  16503. rotation: -Math.PI / 4
  16504. }, {
  16505. color: decalColor,
  16506. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16507. dashArrayY: [6, 0]
  16508. }, {
  16509. color: decalColor,
  16510. dashArrayX: [[1, 0], [1, 6]],
  16511. dashArrayY: [1, 0, 6, 0],
  16512. rotation: Math.PI / 4
  16513. }, {
  16514. color: decalColor,
  16515. symbol: 'triangle',
  16516. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16517. dashArrayY: [7, 2],
  16518. symbolSize: 0.75
  16519. }]
  16520. }
  16521. },
  16522. // If xAxis and yAxis declared, grid is created by default.
  16523. // grid: {},
  16524. textStyle: {
  16525. // color: '#000',
  16526. // decoration: 'none',
  16527. // PENDING
  16528. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16529. // fontFamily: 'Arial, Verdana, sans-serif',
  16530. fontSize: 12,
  16531. fontStyle: 'normal',
  16532. fontWeight: 'normal'
  16533. },
  16534. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16535. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16536. // Default is source-over
  16537. blendMode: null,
  16538. stateAnimation: {
  16539. duration: 300,
  16540. easing: 'cubicOut'
  16541. },
  16542. animation: 'auto',
  16543. animationDuration: 1000,
  16544. animationDurationUpdate: 500,
  16545. animationEasing: 'cubicInOut',
  16546. animationEasingUpdate: 'cubicInOut',
  16547. animationThreshold: 2000,
  16548. // Configuration for progressive/incremental rendering
  16549. progressiveThreshold: 3000,
  16550. progressive: 400,
  16551. // Threshold of if use single hover layer to optimize.
  16552. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16553. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16554. // which is unexpected.
  16555. // see example <echarts/test/heatmap-large.html>.
  16556. hoverLayerThreshold: 3000,
  16557. // See: module:echarts/scale/Time
  16558. useUTC: false
  16559. };
  16560. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'itemChildGroupId', 'seriesName']);
  16561. var SOURCE_FORMAT_ORIGINAL = 'original';
  16562. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16563. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16564. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16565. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16566. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16567. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16568. var SERIES_LAYOUT_BY_ROW = 'row';
  16569. // The result of `guessOrdinal`.
  16570. var BE_ORDINAL = {
  16571. Must: 1,
  16572. Might: 2,
  16573. Not: 3 // Other cases
  16574. };
  16575. var innerGlobalModel = makeInner();
  16576. /**
  16577. * MUST be called before mergeOption of all series.
  16578. */
  16579. function resetSourceDefaulter(ecModel) {
  16580. // `datasetMap` is used to make default encode.
  16581. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16582. }
  16583. /**
  16584. * [The strategy of the arrengment of data dimensions for dataset]:
  16585. * "value way": all axes are non-category axes. So series one by one take
  16586. * several (the number is coordSysDims.length) dimensions from dataset.
  16587. * The result of data arrengment of data dimensions like:
  16588. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16589. * "category way": at least one axis is category axis. So the the first data
  16590. * dimension is always mapped to the first category axis and shared by
  16591. * all of the series. The other data dimensions are taken by series like
  16592. * "value way" does.
  16593. * The result of data arrengment of data dimensions like:
  16594. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16595. *
  16596. * @return encode Never be `null/undefined`.
  16597. */
  16598. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16599. var encode = {};
  16600. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  16601. // Currently only make default when using dataset, util more reqirements occur.
  16602. if (!datasetModel || !coordDimensions) {
  16603. return encode;
  16604. }
  16605. var encodeItemName = [];
  16606. var encodeSeriesName = [];
  16607. var ecModel = seriesModel.ecModel;
  16608. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16609. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16610. var baseCategoryDimIndex;
  16611. var categoryWayValueDimStart;
  16612. coordDimensions = coordDimensions.slice();
  16613. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16614. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16615. name: coordDimInfoLoose
  16616. };
  16617. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16618. baseCategoryDimIndex = coordDimIdx;
  16619. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16620. }
  16621. encode[coordDimInfo.name] = [];
  16622. });
  16623. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16624. categoryWayDim: categoryWayValueDimStart,
  16625. valueWayDim: 0
  16626. });
  16627. // TODO
  16628. // Auto detect first time axis and do arrangement.
  16629. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16630. var coordDimName = coordDimInfo.name;
  16631. var count = getDataDimCountOnCoordDim(coordDimInfo);
  16632. // In value way.
  16633. if (baseCategoryDimIndex == null) {
  16634. var start = datasetRecord.valueWayDim;
  16635. pushDim(encode[coordDimName], start, count);
  16636. pushDim(encodeSeriesName, start, count);
  16637. datasetRecord.valueWayDim += count;
  16638. // ??? TODO give a better default series name rule?
  16639. // especially when encode x y specified.
  16640. // consider: when multiple series share one dimension
  16641. // category axis, series name should better use
  16642. // the other dimension name. On the other hand, use
  16643. // both dimensions name.
  16644. }
  16645. // In category way, the first category axis.
  16646. else if (baseCategoryDimIndex === coordDimIdx) {
  16647. pushDim(encode[coordDimName], 0, count);
  16648. pushDim(encodeItemName, 0, count);
  16649. }
  16650. // In category way, the other axis.
  16651. else {
  16652. var start = datasetRecord.categoryWayDim;
  16653. pushDim(encode[coordDimName], start, count);
  16654. pushDim(encodeSeriesName, start, count);
  16655. datasetRecord.categoryWayDim += count;
  16656. }
  16657. });
  16658. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16659. for (var i = 0; i < idxCount; i++) {
  16660. dimIdxArr.push(idxFrom + i);
  16661. }
  16662. }
  16663. function getDataDimCountOnCoordDim(coordDimInfo) {
  16664. var dimsDef = coordDimInfo.dimsDef;
  16665. return dimsDef ? dimsDef.length : 1;
  16666. }
  16667. encodeItemName.length && (encode.itemName = encodeItemName);
  16668. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16669. return encode;
  16670. }
  16671. /**
  16672. * Work for data like [{name: ..., value: ...}, ...].
  16673. *
  16674. * @return encode Never be `null/undefined`.
  16675. */
  16676. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16677. var encode = {};
  16678. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  16679. // Currently only make default when using dataset, util more reqirements occur.
  16680. if (!datasetModel) {
  16681. return encode;
  16682. }
  16683. var sourceFormat = source.sourceFormat;
  16684. var dimensionsDefine = source.dimensionsDefine;
  16685. var potentialNameDimIndex;
  16686. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16687. each(dimensionsDefine, function (dim, idx) {
  16688. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16689. potentialNameDimIndex = idx;
  16690. }
  16691. });
  16692. }
  16693. var idxResult = function () {
  16694. var idxRes0 = {};
  16695. var idxRes1 = {};
  16696. var guessRecords = [];
  16697. // 5 is an experience value.
  16698. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16699. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16700. guessRecords.push(guessResult);
  16701. var isPureNumber = guessResult === BE_ORDINAL.Not;
  16702. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16703. // and then find a name dim with the priority:
  16704. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16705. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16706. idxRes0.v = i;
  16707. }
  16708. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16709. idxRes0.n = i;
  16710. }
  16711. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16712. return idxRes0;
  16713. }
  16714. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16715. // find the first BE_ORDINAL.Might as the value dim,
  16716. // and then find a name dim with the priority:
  16717. // "other dim" > "the value dim itself".
  16718. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16719. // treated as number.
  16720. if (!isPureNumber) {
  16721. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16722. idxRes1.v = i;
  16723. }
  16724. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16725. idxRes1.n = i;
  16726. }
  16727. }
  16728. }
  16729. function fulfilled(idxResult) {
  16730. return idxResult.v != null && idxResult.n != null;
  16731. }
  16732. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16733. }();
  16734. if (idxResult) {
  16735. encode.value = [idxResult.v];
  16736. // `potentialNameDimIndex` has highest priority.
  16737. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  16738. // By default, label uses itemName in charts.
  16739. // So we don't set encodeLabel here.
  16740. encode.itemName = [nameDimIndex];
  16741. encode.seriesName = [nameDimIndex];
  16742. }
  16743. return encode;
  16744. }
  16745. /**
  16746. * @return If return null/undefined, indicate that should not use datasetModel.
  16747. */
  16748. function querySeriesUpstreamDatasetModel(seriesModel) {
  16749. // Caution: consider the scenario:
  16750. // A dataset is declared and a series is not expected to use the dataset,
  16751. // and at the beginning `setOption({series: { noData })` (just prepare other
  16752. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16753. // the user should set an empty array to avoid that dataset is used by default.
  16754. var thisData = seriesModel.get('data', true);
  16755. if (!thisData) {
  16756. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16757. index: seriesModel.get('datasetIndex', true),
  16758. id: seriesModel.get('datasetId', true)
  16759. }, SINGLE_REFERRING).models[0];
  16760. }
  16761. }
  16762. /**
  16763. * @return Always return an array event empty.
  16764. */
  16765. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16766. // Only these attributes declared, we by default reference to `datasetIndex: 0`.
  16767. // Otherwise, no reference.
  16768. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16769. return [];
  16770. }
  16771. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16772. index: datasetModel.get('fromDatasetIndex', true),
  16773. id: datasetModel.get('fromDatasetId', true)
  16774. }, SINGLE_REFERRING).models;
  16775. }
  16776. /**
  16777. * The rule should not be complex, otherwise user might not
  16778. * be able to known where the data is wrong.
  16779. * The code is ugly, but how to make it neat?
  16780. */
  16781. function guessOrdinal(source, dimIndex) {
  16782. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  16783. }
  16784. // dimIndex may be overflow source data.
  16785. // return {BE_ORDINAL}
  16786. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  16787. var result;
  16788. // Experience value.
  16789. var maxLoop = 5;
  16790. if (isTypedArray(data)) {
  16791. return BE_ORDINAL.Not;
  16792. }
  16793. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16794. // always exists in source.
  16795. var dimName;
  16796. var dimType;
  16797. if (dimensionsDefine) {
  16798. var dimDefItem = dimensionsDefine[dimIndex];
  16799. if (isObject(dimDefItem)) {
  16800. dimName = dimDefItem.name;
  16801. dimType = dimDefItem.type;
  16802. } else if (isString(dimDefItem)) {
  16803. dimName = dimDefItem;
  16804. }
  16805. }
  16806. if (dimType != null) {
  16807. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  16808. }
  16809. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16810. var dataArrayRows = data;
  16811. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16812. var sample = dataArrayRows[dimIndex];
  16813. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16814. if ((result = detectValue(sample[startIndex + i])) != null) {
  16815. return result;
  16816. }
  16817. }
  16818. } else {
  16819. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  16820. var row = dataArrayRows[startIndex + i];
  16821. if (row && (result = detectValue(row[dimIndex])) != null) {
  16822. return result;
  16823. }
  16824. }
  16825. }
  16826. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16827. var dataObjectRows = data;
  16828. if (!dimName) {
  16829. return BE_ORDINAL.Not;
  16830. }
  16831. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  16832. var item = dataObjectRows[i];
  16833. if (item && (result = detectValue(item[dimName])) != null) {
  16834. return result;
  16835. }
  16836. }
  16837. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16838. var dataKeyedColumns = data;
  16839. if (!dimName) {
  16840. return BE_ORDINAL.Not;
  16841. }
  16842. var sample = dataKeyedColumns[dimName];
  16843. if (!sample || isTypedArray(sample)) {
  16844. return BE_ORDINAL.Not;
  16845. }
  16846. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16847. if ((result = detectValue(sample[i])) != null) {
  16848. return result;
  16849. }
  16850. }
  16851. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16852. var dataOriginal = data;
  16853. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  16854. var item = dataOriginal[i];
  16855. var val = getDataItemValue(item);
  16856. if (!isArray(val)) {
  16857. return BE_ORDINAL.Not;
  16858. }
  16859. if ((result = detectValue(val[dimIndex])) != null) {
  16860. return result;
  16861. }
  16862. }
  16863. }
  16864. function detectValue(val) {
  16865. var beStr = isString(val);
  16866. // Consider usage convenience, '1', '2' will be treated as "number".
  16867. // `Number('')` (or any whitespace) is `0`.
  16868. if (val != null && Number.isFinite(Number(val)) && val !== '') {
  16869. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  16870. } else if (beStr && val !== '-') {
  16871. return BE_ORDINAL.Must;
  16872. }
  16873. }
  16874. return BE_ORDINAL.Not;
  16875. }
  16876. var internalOptionCreatorMap = createHashMap();
  16877. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  16878. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  16879. if (!internalOptionCreator) {
  16880. return newCmptOptionList;
  16881. }
  16882. var internalOptions = internalOptionCreator(ecModel);
  16883. if (!internalOptions) {
  16884. return newCmptOptionList;
  16885. }
  16886. if ("development" !== 'production') {
  16887. for (var i = 0; i < internalOptions.length; i++) {
  16888. assert(isComponentIdInternal(internalOptions[i]));
  16889. }
  16890. }
  16891. return newCmptOptionList.concat(internalOptions);
  16892. }
  16893. var innerColor = makeInner();
  16894. var innerDecal = makeInner();
  16895. var PaletteMixin = /** @class */function () {
  16896. function PaletteMixin() {}
  16897. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  16898. var defaultPalette = normalizeToArray(this.get('color', true));
  16899. var layeredPalette = this.get('colorLayer', true);
  16900. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  16901. };
  16902. PaletteMixin.prototype.clearColorPalette = function () {
  16903. clearPalette(this, innerColor);
  16904. };
  16905. return PaletteMixin;
  16906. }();
  16907. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  16908. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  16909. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  16910. }
  16911. function getNearestPalette(palettes, requestColorNum) {
  16912. var paletteNum = palettes.length;
  16913. // TODO palettes must be in order
  16914. for (var i = 0; i < paletteNum; i++) {
  16915. if (palettes[i].length > requestColorNum) {
  16916. return palettes[i];
  16917. }
  16918. }
  16919. return palettes[paletteNum - 1];
  16920. }
  16921. /**
  16922. * @param name MUST NOT be null/undefined. Otherwise call this function
  16923. * twise with the same parameters will get different result.
  16924. * @param scope default this.
  16925. * @return Can be null/undefined
  16926. */
  16927. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  16928. scope = scope || that;
  16929. var scopeFields = inner(scope);
  16930. var paletteIdx = scopeFields.paletteIdx || 0;
  16931. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {};
  16932. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16933. if (paletteNameMap.hasOwnProperty(name)) {
  16934. return paletteNameMap[name];
  16935. }
  16936. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum);
  16937. // In case can't find in layered color palette.
  16938. palette = palette || defaultPalette;
  16939. if (!palette || !palette.length) {
  16940. return;
  16941. }
  16942. var pickedPaletteItem = palette[paletteIdx];
  16943. if (name) {
  16944. paletteNameMap[name] = pickedPaletteItem;
  16945. }
  16946. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  16947. return pickedPaletteItem;
  16948. }
  16949. function clearPalette(that, inner) {
  16950. inner(that).paletteIdx = 0;
  16951. inner(that).paletteNameMap = {};
  16952. }
  16953. // -----------------------
  16954. // Internal method names:
  16955. // -----------------------
  16956. var reCreateSeriesIndices;
  16957. var assertSeriesInitialized;
  16958. var initBase;
  16959. var OPTION_INNER_KEY = '\0_ec_inner';
  16960. var OPTION_INNER_VALUE = 1;
  16961. var BUITIN_COMPONENTS_MAP = {
  16962. grid: 'GridComponent',
  16963. polar: 'PolarComponent',
  16964. geo: 'GeoComponent',
  16965. singleAxis: 'SingleAxisComponent',
  16966. parallel: 'ParallelComponent',
  16967. calendar: 'CalendarComponent',
  16968. graphic: 'GraphicComponent',
  16969. toolbox: 'ToolboxComponent',
  16970. tooltip: 'TooltipComponent',
  16971. axisPointer: 'AxisPointerComponent',
  16972. brush: 'BrushComponent',
  16973. title: 'TitleComponent',
  16974. timeline: 'TimelineComponent',
  16975. markPoint: 'MarkPointComponent',
  16976. markLine: 'MarkLineComponent',
  16977. markArea: 'MarkAreaComponent',
  16978. legend: 'LegendComponent',
  16979. dataZoom: 'DataZoomComponent',
  16980. visualMap: 'VisualMapComponent',
  16981. // aria: 'AriaComponent',
  16982. // dataset: 'DatasetComponent',
  16983. // Dependencies
  16984. xAxis: 'GridComponent',
  16985. yAxis: 'GridComponent',
  16986. angleAxis: 'PolarComponent',
  16987. radiusAxis: 'PolarComponent'
  16988. };
  16989. var BUILTIN_CHARTS_MAP = {
  16990. line: 'LineChart',
  16991. bar: 'BarChart',
  16992. pie: 'PieChart',
  16993. scatter: 'ScatterChart',
  16994. radar: 'RadarChart',
  16995. map: 'MapChart',
  16996. tree: 'TreeChart',
  16997. treemap: 'TreemapChart',
  16998. graph: 'GraphChart',
  16999. gauge: 'GaugeChart',
  17000. funnel: 'FunnelChart',
  17001. parallel: 'ParallelChart',
  17002. sankey: 'SankeyChart',
  17003. boxplot: 'BoxplotChart',
  17004. candlestick: 'CandlestickChart',
  17005. effectScatter: 'EffectScatterChart',
  17006. lines: 'LinesChart',
  17007. heatmap: 'HeatmapChart',
  17008. pictorialBar: 'PictorialBarChart',
  17009. themeRiver: 'ThemeRiverChart',
  17010. sunburst: 'SunburstChart',
  17011. custom: 'CustomChart'
  17012. };
  17013. var componetsMissingLogPrinted = {};
  17014. function checkMissingComponents(option) {
  17015. each(option, function (componentOption, mainType) {
  17016. if (!ComponentModel.hasClass(mainType)) {
  17017. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17018. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17019. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17020. componetsMissingLogPrinted[componentImportName] = true;
  17021. }
  17022. }
  17023. });
  17024. }
  17025. var GlobalModel = /** @class */function (_super) {
  17026. __extends(GlobalModel, _super);
  17027. function GlobalModel() {
  17028. return _super !== null && _super.apply(this, arguments) || this;
  17029. }
  17030. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17031. theme = theme || {};
  17032. this.option = null; // Mark as not initialized.
  17033. this._theme = new Model(theme);
  17034. this._locale = new Model(locale);
  17035. this._optionManager = optionManager;
  17036. };
  17037. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17038. if ("development" !== 'production') {
  17039. assert(option != null, 'option is null/undefined');
  17040. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17041. }
  17042. var innerOpt = normalizeSetOptionInput(opts);
  17043. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17044. this._resetOption(null, innerOpt);
  17045. };
  17046. /**
  17047. * @param type null/undefined: reset all.
  17048. * 'recreate': force recreate all.
  17049. * 'timeline': only reset timeline option
  17050. * 'media': only reset media query option
  17051. * @return Whether option changed.
  17052. */
  17053. GlobalModel.prototype.resetOption = function (type, opt) {
  17054. return this._resetOption(type, normalizeSetOptionInput(opt));
  17055. };
  17056. GlobalModel.prototype._resetOption = function (type, opt) {
  17057. var optionChanged = false;
  17058. var optionManager = this._optionManager;
  17059. if (!type || type === 'recreate') {
  17060. var baseOption = optionManager.mountOption(type === 'recreate');
  17061. if ("development" !== 'production') {
  17062. checkMissingComponents(baseOption);
  17063. }
  17064. if (!this.option || type === 'recreate') {
  17065. initBase(this, baseOption);
  17066. } else {
  17067. this.restoreData();
  17068. this._mergeOption(baseOption, opt);
  17069. }
  17070. optionChanged = true;
  17071. }
  17072. if (type === 'timeline' || type === 'media') {
  17073. this.restoreData();
  17074. }
  17075. // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17076. // it should better not have the same props with `MediaUnit['option']`.
  17077. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17078. // rather than original "baseOption". If they both override a prop, the result might be
  17079. // unexpected when media state changed after `setOption` called.
  17080. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17081. // (`{baseOption, media}`) in `setOption`.
  17082. // For `timeline`, the case is the same.
  17083. if (!type || type === 'recreate' || type === 'timeline') {
  17084. var timelineOption = optionManager.getTimelineOption(this);
  17085. if (timelineOption) {
  17086. optionChanged = true;
  17087. this._mergeOption(timelineOption, opt);
  17088. }
  17089. }
  17090. if (!type || type === 'recreate' || type === 'media') {
  17091. var mediaOptions = optionManager.getMediaOption(this);
  17092. if (mediaOptions.length) {
  17093. each(mediaOptions, function (mediaOption) {
  17094. optionChanged = true;
  17095. this._mergeOption(mediaOption, opt);
  17096. }, this);
  17097. }
  17098. }
  17099. return optionChanged;
  17100. };
  17101. GlobalModel.prototype.mergeOption = function (option) {
  17102. this._mergeOption(option, null);
  17103. };
  17104. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17105. var option = this.option;
  17106. var componentsMap = this._componentsMap;
  17107. var componentsCount = this._componentsCount;
  17108. var newCmptTypes = [];
  17109. var newCmptTypeMap = createHashMap();
  17110. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17111. resetSourceDefaulter(this);
  17112. // If no component class, merge directly.
  17113. // For example: color, animaiton options, etc.
  17114. each(newOption, function (componentOption, mainType) {
  17115. if (componentOption == null) {
  17116. return;
  17117. }
  17118. if (!ComponentModel.hasClass(mainType)) {
  17119. // globalSettingTask.dirty();
  17120. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17121. } else if (mainType) {
  17122. newCmptTypes.push(mainType);
  17123. newCmptTypeMap.set(mainType, true);
  17124. }
  17125. });
  17126. if (replaceMergeMainTypeMap) {
  17127. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17128. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17129. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17130. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17131. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17132. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17133. newCmptTypes.push(mainTypeInReplaceMerge);
  17134. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17135. }
  17136. });
  17137. }
  17138. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17139. function visitComponent(mainType) {
  17140. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17141. var oldCmptList = componentsMap.get(mainType);
  17142. var mergeMode =
  17143. // `!oldCmptList` means init. See the comment in `mappingToExists`
  17144. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17145. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode);
  17146. // Set mainType and complete subType.
  17147. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel);
  17148. // Empty it before the travel, in order to prevent `this._componentsMap`
  17149. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17150. // components, which is probably incorrect logic.
  17151. option[mainType] = null;
  17152. componentsMap.set(mainType, null);
  17153. componentsCount.set(mainType, 0);
  17154. var optionsByMainType = [];
  17155. var cmptsByMainType = [];
  17156. var cmptsCountByMainType = 0;
  17157. var tooltipExists;
  17158. var tooltipWarningLogged;
  17159. each(mappingResult, function (resultItem, index) {
  17160. var componentModel = resultItem.existing;
  17161. var newCmptOption = resultItem.newOption;
  17162. if (!newCmptOption) {
  17163. if (componentModel) {
  17164. // Consider where is no new option and should be merged using {},
  17165. // see removeEdgeAndAdd in topologicalTravel and
  17166. // ComponentModel.getAllClassMainTypes.
  17167. componentModel.mergeOption({}, this);
  17168. componentModel.optionUpdated({}, false);
  17169. }
  17170. // If no both `resultItem.exist` and `resultItem.option`,
  17171. // either it is in `replaceMerge` and not matched by any id,
  17172. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17173. } else {
  17174. var isSeriesType = mainType === 'series';
  17175. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17176. );
  17177. if (!ComponentModelClass) {
  17178. if ("development" !== 'production') {
  17179. var subType = resultItem.keyInfo.subType;
  17180. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17181. if (!componetsMissingLogPrinted[subType]) {
  17182. componetsMissingLogPrinted[subType] = true;
  17183. if (seriesImportName) {
  17184. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17185. } else {
  17186. error("Unknown series " + subType);
  17187. }
  17188. }
  17189. }
  17190. return;
  17191. }
  17192. // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17193. if (mainType === 'tooltip') {
  17194. if (tooltipExists) {
  17195. if ("development" !== 'production') {
  17196. if (!tooltipWarningLogged) {
  17197. warn('Currently only one tooltip component is allowed.');
  17198. tooltipWarningLogged = true;
  17199. }
  17200. }
  17201. return;
  17202. }
  17203. tooltipExists = true;
  17204. }
  17205. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17206. componentModel.name = resultItem.keyInfo.name;
  17207. // componentModel.settingTask && componentModel.settingTask.dirty();
  17208. componentModel.mergeOption(newCmptOption, this);
  17209. componentModel.optionUpdated(newCmptOption, false);
  17210. } else {
  17211. // PENDING Global as parent ?
  17212. var extraOpt = extend({
  17213. componentIndex: index
  17214. }, resultItem.keyInfo);
  17215. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt);
  17216. // Assign `keyInfo`
  17217. extend(componentModel, extraOpt);
  17218. if (resultItem.brandNew) {
  17219. componentModel.__requireNewView = true;
  17220. }
  17221. componentModel.init(newCmptOption, this, this);
  17222. // Call optionUpdated after init.
  17223. // newCmptOption has been used as componentModel.option
  17224. // and may be merged with theme and default, so pass null
  17225. // to avoid confusion.
  17226. componentModel.optionUpdated(null, true);
  17227. }
  17228. }
  17229. if (componentModel) {
  17230. optionsByMainType.push(componentModel.option);
  17231. cmptsByMainType.push(componentModel);
  17232. cmptsCountByMainType++;
  17233. } else {
  17234. // Always do assign to avoid elided item in array.
  17235. optionsByMainType.push(void 0);
  17236. cmptsByMainType.push(void 0);
  17237. }
  17238. }, this);
  17239. option[mainType] = optionsByMainType;
  17240. componentsMap.set(mainType, cmptsByMainType);
  17241. componentsCount.set(mainType, cmptsCountByMainType);
  17242. // Backup series for filtering.
  17243. if (mainType === 'series') {
  17244. reCreateSeriesIndices(this);
  17245. }
  17246. }
  17247. // If no series declared, ensure `_seriesIndices` initialized.
  17248. if (!this._seriesIndices) {
  17249. reCreateSeriesIndices(this);
  17250. }
  17251. };
  17252. /**
  17253. * Get option for output (cloned option and inner info removed)
  17254. */
  17255. GlobalModel.prototype.getOption = function () {
  17256. var option = clone(this.option);
  17257. each(option, function (optInMainType, mainType) {
  17258. if (ComponentModel.hasClass(mainType)) {
  17259. var opts = normalizeToArray(optInMainType);
  17260. // Inner cmpts need to be removed.
  17261. // Inner cmpts might not be at last since ec5.0, but still
  17262. // compatible for users: if inner cmpt at last, splice the returned array.
  17263. var realLen = opts.length;
  17264. var metNonInner = false;
  17265. for (var i = realLen - 1; i >= 0; i--) {
  17266. // Remove options with inner id.
  17267. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17268. metNonInner = true;
  17269. } else {
  17270. opts[i] = null;
  17271. !metNonInner && realLen--;
  17272. }
  17273. }
  17274. opts.length = realLen;
  17275. option[mainType] = opts;
  17276. }
  17277. });
  17278. delete option[OPTION_INNER_KEY];
  17279. return option;
  17280. };
  17281. GlobalModel.prototype.getTheme = function () {
  17282. return this._theme;
  17283. };
  17284. GlobalModel.prototype.getLocaleModel = function () {
  17285. return this._locale;
  17286. };
  17287. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17288. this._payload = payload;
  17289. };
  17290. GlobalModel.prototype.getUpdatePayload = function () {
  17291. return this._payload;
  17292. };
  17293. /**
  17294. * @param idx If not specified, return the first one.
  17295. */
  17296. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17297. var list = this._componentsMap.get(mainType);
  17298. if (list) {
  17299. var cmpt = list[idx || 0];
  17300. if (cmpt) {
  17301. return cmpt;
  17302. } else if (idx == null) {
  17303. for (var i = 0; i < list.length; i++) {
  17304. if (list[i]) {
  17305. return list[i];
  17306. }
  17307. }
  17308. }
  17309. }
  17310. };
  17311. /**
  17312. * @return Never be null/undefined.
  17313. */
  17314. GlobalModel.prototype.queryComponents = function (condition) {
  17315. var mainType = condition.mainType;
  17316. if (!mainType) {
  17317. return [];
  17318. }
  17319. var index = condition.index;
  17320. var id = condition.id;
  17321. var name = condition.name;
  17322. var cmpts = this._componentsMap.get(mainType);
  17323. if (!cmpts || !cmpts.length) {
  17324. return [];
  17325. }
  17326. var result;
  17327. if (index != null) {
  17328. result = [];
  17329. each(normalizeToArray(index), function (idx) {
  17330. cmpts[idx] && result.push(cmpts[idx]);
  17331. });
  17332. } else if (id != null) {
  17333. result = queryByIdOrName('id', id, cmpts);
  17334. } else if (name != null) {
  17335. result = queryByIdOrName('name', name, cmpts);
  17336. } else {
  17337. // Return all non-empty components in that mainType
  17338. result = filter(cmpts, function (cmpt) {
  17339. return !!cmpt;
  17340. });
  17341. }
  17342. return filterBySubType(result, condition);
  17343. };
  17344. /**
  17345. * The interface is different from queryComponents,
  17346. * which is convenient for inner usage.
  17347. *
  17348. * @usage
  17349. * let result = findComponents(
  17350. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17351. * );
  17352. * let result = findComponents(
  17353. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17354. * );
  17355. * let result = findComponents(
  17356. * {mainType: 'series',
  17357. * filter: function (model, index) {...}}
  17358. * );
  17359. * // result like [component0, componnet1, ...]
  17360. */
  17361. GlobalModel.prototype.findComponents = function (condition) {
  17362. var query = condition.query;
  17363. var mainType = condition.mainType;
  17364. var queryCond = getQueryCond(query);
  17365. var result = queryCond ? this.queryComponents(queryCond)
  17366. // Retrieve all non-empty components.
  17367. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17368. return !!cmpt;
  17369. });
  17370. return doFilter(filterBySubType(result, condition));
  17371. function getQueryCond(q) {
  17372. var indexAttr = mainType + 'Index';
  17373. var idAttr = mainType + 'Id';
  17374. var nameAttr = mainType + 'Name';
  17375. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17376. mainType: mainType,
  17377. // subType will be filtered finally.
  17378. index: q[indexAttr],
  17379. id: q[idAttr],
  17380. name: q[nameAttr]
  17381. } : null;
  17382. }
  17383. function doFilter(res) {
  17384. return condition.filter ? filter(res, condition.filter) : res;
  17385. }
  17386. };
  17387. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17388. var componentsMap = this._componentsMap;
  17389. if (isFunction(mainType)) {
  17390. var ctxForAll_1 = cb;
  17391. var cbForAll_1 = mainType;
  17392. componentsMap.each(function (cmpts, componentType) {
  17393. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17394. var cmpt = cmpts[i];
  17395. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17396. }
  17397. });
  17398. } else {
  17399. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17400. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17401. var cmpt = cmpts[i];
  17402. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17403. }
  17404. }
  17405. };
  17406. /**
  17407. * Get series list before filtered by name.
  17408. */
  17409. GlobalModel.prototype.getSeriesByName = function (name) {
  17410. var nameStr = convertOptionIdName(name, null);
  17411. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17412. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17413. });
  17414. };
  17415. /**
  17416. * Get series list before filtered by index.
  17417. */
  17418. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17419. return this._componentsMap.get('series')[seriesIndex];
  17420. };
  17421. /**
  17422. * Get series list before filtered by type.
  17423. * FIXME: rename to getRawSeriesByType?
  17424. */
  17425. GlobalModel.prototype.getSeriesByType = function (subType) {
  17426. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17427. return !!oneSeries && oneSeries.subType === subType;
  17428. });
  17429. };
  17430. /**
  17431. * Get all series before filtered.
  17432. */
  17433. GlobalModel.prototype.getSeries = function () {
  17434. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17435. return !!oneSeries;
  17436. });
  17437. };
  17438. /**
  17439. * Count series before filtered.
  17440. */
  17441. GlobalModel.prototype.getSeriesCount = function () {
  17442. return this._componentsCount.get('series');
  17443. };
  17444. /**
  17445. * After filtering, series may be different
  17446. * from raw series.
  17447. */
  17448. GlobalModel.prototype.eachSeries = function (cb, context) {
  17449. assertSeriesInitialized(this);
  17450. each(this._seriesIndices, function (rawSeriesIndex) {
  17451. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17452. cb.call(context, series, rawSeriesIndex);
  17453. }, this);
  17454. };
  17455. /**
  17456. * Iterate raw series before filtered.
  17457. *
  17458. * @param {Function} cb
  17459. * @param {*} context
  17460. */
  17461. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17462. each(this._componentsMap.get('series'), function (series) {
  17463. series && cb.call(context, series, series.componentIndex);
  17464. });
  17465. };
  17466. /**
  17467. * After filtering, series may be different.
  17468. * from raw series.
  17469. */
  17470. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17471. assertSeriesInitialized(this);
  17472. each(this._seriesIndices, function (rawSeriesIndex) {
  17473. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17474. if (series.subType === subType) {
  17475. cb.call(context, series, rawSeriesIndex);
  17476. }
  17477. }, this);
  17478. };
  17479. /**
  17480. * Iterate raw series before filtered of given type.
  17481. */
  17482. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17483. return each(this.getSeriesByType(subType), cb, context);
  17484. };
  17485. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17486. assertSeriesInitialized(this);
  17487. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17488. };
  17489. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17490. return (this._seriesIndices || []).slice();
  17491. };
  17492. GlobalModel.prototype.filterSeries = function (cb, context) {
  17493. assertSeriesInitialized(this);
  17494. var newSeriesIndices = [];
  17495. each(this._seriesIndices, function (seriesRawIdx) {
  17496. var series = this._componentsMap.get('series')[seriesRawIdx];
  17497. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17498. }, this);
  17499. this._seriesIndices = newSeriesIndices;
  17500. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17501. };
  17502. GlobalModel.prototype.restoreData = function (payload) {
  17503. reCreateSeriesIndices(this);
  17504. var componentsMap = this._componentsMap;
  17505. var componentTypes = [];
  17506. componentsMap.each(function (components, componentType) {
  17507. if (ComponentModel.hasClass(componentType)) {
  17508. componentTypes.push(componentType);
  17509. }
  17510. });
  17511. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17512. each(componentsMap.get(componentType), function (component) {
  17513. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17514. component.restoreData();
  17515. }
  17516. });
  17517. });
  17518. };
  17519. GlobalModel.internalField = function () {
  17520. reCreateSeriesIndices = function (ecModel) {
  17521. var seriesIndices = ecModel._seriesIndices = [];
  17522. each(ecModel._componentsMap.get('series'), function (series) {
  17523. // series may have been removed by `replaceMerge`.
  17524. series && seriesIndices.push(series.componentIndex);
  17525. });
  17526. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17527. };
  17528. assertSeriesInitialized = function (ecModel) {
  17529. // Components that use _seriesIndices should depends on series component,
  17530. // which make sure that their initialization is after series.
  17531. if ("development" !== 'production') {
  17532. if (!ecModel._seriesIndices) {
  17533. throw new Error('Option should contains series.');
  17534. }
  17535. }
  17536. };
  17537. initBase = function (ecModel, baseOption) {
  17538. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  17539. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  17540. ecModel.option = {};
  17541. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE;
  17542. // Init with series: [], in case of calling findSeries method
  17543. // before series initialized.
  17544. ecModel._componentsMap = createHashMap({
  17545. series: []
  17546. });
  17547. ecModel._componentsCount = createHashMap();
  17548. // If user spefied `option.aria`, aria will be enable. This detection should be
  17549. // performed before theme and globalDefault merge.
  17550. var airaOption = baseOption.aria;
  17551. if (isObject(airaOption) && airaOption.enabled == null) {
  17552. airaOption.enabled = true;
  17553. }
  17554. mergeTheme(baseOption, ecModel._theme.option);
  17555. // TODO Needs clone when merging to the unexisted property
  17556. merge(baseOption, globalDefault, false);
  17557. ecModel._mergeOption(baseOption, null);
  17558. };
  17559. }();
  17560. return GlobalModel;
  17561. }(Model);
  17562. function isNotTargetSeries(seriesModel, payload) {
  17563. if (payload) {
  17564. var index = payload.seriesIndex;
  17565. var id = payload.seriesId;
  17566. var name_1 = payload.seriesName;
  17567. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17568. }
  17569. }
  17570. function mergeTheme(option, theme) {
  17571. // PENDING
  17572. // NOT use `colorLayer` in theme if option has `color`
  17573. var notMergeColorLayer = option.color && !option.colorLayer;
  17574. each(theme, function (themeItem, name) {
  17575. if (name === 'colorLayer' && notMergeColorLayer) {
  17576. return;
  17577. }
  17578. // If it is component model mainType, the model handles that merge later.
  17579. // otherwise, merge them here.
  17580. if (!ComponentModel.hasClass(name)) {
  17581. if (typeof themeItem === 'object') {
  17582. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17583. } else {
  17584. if (option[name] == null) {
  17585. option[name] = themeItem;
  17586. }
  17587. }
  17588. }
  17589. });
  17590. }
  17591. function queryByIdOrName(attr, idOrName, cmpts) {
  17592. // Here is a break from echarts4: string and number are
  17593. // treated as equal.
  17594. if (isArray(idOrName)) {
  17595. var keyMap_1 = createHashMap();
  17596. each(idOrName, function (idOrNameItem) {
  17597. if (idOrNameItem != null) {
  17598. var idName = convertOptionIdName(idOrNameItem, null);
  17599. idName != null && keyMap_1.set(idOrNameItem, true);
  17600. }
  17601. });
  17602. return filter(cmpts, function (cmpt) {
  17603. return cmpt && keyMap_1.get(cmpt[attr]);
  17604. });
  17605. } else {
  17606. var idName_1 = convertOptionIdName(idOrName, null);
  17607. return filter(cmpts, function (cmpt) {
  17608. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17609. });
  17610. }
  17611. }
  17612. function filterBySubType(components, condition) {
  17613. // Using hasOwnProperty for restrict. Consider
  17614. // subType is undefined in user payload.
  17615. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  17616. return cmpt && cmpt.subType === condition.subType;
  17617. }) : components;
  17618. }
  17619. function normalizeSetOptionInput(opts) {
  17620. var replaceMergeMainTypeMap = createHashMap();
  17621. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  17622. if ("development" !== 'production') {
  17623. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  17624. }
  17625. replaceMergeMainTypeMap.set(mainType, true);
  17626. });
  17627. return {
  17628. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  17629. };
  17630. }
  17631. mixin(GlobalModel, PaletteMixin);
  17632. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL',
  17633. // 'getModel',
  17634. 'getOption',
  17635. // 'getViewOfComponentModel',
  17636. // 'getViewOfSeriesModel',
  17637. 'getId', 'updateLabelLayout'];
  17638. var ExtensionAPI = /** @class */function () {
  17639. function ExtensionAPI(ecInstance) {
  17640. each(availableMethods, function (methodName) {
  17641. this[methodName] = bind(ecInstance[methodName], ecInstance);
  17642. }, this);
  17643. }
  17644. return ExtensionAPI;
  17645. }();
  17646. var coordinateSystemCreators = {};
  17647. var CoordinateSystemManager = /** @class */function () {
  17648. function CoordinateSystemManager() {
  17649. this._coordinateSystems = [];
  17650. }
  17651. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17652. var coordinateSystems = [];
  17653. each(coordinateSystemCreators, function (creator, type) {
  17654. var list = creator.create(ecModel, api);
  17655. coordinateSystems = coordinateSystems.concat(list || []);
  17656. });
  17657. this._coordinateSystems = coordinateSystems;
  17658. };
  17659. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17660. each(this._coordinateSystems, function (coordSys) {
  17661. coordSys.update && coordSys.update(ecModel, api);
  17662. });
  17663. };
  17664. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17665. return this._coordinateSystems.slice();
  17666. };
  17667. CoordinateSystemManager.register = function (type, creator) {
  17668. coordinateSystemCreators[type] = creator;
  17669. };
  17670. CoordinateSystemManager.get = function (type) {
  17671. return coordinateSystemCreators[type];
  17672. };
  17673. return CoordinateSystemManager;
  17674. }();
  17675. var QUERY_REG = /^(min|max)?(.+)$/;
  17676. // Key: mainType
  17677. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  17678. /**
  17679. * TERM EXPLANATIONS:
  17680. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  17681. */
  17682. var OptionManager = /** @class */function () {
  17683. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17684. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17685. // rawOption cloned and backuped when timeline changed, which does no
  17686. // good to performance. What's more, that both timeline and setOption
  17687. // method supply 'notMerge' brings complex and some problems.
  17688. // Consider this case:
  17689. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17690. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17691. function OptionManager(api) {
  17692. this._timelineOptions = [];
  17693. this._mediaList = [];
  17694. /**
  17695. * -1, means default.
  17696. * empty means no media.
  17697. */
  17698. this._currentMediaIndices = [];
  17699. this._api = api;
  17700. }
  17701. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17702. if (rawOption) {
  17703. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17704. each(normalizeToArray(rawOption.series), function (series) {
  17705. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17706. });
  17707. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17708. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17709. });
  17710. }
  17711. // Caution: some series modify option data, if do not clone,
  17712. // it should ensure that the repeat modify correctly
  17713. // (create a new object when modify itself).
  17714. rawOption = clone(rawOption);
  17715. // FIXME
  17716. // If some property is set in timeline options or media option but
  17717. // not set in baseOption, a warning should be given.
  17718. var optionBackup = this._optionBackup;
  17719. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17720. this._newBaseOption = newParsedOption.baseOption;
  17721. // For setOption at second time (using merge mode);
  17722. if (optionBackup) {
  17723. // FIXME
  17724. // the restore merge solution is essentially incorrect.
  17725. // the mapping can not be 100% consistent with ecModel, which probably brings
  17726. // potential bug!
  17727. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  17728. // let fakeCmptsMap = this._fakeCmptsMap;
  17729. // if (!fakeCmptsMap) {
  17730. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17731. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17732. // }
  17733. // mergeToBackupOption(
  17734. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17735. // );
  17736. // For simplicity, timeline options and media options do not support merge,
  17737. // that is, if you `setOption` twice and both has timeline options, the latter
  17738. // timeline options will not be merged to the former, but just substitute them.
  17739. if (newParsedOption.timelineOptions.length) {
  17740. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17741. }
  17742. if (newParsedOption.mediaList.length) {
  17743. optionBackup.mediaList = newParsedOption.mediaList;
  17744. }
  17745. if (newParsedOption.mediaDefault) {
  17746. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17747. }
  17748. } else {
  17749. this._optionBackup = newParsedOption;
  17750. }
  17751. };
  17752. OptionManager.prototype.mountOption = function (isRecreate) {
  17753. var optionBackup = this._optionBackup;
  17754. this._timelineOptions = optionBackup.timelineOptions;
  17755. this._mediaList = optionBackup.mediaList;
  17756. this._mediaDefault = optionBackup.mediaDefault;
  17757. this._currentMediaIndices = [];
  17758. return clone(isRecreate
  17759. // this._optionBackup.baseOption, which is created at the first `setOption`
  17760. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17761. // each time `setOption` called, can be only used in `isRecreate`, because
  17762. // its reliability is under suspicion. In other cases option merge is
  17763. // performed by `model.mergeOption`.
  17764. ? optionBackup.baseOption : this._newBaseOption);
  17765. };
  17766. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17767. var option;
  17768. var timelineOptions = this._timelineOptions;
  17769. if (timelineOptions.length) {
  17770. // getTimelineOption can only be called after ecModel inited,
  17771. // so we can get currentIndex from timelineModel.
  17772. var timelineModel = ecModel.getComponent('timeline');
  17773. if (timelineModel) {
  17774. option = clone(
  17775. // FIXME:TS as TimelineModel or quivlant interface
  17776. timelineOptions[timelineModel.getCurrentIndex()]);
  17777. }
  17778. }
  17779. return option;
  17780. };
  17781. OptionManager.prototype.getMediaOption = function (ecModel) {
  17782. var ecWidth = this._api.getWidth();
  17783. var ecHeight = this._api.getHeight();
  17784. var mediaList = this._mediaList;
  17785. var mediaDefault = this._mediaDefault;
  17786. var indices = [];
  17787. var result = [];
  17788. // No media defined.
  17789. if (!mediaList.length && !mediaDefault) {
  17790. return result;
  17791. }
  17792. // Multi media may be applied, the latter defined media has higher priority.
  17793. for (var i = 0, len = mediaList.length; i < len; i++) {
  17794. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17795. indices.push(i);
  17796. }
  17797. }
  17798. // FIXME
  17799. // Whether mediaDefault should force users to provide? Otherwise
  17800. // the change by media query can not be recorvered.
  17801. if (!indices.length && mediaDefault) {
  17802. indices = [-1];
  17803. }
  17804. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17805. result = map(indices, function (index) {
  17806. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  17807. });
  17808. }
  17809. // Otherwise return nothing.
  17810. this._currentMediaIndices = indices;
  17811. return result;
  17812. };
  17813. return OptionManager;
  17814. }();
  17815. /**
  17816. * [RAW_OPTION_PATTERNS]
  17817. * (Note: "series: []" represents all other props in `ECUnitOption`)
  17818. *
  17819. * (1) No prop "baseOption" declared:
  17820. * Root option is used as "baseOption" (except prop "options" and "media").
  17821. * ```js
  17822. * option = {
  17823. * series: [],
  17824. * timeline: {},
  17825. * options: [],
  17826. * };
  17827. * option = {
  17828. * series: [],
  17829. * media: {},
  17830. * };
  17831. * option = {
  17832. * series: [],
  17833. * timeline: {},
  17834. * options: [],
  17835. * media: {},
  17836. * }
  17837. * ```
  17838. *
  17839. * (2) Prop "baseOption" declared:
  17840. * If "baseOption" declared, `ECUnitOption` props can only be declared
  17841. * inside "baseOption" except prop "timeline" (compat ec2).
  17842. * ```js
  17843. * option = {
  17844. * baseOption: {
  17845. * timeline: {},
  17846. * series: [],
  17847. * },
  17848. * options: []
  17849. * };
  17850. * option = {
  17851. * baseOption: {
  17852. * series: [],
  17853. * },
  17854. * media: []
  17855. * };
  17856. * option = {
  17857. * baseOption: {
  17858. * timeline: {},
  17859. * series: [],
  17860. * },
  17861. * options: []
  17862. * media: []
  17863. * };
  17864. * option = {
  17865. * // ec3 compat ec2: allow (only) `timeline` declared
  17866. * // outside baseOption. Keep this setting for compat.
  17867. * timeline: {},
  17868. * baseOption: {
  17869. * series: [],
  17870. * },
  17871. * options: [],
  17872. * media: []
  17873. * };
  17874. * ```
  17875. */
  17876. function parseRawOption(
  17877. // `rawOption` May be modified
  17878. rawOption, optionPreprocessorFuncs, isNew) {
  17879. var mediaList = [];
  17880. var mediaDefault;
  17881. var baseOption;
  17882. var declaredBaseOption = rawOption.baseOption;
  17883. // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  17884. var timelineOnRoot = rawOption.timeline;
  17885. var timelineOptionsOnRoot = rawOption.options;
  17886. var mediaOnRoot = rawOption.media;
  17887. var hasMedia = !!rawOption.media;
  17888. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  17889. if (declaredBaseOption) {
  17890. baseOption = declaredBaseOption;
  17891. // For merge option.
  17892. if (!baseOption.timeline) {
  17893. baseOption.timeline = timelineOnRoot;
  17894. }
  17895. }
  17896. // For convenience, enable to use the root option as the `baseOption`:
  17897. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  17898. else {
  17899. if (hasTimeline || hasMedia) {
  17900. rawOption.options = rawOption.media = null;
  17901. }
  17902. baseOption = rawOption;
  17903. }
  17904. if (hasMedia) {
  17905. if (isArray(mediaOnRoot)) {
  17906. each(mediaOnRoot, function (singleMedia) {
  17907. if ("development" !== 'production') {
  17908. // Real case of wrong config.
  17909. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  17910. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  17911. }
  17912. }
  17913. if (singleMedia && singleMedia.option) {
  17914. if (singleMedia.query) {
  17915. mediaList.push(singleMedia);
  17916. } else if (!mediaDefault) {
  17917. // Use the first media default.
  17918. mediaDefault = singleMedia;
  17919. }
  17920. }
  17921. });
  17922. } else {
  17923. if ("development" !== 'production') {
  17924. // Real case of wrong config.
  17925. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  17926. }
  17927. }
  17928. }
  17929. doPreprocess(baseOption);
  17930. each(timelineOptionsOnRoot, function (option) {
  17931. return doPreprocess(option);
  17932. });
  17933. each(mediaList, function (media) {
  17934. return doPreprocess(media.option);
  17935. });
  17936. function doPreprocess(option) {
  17937. each(optionPreprocessorFuncs, function (preProcess) {
  17938. preProcess(option, isNew);
  17939. });
  17940. }
  17941. return {
  17942. baseOption: baseOption,
  17943. timelineOptions: timelineOptionsOnRoot || [],
  17944. mediaDefault: mediaDefault,
  17945. mediaList: mediaList
  17946. };
  17947. }
  17948. /**
  17949. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17950. * Support: width, height, aspectRatio
  17951. * Can use max or min as prefix.
  17952. */
  17953. function applyMediaQuery(query, ecWidth, ecHeight) {
  17954. var realMap = {
  17955. width: ecWidth,
  17956. height: ecHeight,
  17957. aspectratio: ecWidth / ecHeight // lower case for convenience.
  17958. };
  17959. var applicable = true;
  17960. each(query, function (value, attr) {
  17961. var matched = attr.match(QUERY_REG);
  17962. if (!matched || !matched[1] || !matched[2]) {
  17963. return;
  17964. }
  17965. var operator = matched[1];
  17966. var realAttr = matched[2].toLowerCase();
  17967. if (!compare(realMap[realAttr], value, operator)) {
  17968. applicable = false;
  17969. }
  17970. });
  17971. return applicable;
  17972. }
  17973. function compare(real, expect, operator) {
  17974. if (operator === 'min') {
  17975. return real >= expect;
  17976. } else if (operator === 'max') {
  17977. return real <= expect;
  17978. } else {
  17979. // Equals
  17980. return real === expect;
  17981. }
  17982. }
  17983. function indicesEquals(indices1, indices2) {
  17984. // indices is always order by asc and has only finite number.
  17985. return indices1.join(',') === indices2.join(',');
  17986. }
  17987. var each$2 = each;
  17988. var isObject$1 = isObject;
  17989. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  17990. function compatEC2ItemStyle(opt) {
  17991. var itemStyleOpt = opt && opt.itemStyle;
  17992. if (!itemStyleOpt) {
  17993. return;
  17994. }
  17995. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17996. var styleName = POSSIBLE_STYLES[i];
  17997. var normalItemStyleOpt = itemStyleOpt.normal;
  17998. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17999. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18000. if ("development" !== 'production') {
  18001. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18002. }
  18003. opt[styleName] = opt[styleName] || {};
  18004. if (!opt[styleName].normal) {
  18005. opt[styleName].normal = normalItemStyleOpt[styleName];
  18006. } else {
  18007. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18008. }
  18009. normalItemStyleOpt[styleName] = null;
  18010. }
  18011. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18012. if ("development" !== 'production') {
  18013. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18014. }
  18015. opt[styleName] = opt[styleName] || {};
  18016. if (!opt[styleName].emphasis) {
  18017. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18018. } else {
  18019. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18020. }
  18021. emphasisItemStyleOpt[styleName] = null;
  18022. }
  18023. }
  18024. }
  18025. function convertNormalEmphasis(opt, optType, useExtend) {
  18026. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18027. var normalOpt = opt[optType].normal;
  18028. var emphasisOpt = opt[optType].emphasis;
  18029. if (normalOpt) {
  18030. if ("development" !== 'production') {
  18031. // eslint-disable-next-line max-len
  18032. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18033. }
  18034. // Timeline controlStyle has other properties besides normal and emphasis
  18035. if (useExtend) {
  18036. opt[optType].normal = opt[optType].emphasis = null;
  18037. defaults(opt[optType], normalOpt);
  18038. } else {
  18039. opt[optType] = normalOpt;
  18040. }
  18041. }
  18042. if (emphasisOpt) {
  18043. if ("development" !== 'production') {
  18044. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18045. }
  18046. opt.emphasis = opt.emphasis || {};
  18047. opt.emphasis[optType] = emphasisOpt;
  18048. // Also compat the case user mix the style and focus together in ec3 style
  18049. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18050. if (emphasisOpt.focus) {
  18051. opt.emphasis.focus = emphasisOpt.focus;
  18052. }
  18053. if (emphasisOpt.blurScope) {
  18054. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18055. }
  18056. }
  18057. }
  18058. }
  18059. function removeEC3NormalStatus(opt) {
  18060. convertNormalEmphasis(opt, 'itemStyle');
  18061. convertNormalEmphasis(opt, 'lineStyle');
  18062. convertNormalEmphasis(opt, 'areaStyle');
  18063. convertNormalEmphasis(opt, 'label');
  18064. convertNormalEmphasis(opt, 'labelLine');
  18065. // treemap
  18066. convertNormalEmphasis(opt, 'upperLabel');
  18067. // graph
  18068. convertNormalEmphasis(opt, 'edgeLabel');
  18069. }
  18070. function compatTextStyle(opt, propName) {
  18071. // Check whether is not object (string\null\undefined ...)
  18072. var labelOptSingle = isObject$1(opt) && opt[propName];
  18073. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18074. if (textStyle) {
  18075. if ("development" !== 'production') {
  18076. // eslint-disable-next-line max-len
  18077. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18078. }
  18079. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18080. var textPropName = TEXT_STYLE_OPTIONS[i];
  18081. if (textStyle.hasOwnProperty(textPropName)) {
  18082. labelOptSingle[textPropName] = textStyle[textPropName];
  18083. }
  18084. }
  18085. }
  18086. }
  18087. function compatEC3CommonStyles(opt) {
  18088. if (opt) {
  18089. removeEC3NormalStatus(opt);
  18090. compatTextStyle(opt, 'label');
  18091. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18092. }
  18093. }
  18094. function processSeries(seriesOpt) {
  18095. if (!isObject$1(seriesOpt)) {
  18096. return;
  18097. }
  18098. compatEC2ItemStyle(seriesOpt);
  18099. removeEC3NormalStatus(seriesOpt);
  18100. compatTextStyle(seriesOpt, 'label');
  18101. // treemap
  18102. compatTextStyle(seriesOpt, 'upperLabel');
  18103. // graph
  18104. compatTextStyle(seriesOpt, 'edgeLabel');
  18105. if (seriesOpt.emphasis) {
  18106. compatTextStyle(seriesOpt.emphasis, 'label');
  18107. // treemap
  18108. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18109. // graph
  18110. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18111. }
  18112. var markPoint = seriesOpt.markPoint;
  18113. if (markPoint) {
  18114. compatEC2ItemStyle(markPoint);
  18115. compatEC3CommonStyles(markPoint);
  18116. }
  18117. var markLine = seriesOpt.markLine;
  18118. if (markLine) {
  18119. compatEC2ItemStyle(markLine);
  18120. compatEC3CommonStyles(markLine);
  18121. }
  18122. var markArea = seriesOpt.markArea;
  18123. if (markArea) {
  18124. compatEC3CommonStyles(markArea);
  18125. }
  18126. var data = seriesOpt.data;
  18127. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18128. // then the backward compat based on option type will not be performed.
  18129. if (seriesOpt.type === 'graph') {
  18130. data = data || seriesOpt.nodes;
  18131. var edgeData = seriesOpt.links || seriesOpt.edges;
  18132. if (edgeData && !isTypedArray(edgeData)) {
  18133. for (var i = 0; i < edgeData.length; i++) {
  18134. compatEC3CommonStyles(edgeData[i]);
  18135. }
  18136. }
  18137. each(seriesOpt.categories, function (opt) {
  18138. removeEC3NormalStatus(opt);
  18139. });
  18140. }
  18141. if (data && !isTypedArray(data)) {
  18142. for (var i = 0; i < data.length; i++) {
  18143. compatEC3CommonStyles(data[i]);
  18144. }
  18145. }
  18146. // mark point data
  18147. markPoint = seriesOpt.markPoint;
  18148. if (markPoint && markPoint.data) {
  18149. var mpData = markPoint.data;
  18150. for (var i = 0; i < mpData.length; i++) {
  18151. compatEC3CommonStyles(mpData[i]);
  18152. }
  18153. }
  18154. // mark line data
  18155. markLine = seriesOpt.markLine;
  18156. if (markLine && markLine.data) {
  18157. var mlData = markLine.data;
  18158. for (var i = 0; i < mlData.length; i++) {
  18159. if (isArray(mlData[i])) {
  18160. compatEC3CommonStyles(mlData[i][0]);
  18161. compatEC3CommonStyles(mlData[i][1]);
  18162. } else {
  18163. compatEC3CommonStyles(mlData[i]);
  18164. }
  18165. }
  18166. }
  18167. // Series
  18168. if (seriesOpt.type === 'gauge') {
  18169. compatTextStyle(seriesOpt, 'axisLabel');
  18170. compatTextStyle(seriesOpt, 'title');
  18171. compatTextStyle(seriesOpt, 'detail');
  18172. } else if (seriesOpt.type === 'treemap') {
  18173. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18174. each(seriesOpt.levels, function (opt) {
  18175. removeEC3NormalStatus(opt);
  18176. });
  18177. } else if (seriesOpt.type === 'tree') {
  18178. removeEC3NormalStatus(seriesOpt.leaves);
  18179. }
  18180. // sunburst starts from ec4, so it does not need to compat levels.
  18181. }
  18182. function toArr(o) {
  18183. return isArray(o) ? o : o ? [o] : [];
  18184. }
  18185. function toObj(o) {
  18186. return (isArray(o) ? o[0] : o) || {};
  18187. }
  18188. function globalCompatStyle(option, isTheme) {
  18189. each$2(toArr(option.series), function (seriesOpt) {
  18190. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18191. });
  18192. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18193. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18194. each$2(axes, function (axisName) {
  18195. each$2(toArr(option[axisName]), function (axisOpt) {
  18196. if (axisOpt) {
  18197. compatTextStyle(axisOpt, 'axisLabel');
  18198. compatTextStyle(axisOpt.axisPointer, 'label');
  18199. }
  18200. });
  18201. });
  18202. each$2(toArr(option.parallel), function (parallelOpt) {
  18203. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18204. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18205. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18206. });
  18207. each$2(toArr(option.calendar), function (calendarOpt) {
  18208. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18209. compatTextStyle(calendarOpt, 'dayLabel');
  18210. compatTextStyle(calendarOpt, 'monthLabel');
  18211. compatTextStyle(calendarOpt, 'yearLabel');
  18212. });
  18213. // radar.name.textStyle
  18214. each$2(toArr(option.radar), function (radarOpt) {
  18215. compatTextStyle(radarOpt, 'name');
  18216. // Use axisName instead of name because component has name property
  18217. if (radarOpt.name && radarOpt.axisName == null) {
  18218. radarOpt.axisName = radarOpt.name;
  18219. delete radarOpt.name;
  18220. if ("development" !== 'production') {
  18221. deprecateLog('name property in radar component has been changed to axisName');
  18222. }
  18223. }
  18224. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18225. radarOpt.axisNameGap = radarOpt.nameGap;
  18226. delete radarOpt.nameGap;
  18227. if ("development" !== 'production') {
  18228. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18229. }
  18230. }
  18231. if ("development" !== 'production') {
  18232. each$2(radarOpt.indicator, function (indicatorOpt) {
  18233. if (indicatorOpt.text) {
  18234. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18235. }
  18236. });
  18237. }
  18238. });
  18239. each$2(toArr(option.geo), function (geoOpt) {
  18240. if (isObject$1(geoOpt)) {
  18241. compatEC3CommonStyles(geoOpt);
  18242. each$2(toArr(geoOpt.regions), function (regionObj) {
  18243. compatEC3CommonStyles(regionObj);
  18244. });
  18245. }
  18246. });
  18247. each$2(toArr(option.timeline), function (timelineOpt) {
  18248. compatEC3CommonStyles(timelineOpt);
  18249. convertNormalEmphasis(timelineOpt, 'label');
  18250. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18251. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18252. var data = timelineOpt.data;
  18253. isArray(data) && each(data, function (item) {
  18254. if (isObject(item)) {
  18255. convertNormalEmphasis(item, 'label');
  18256. convertNormalEmphasis(item, 'itemStyle');
  18257. }
  18258. });
  18259. });
  18260. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18261. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18262. each$2(toolboxOpt.feature, function (featureOpt) {
  18263. convertNormalEmphasis(featureOpt, 'iconStyle');
  18264. });
  18265. });
  18266. compatTextStyle(toObj(option.axisPointer), 'label');
  18267. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18268. // Clean logs
  18269. // storedLogs = {};
  18270. }
  18271. function get(opt, path) {
  18272. var pathArr = path.split(',');
  18273. var obj = opt;
  18274. for (var i = 0; i < pathArr.length; i++) {
  18275. obj = obj && obj[pathArr[i]];
  18276. if (obj == null) {
  18277. break;
  18278. }
  18279. }
  18280. return obj;
  18281. }
  18282. function set$1(opt, path, val, overwrite) {
  18283. var pathArr = path.split(',');
  18284. var obj = opt;
  18285. var key;
  18286. var i = 0;
  18287. for (; i < pathArr.length - 1; i++) {
  18288. key = pathArr[i];
  18289. if (obj[key] == null) {
  18290. obj[key] = {};
  18291. }
  18292. obj = obj[key];
  18293. }
  18294. if (overwrite || obj[pathArr[i]] == null) {
  18295. obj[pathArr[i]] = val;
  18296. }
  18297. }
  18298. function compatLayoutProperties(option) {
  18299. option && each(LAYOUT_PROPERTIES, function (prop) {
  18300. if (prop[0] in option && !(prop[1] in option)) {
  18301. option[prop[1]] = option[prop[0]];
  18302. }
  18303. });
  18304. }
  18305. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18306. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18307. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18308. function compatBarItemStyle(option) {
  18309. var itemStyle = option && option.itemStyle;
  18310. if (itemStyle) {
  18311. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18312. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18313. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18314. if (itemStyle[oldName] != null) {
  18315. itemStyle[newName] = itemStyle[oldName];
  18316. if ("development" !== 'production') {
  18317. deprecateReplaceLog(oldName, newName);
  18318. }
  18319. }
  18320. }
  18321. }
  18322. }
  18323. function compatPieLabel(option) {
  18324. if (!option) {
  18325. return;
  18326. }
  18327. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18328. if ("development" !== 'production') {
  18329. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18330. }
  18331. option.edgeDistance = option.margin;
  18332. }
  18333. }
  18334. function compatSunburstState(option) {
  18335. if (!option) {
  18336. return;
  18337. }
  18338. if (option.downplay && !option.blur) {
  18339. option.blur = option.downplay;
  18340. if ("development" !== 'production') {
  18341. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18342. }
  18343. }
  18344. }
  18345. function compatGraphFocus(option) {
  18346. if (!option) {
  18347. return;
  18348. }
  18349. if (option.focusNodeAdjacency != null) {
  18350. option.emphasis = option.emphasis || {};
  18351. if (option.emphasis.focus == null) {
  18352. if ("development" !== 'production') {
  18353. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18354. }
  18355. option.emphasis.focus = 'adjacency';
  18356. }
  18357. }
  18358. }
  18359. function traverseTree(data, cb) {
  18360. if (data) {
  18361. for (var i = 0; i < data.length; i++) {
  18362. cb(data[i]);
  18363. data[i] && traverseTree(data[i].children, cb);
  18364. }
  18365. }
  18366. }
  18367. function globalBackwardCompat(option, isTheme) {
  18368. globalCompatStyle(option, isTheme);
  18369. // Make sure series array for model initialization.
  18370. option.series = normalizeToArray(option.series);
  18371. each(option.series, function (seriesOpt) {
  18372. if (!isObject(seriesOpt)) {
  18373. return;
  18374. }
  18375. var seriesType = seriesOpt.type;
  18376. if (seriesType === 'line') {
  18377. if (seriesOpt.clipOverflow != null) {
  18378. seriesOpt.clip = seriesOpt.clipOverflow;
  18379. if ("development" !== 'production') {
  18380. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18381. }
  18382. }
  18383. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18384. if (seriesOpt.clockWise != null) {
  18385. seriesOpt.clockwise = seriesOpt.clockWise;
  18386. if ("development" !== 'production') {
  18387. deprecateReplaceLog('clockWise', 'clockwise');
  18388. }
  18389. }
  18390. compatPieLabel(seriesOpt.label);
  18391. var data = seriesOpt.data;
  18392. if (data && !isTypedArray(data)) {
  18393. for (var i = 0; i < data.length; i++) {
  18394. compatPieLabel(data[i]);
  18395. }
  18396. }
  18397. if (seriesOpt.hoverOffset != null) {
  18398. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18399. if (seriesOpt.emphasis.scaleSize = null) {
  18400. if ("development" !== 'production') {
  18401. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18402. }
  18403. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18404. }
  18405. }
  18406. } else if (seriesType === 'gauge') {
  18407. var pointerColor = get(seriesOpt, 'pointer.color');
  18408. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18409. } else if (seriesType === 'bar') {
  18410. compatBarItemStyle(seriesOpt);
  18411. compatBarItemStyle(seriesOpt.backgroundStyle);
  18412. compatBarItemStyle(seriesOpt.emphasis);
  18413. var data = seriesOpt.data;
  18414. if (data && !isTypedArray(data)) {
  18415. for (var i = 0; i < data.length; i++) {
  18416. if (typeof data[i] === 'object') {
  18417. compatBarItemStyle(data[i]);
  18418. compatBarItemStyle(data[i] && data[i].emphasis);
  18419. }
  18420. }
  18421. }
  18422. } else if (seriesType === 'sunburst') {
  18423. var highlightPolicy = seriesOpt.highlightPolicy;
  18424. if (highlightPolicy) {
  18425. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18426. if (!seriesOpt.emphasis.focus) {
  18427. seriesOpt.emphasis.focus = highlightPolicy;
  18428. if ("development" !== 'production') {
  18429. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18430. }
  18431. }
  18432. }
  18433. compatSunburstState(seriesOpt);
  18434. traverseTree(seriesOpt.data, compatSunburstState);
  18435. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18436. compatGraphFocus(seriesOpt);
  18437. // TODO nodes, edges?
  18438. } else if (seriesType === 'map') {
  18439. if (seriesOpt.mapType && !seriesOpt.map) {
  18440. if ("development" !== 'production') {
  18441. deprecateReplaceLog('mapType', 'map', 'map');
  18442. }
  18443. seriesOpt.map = seriesOpt.mapType;
  18444. }
  18445. if (seriesOpt.mapLocation) {
  18446. if ("development" !== 'production') {
  18447. deprecateLog('`mapLocation` is not used anymore.');
  18448. }
  18449. defaults(seriesOpt, seriesOpt.mapLocation);
  18450. }
  18451. }
  18452. if (seriesOpt.hoverAnimation != null) {
  18453. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18454. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18455. if ("development" !== 'production') {
  18456. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18457. }
  18458. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18459. }
  18460. }
  18461. compatLayoutProperties(seriesOpt);
  18462. });
  18463. // dataRange has changed to visualMap
  18464. if (option.dataRange) {
  18465. option.visualMap = option.dataRange;
  18466. }
  18467. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18468. var options = option[componentName];
  18469. if (options) {
  18470. if (!isArray(options)) {
  18471. options = [options];
  18472. }
  18473. each(options, function (option) {
  18474. compatLayoutProperties(option);
  18475. });
  18476. }
  18477. });
  18478. }
  18479. // (1) [Caution]: the logic is correct based on the premises:
  18480. // data processing stage is blocked in stream.
  18481. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18482. // (2) Only register once when import repeatedly.
  18483. // Should be executed after series is filtered and before stack calculation.
  18484. function dataStack(ecModel) {
  18485. var stackInfoMap = createHashMap();
  18486. ecModel.eachSeries(function (seriesModel) {
  18487. var stack = seriesModel.get('stack');
  18488. // Compatible: when `stack` is set as '', do not stack.
  18489. if (stack) {
  18490. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18491. var data = seriesModel.getData();
  18492. var stackInfo = {
  18493. // Used for calculate axis extent automatically.
  18494. // TODO: Type getCalculationInfo return more specific type?
  18495. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18496. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18497. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18498. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18499. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18500. data: data,
  18501. seriesModel: seriesModel
  18502. };
  18503. // If stacked on axis that do not support data stack.
  18504. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18505. return;
  18506. }
  18507. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18508. stackInfoList.push(stackInfo);
  18509. }
  18510. });
  18511. stackInfoMap.each(calculateStack);
  18512. }
  18513. function calculateStack(stackInfoList) {
  18514. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18515. var resultVal = [];
  18516. var resultNaN = [NaN, NaN];
  18517. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18518. var targetData = targetStackInfo.data;
  18519. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18520. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign';
  18521. // Should not write on raw data, because stack series model list changes
  18522. // depending on legend selection.
  18523. targetData.modify(dims, function (v0, v1, dataIndex) {
  18524. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  18525. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18526. // should also be NaN, to draw a appropriate belt area.
  18527. if (isNaN(sum)) {
  18528. return resultNaN;
  18529. }
  18530. var byValue;
  18531. var stackedDataRawIndex;
  18532. if (isStackedByIndex) {
  18533. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18534. } else {
  18535. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18536. }
  18537. // If stackOver is NaN, chart view will render point on value start.
  18538. var stackedOver = NaN;
  18539. for (var j = idxInStack - 1; j >= 0; j--) {
  18540. var stackInfo = stackInfoList[j];
  18541. // Has been optimized by inverted indices on `stackedByDimension`.
  18542. if (!isStackedByIndex) {
  18543. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18544. }
  18545. if (stackedDataRawIndex >= 0) {
  18546. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  18547. // Considering positive stack, negative stack and empty data
  18548. if (stackStrategy === 'all' // single stack group
  18549. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  18550. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  18551. ) {
  18552. // The sum has to be very small to be affected by the
  18553. // floating arithmetic problem. An incorrect result will probably
  18554. // cause axis min/max to be filtered incorrectly.
  18555. sum = addSafe(sum, val);
  18556. stackedOver = val;
  18557. break;
  18558. }
  18559. }
  18560. }
  18561. resultVal[0] = sum;
  18562. resultVal[1] = stackedOver;
  18563. return resultVal;
  18564. });
  18565. });
  18566. }
  18567. // @inner
  18568. var SourceImpl = /** @class */function () {
  18569. function SourceImpl(fields) {
  18570. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18571. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  18572. // Visit config
  18573. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18574. this.startIndex = fields.startIndex || 0;
  18575. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18576. this.metaRawOption = fields.metaRawOption;
  18577. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18578. if (dimensionsDefine) {
  18579. for (var i = 0; i < dimensionsDefine.length; i++) {
  18580. var dim = dimensionsDefine[i];
  18581. if (dim.type == null) {
  18582. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18583. dim.type = 'ordinal';
  18584. }
  18585. }
  18586. }
  18587. }
  18588. }
  18589. return SourceImpl;
  18590. }();
  18591. function isSourceInstance(val) {
  18592. return val instanceof SourceImpl;
  18593. }
  18594. /**
  18595. * Create a source from option.
  18596. * NOTE: Created source is immutable. Don't change any properties in it.
  18597. */
  18598. function createSource(sourceData, thisMetaRawOption,
  18599. // can be null. If not provided, auto detect it from `sourceData`.
  18600. sourceFormat) {
  18601. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18602. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18603. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18604. var source = new SourceImpl({
  18605. data: sourceData,
  18606. sourceFormat: sourceFormat,
  18607. seriesLayoutBy: seriesLayoutBy,
  18608. dimensionsDefine: determined.dimensionsDefine,
  18609. startIndex: determined.startIndex,
  18610. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18611. metaRawOption: clone(thisMetaRawOption)
  18612. });
  18613. return source;
  18614. }
  18615. /**
  18616. * Wrap original series data for some compatibility cases.
  18617. */
  18618. function createSourceFromSeriesDataOption(data) {
  18619. return new SourceImpl({
  18620. data: data,
  18621. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18622. });
  18623. }
  18624. /**
  18625. * Clone source but excludes source data.
  18626. */
  18627. function cloneSourceShallow(source) {
  18628. return new SourceImpl({
  18629. data: source.data,
  18630. sourceFormat: source.sourceFormat,
  18631. seriesLayoutBy: source.seriesLayoutBy,
  18632. dimensionsDefine: clone(source.dimensionsDefine),
  18633. startIndex: source.startIndex,
  18634. dimensionsDetectedCount: source.dimensionsDetectedCount
  18635. });
  18636. }
  18637. /**
  18638. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18639. */
  18640. function detectSourceFormat(data) {
  18641. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18642. if (isTypedArray(data)) {
  18643. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18644. } else if (isArray(data)) {
  18645. // FIXME Whether tolerate null in top level array?
  18646. if (data.length === 0) {
  18647. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18648. }
  18649. for (var i = 0, len = data.length; i < len; i++) {
  18650. var item = data[i];
  18651. if (item == null) {
  18652. continue;
  18653. } else if (isArray(item) || isTypedArray(item)) {
  18654. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18655. break;
  18656. } else if (isObject(item)) {
  18657. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18658. break;
  18659. }
  18660. }
  18661. } else if (isObject(data)) {
  18662. for (var key in data) {
  18663. if (hasOwn(data, key) && isArrayLike(data[key])) {
  18664. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18665. break;
  18666. }
  18667. }
  18668. }
  18669. return sourceFormat;
  18670. }
  18671. /**
  18672. * Determine the source definitions from data standalone dimensions definitions
  18673. * are not specified.
  18674. */
  18675. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader,
  18676. // standalone raw dimensions definition, like:
  18677. // {
  18678. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  18679. // }
  18680. // in `dataset` or `series`
  18681. dimensionsDefine) {
  18682. var dimensionsDetectedCount;
  18683. var startIndex;
  18684. // PENDING: Could data be null/undefined here?
  18685. // currently, if `dataset.source` not specified, error thrown.
  18686. // if `series.data` not specified, nothing rendered without error thrown.
  18687. // Should test these cases.
  18688. if (!data) {
  18689. return {
  18690. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18691. startIndex: startIndex,
  18692. dimensionsDetectedCount: dimensionsDetectedCount
  18693. };
  18694. }
  18695. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18696. var dataArrayRows = data;
  18697. // Rule: Most of the first line are string: it is header.
  18698. // Caution: consider a line with 5 string and 1 number,
  18699. // it still can not be sure it is a head, because the
  18700. // 5 string may be 5 values of category columns.
  18701. if (sourceHeader === 'auto' || sourceHeader == null) {
  18702. arrayRowsTravelFirst(function (val) {
  18703. // '-' is regarded as null/undefined.
  18704. if (val != null && val !== '-') {
  18705. if (isString(val)) {
  18706. startIndex == null && (startIndex = 1);
  18707. } else {
  18708. startIndex = 0;
  18709. }
  18710. }
  18711. // 10 is an experience number, avoid long loop.
  18712. }, seriesLayoutBy, dataArrayRows, 10);
  18713. } else {
  18714. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  18715. }
  18716. if (!dimensionsDefine && startIndex === 1) {
  18717. dimensionsDefine = [];
  18718. arrayRowsTravelFirst(function (val, index) {
  18719. dimensionsDefine[index] = val != null ? val + '' : '';
  18720. }, seriesLayoutBy, dataArrayRows, Infinity);
  18721. }
  18722. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  18723. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18724. if (!dimensionsDefine) {
  18725. dimensionsDefine = objectRowsCollectDimensions(data);
  18726. }
  18727. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18728. if (!dimensionsDefine) {
  18729. dimensionsDefine = [];
  18730. each(data, function (colArr, key) {
  18731. dimensionsDefine.push(key);
  18732. });
  18733. }
  18734. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18735. var value0 = getDataItemValue(data[0]);
  18736. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  18737. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18738. if ("development" !== 'production') {
  18739. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18740. }
  18741. }
  18742. return {
  18743. startIndex: startIndex,
  18744. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18745. dimensionsDetectedCount: dimensionsDetectedCount
  18746. };
  18747. }
  18748. function objectRowsCollectDimensions(data) {
  18749. var firstIndex = 0;
  18750. var obj;
  18751. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18752. if (obj) {
  18753. return keys(obj);
  18754. }
  18755. }
  18756. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18757. // which is reasonable. But dimension name is duplicated.
  18758. // Returns undefined or an array contains only object without null/undefined or string.
  18759. function normalizeDimensionsOption(dimensionsDefine) {
  18760. if (!dimensionsDefine) {
  18761. // The meaning of null/undefined is different from empty array.
  18762. return;
  18763. }
  18764. var nameMap = createHashMap();
  18765. return map(dimensionsDefine, function (rawItem, index) {
  18766. rawItem = isObject(rawItem) ? rawItem : {
  18767. name: rawItem
  18768. };
  18769. // Other fields will be discarded.
  18770. var item = {
  18771. name: rawItem.name,
  18772. displayName: rawItem.displayName,
  18773. type: rawItem.type
  18774. };
  18775. // User can set null in dimensions.
  18776. // We don't auto specify name, otherwise a given name may
  18777. // cause it to be referred unexpectedly.
  18778. if (item.name == null) {
  18779. return item;
  18780. }
  18781. // Also consider number form like 2012.
  18782. item.name += '';
  18783. // User may also specify displayName.
  18784. // displayName will always exists except user not
  18785. // specified or dim name is not specified or detected.
  18786. // (A auto generated dim name will not be used as
  18787. // displayName).
  18788. if (item.displayName == null) {
  18789. item.displayName = item.name;
  18790. }
  18791. var exist = nameMap.get(item.name);
  18792. if (!exist) {
  18793. nameMap.set(item.name, {
  18794. count: 1
  18795. });
  18796. } else {
  18797. item.name += '-' + exist.count++;
  18798. }
  18799. return item;
  18800. });
  18801. }
  18802. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18803. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18804. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18805. cb(data[i] ? data[i][0] : null, i);
  18806. }
  18807. } else {
  18808. var value0 = data[0] || [];
  18809. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18810. cb(value0[i], i);
  18811. }
  18812. }
  18813. }
  18814. function shouldRetrieveDataByName(source) {
  18815. var sourceFormat = source.sourceFormat;
  18816. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  18817. }
  18818. /*
  18819. * Licensed to the Apache Software Foundation (ASF) under one
  18820. * or more contributor license agreements. See the NOTICE file
  18821. * distributed with this work for additional information
  18822. * regarding copyright ownership. The ASF licenses this file
  18823. * to you under the Apache License, Version 2.0 (the
  18824. * "License"); you may not use this file except in compliance
  18825. * with the License. You may obtain a copy of the License at
  18826. *
  18827. * http://www.apache.org/licenses/LICENSE-2.0
  18828. *
  18829. * Unless required by applicable law or agreed to in writing,
  18830. * software distributed under the License is distributed on an
  18831. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18832. * KIND, either express or implied. See the License for the
  18833. * specific language governing permissions and limitations
  18834. * under the License.
  18835. */
  18836. /**
  18837. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18838. */
  18839. /*
  18840. * Licensed to the Apache Software Foundation (ASF) under one
  18841. * or more contributor license agreements. See the NOTICE file
  18842. * distributed with this work for additional information
  18843. * regarding copyright ownership. The ASF licenses this file
  18844. * to you under the Apache License, Version 2.0 (the
  18845. * "License"); you may not use this file except in compliance
  18846. * with the License. You may obtain a copy of the License at
  18847. *
  18848. * http://www.apache.org/licenses/LICENSE-2.0
  18849. *
  18850. * Unless required by applicable law or agreed to in writing,
  18851. * software distributed under the License is distributed on an
  18852. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18853. * KIND, either express or implied. See the License for the
  18854. * specific language governing permissions and limitations
  18855. * under the License.
  18856. */
  18857. var _a, _b, _c;
  18858. var providerMethods;
  18859. var mountMethods;
  18860. /**
  18861. * If normal array used, mutable chunk size is supported.
  18862. * If typed array used, chunk size must be fixed.
  18863. */
  18864. var DefaultDataProvider = /** @class */function () {
  18865. function DefaultDataProvider(sourceParam, dimSize) {
  18866. // let source: Source;
  18867. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam;
  18868. // declare source is Source;
  18869. this._source = source;
  18870. var data = this._data = source.data;
  18871. // Typed array. TODO IE10+?
  18872. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18873. if ("development" !== 'production') {
  18874. if (dimSize == null) {
  18875. throw new Error('Typed array data must specify dimension size');
  18876. }
  18877. }
  18878. this._offset = 0;
  18879. this._dimSize = dimSize;
  18880. this._data = data;
  18881. }
  18882. mountMethods(this, data, source);
  18883. }
  18884. DefaultDataProvider.prototype.getSource = function () {
  18885. return this._source;
  18886. };
  18887. DefaultDataProvider.prototype.count = function () {
  18888. return 0;
  18889. };
  18890. DefaultDataProvider.prototype.getItem = function (idx, out) {
  18891. return;
  18892. };
  18893. DefaultDataProvider.prototype.appendData = function (newData) {};
  18894. DefaultDataProvider.prototype.clean = function () {};
  18895. DefaultDataProvider.protoInitialize = function () {
  18896. // PENDING: To avoid potential incompat (e.g., prototype
  18897. // is visited somewhere), still init them on prototype.
  18898. var proto = DefaultDataProvider.prototype;
  18899. proto.pure = false;
  18900. proto.persistent = true;
  18901. }();
  18902. DefaultDataProvider.internalField = function () {
  18903. var _a;
  18904. mountMethods = function (provider, data, source) {
  18905. var sourceFormat = source.sourceFormat;
  18906. var seriesLayoutBy = source.seriesLayoutBy;
  18907. var startIndex = source.startIndex;
  18908. var dimsDef = source.dimensionsDefine;
  18909. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18910. if ("development" !== 'production') {
  18911. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18912. }
  18913. extend(provider, methods);
  18914. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18915. provider.getItem = getItemForTypedArray;
  18916. provider.count = countForTypedArray;
  18917. provider.fillStorage = fillStorageForTypedArray;
  18918. } else {
  18919. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  18920. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  18921. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  18922. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  18923. }
  18924. };
  18925. var getItemForTypedArray = function (idx, out) {
  18926. idx = idx - this._offset;
  18927. out = out || [];
  18928. var data = this._data;
  18929. var dimSize = this._dimSize;
  18930. var offset = dimSize * idx;
  18931. for (var i = 0; i < dimSize; i++) {
  18932. out[i] = data[offset + i];
  18933. }
  18934. return out;
  18935. };
  18936. var fillStorageForTypedArray = function (start, end, storage, extent) {
  18937. var data = this._data;
  18938. var dimSize = this._dimSize;
  18939. for (var dim = 0; dim < dimSize; dim++) {
  18940. var dimExtent = extent[dim];
  18941. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  18942. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  18943. var count = end - start;
  18944. var arr = storage[dim];
  18945. for (var i = 0; i < count; i++) {
  18946. // appendData with TypedArray will always do replace in provider.
  18947. var val = data[i * dimSize + dim];
  18948. arr[start + i] = val;
  18949. val < min && (min = val);
  18950. val > max && (max = val);
  18951. }
  18952. dimExtent[0] = min;
  18953. dimExtent[1] = max;
  18954. }
  18955. };
  18956. var countForTypedArray = function () {
  18957. return this._data ? this._data.length / this._dimSize : 0;
  18958. };
  18959. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  18960. pure: true,
  18961. appendData: appendDataSimply
  18962. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  18963. pure: true,
  18964. appendData: function () {
  18965. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18966. }
  18967. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  18968. pure: true,
  18969. appendData: appendDataSimply
  18970. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  18971. pure: true,
  18972. appendData: function (newData) {
  18973. var data = this._data;
  18974. each(newData, function (newCol, key) {
  18975. var oldCol = data[key] || (data[key] = []);
  18976. for (var i = 0; i < (newCol || []).length; i++) {
  18977. oldCol.push(newCol[i]);
  18978. }
  18979. });
  18980. }
  18981. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  18982. appendData: appendDataSimply
  18983. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  18984. persistent: false,
  18985. pure: true,
  18986. appendData: function (newData) {
  18987. if ("development" !== 'production') {
  18988. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  18989. }
  18990. this._data = newData;
  18991. },
  18992. // Clean self if data is already used.
  18993. clean: function () {
  18994. // PENDING
  18995. this._offset += this.count();
  18996. this._data = null;
  18997. }
  18998. }, _a);
  18999. function appendDataSimply(newData) {
  19000. for (var i = 0; i < newData.length; i++) {
  19001. this._data.push(newData[i]);
  19002. }
  19003. }
  19004. }();
  19005. return DefaultDataProvider;
  19006. }();
  19007. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19008. return rawData[idx];
  19009. };
  19010. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19011. return rawData[idx + startIndex];
  19012. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19013. idx += startIndex;
  19014. var item = out || [];
  19015. var data = rawData;
  19016. for (var i = 0; i < data.length; i++) {
  19017. var row = data[i];
  19018. item[i] = row ? row[idx] : null;
  19019. }
  19020. return item;
  19021. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19022. var item = out || [];
  19023. for (var i = 0; i < dimsDef.length; i++) {
  19024. var dimName = dimsDef[i].name;
  19025. if ("development" !== 'production') {
  19026. if (dimName == null) {
  19027. throw new Error();
  19028. }
  19029. }
  19030. var col = rawData[dimName];
  19031. item[i] = col ? col[idx] : null;
  19032. }
  19033. return item;
  19034. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19035. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19036. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19037. if ("development" !== 'production') {
  19038. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19039. }
  19040. return method;
  19041. }
  19042. var countSimply = function (rawData, startIndex, dimsDef) {
  19043. return rawData.length;
  19044. };
  19045. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19046. return Math.max(0, rawData.length - startIndex);
  19047. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19048. var row = rawData[0];
  19049. return row ? Math.max(0, row.length - startIndex) : 0;
  19050. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19051. var dimName = dimsDef[0].name;
  19052. if ("development" !== 'production') {
  19053. if (dimName == null) {
  19054. throw new Error();
  19055. }
  19056. }
  19057. var col = rawData[dimName];
  19058. return col ? col.length : 0;
  19059. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19060. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19061. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19062. if ("development" !== 'production') {
  19063. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19064. }
  19065. return method;
  19066. }
  19067. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19068. return dataItem[dimIndex];
  19069. };
  19070. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19071. return dataItem[property];
  19072. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19073. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19074. // dataItem is {coord: [...]}
  19075. var value = getDataItemValue(dataItem);
  19076. return !(value instanceof Array) ? value : value[dimIndex];
  19077. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19078. function getRawSourceValueGetter(sourceFormat) {
  19079. var method = rawSourceValueGetterMap[sourceFormat];
  19080. if ("development" !== 'production') {
  19081. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  19082. }
  19083. return method;
  19084. }
  19085. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19086. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19087. }
  19088. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19089. // Consider persistent.
  19090. // Caution: why use raw value to display on label or tooltip?
  19091. // A reason is to avoid format. For example time value we do not know
  19092. // how to format is expected. More over, if stack is used, calculated
  19093. // value may be 0.91000000001, which have brings trouble to display.
  19094. // TODO: consider how to treat null/undefined/NaN when display?
  19095. function retrieveRawValue(data, dataIndex,
  19096. // If dimIndex is null/undefined, return OptionDataItem.
  19097. // Otherwise, return OptionDataValue.
  19098. dim) {
  19099. if (!data) {
  19100. return;
  19101. }
  19102. // Consider data may be not persistent.
  19103. var dataItem = data.getRawDataItem(dataIndex);
  19104. if (dataItem == null) {
  19105. return;
  19106. }
  19107. var store = data.getStore();
  19108. var sourceFormat = store.getSource().sourceFormat;
  19109. if (dim != null) {
  19110. var dimIndex = data.getDimensionIndex(dim);
  19111. var property = store.getDimensionProperty(dimIndex);
  19112. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19113. } else {
  19114. var result = dataItem;
  19115. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19116. result = getDataItemValue(dataItem);
  19117. }
  19118. return result;
  19119. }
  19120. }
  19121. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19122. var DataFormatMixin = /** @class */function () {
  19123. function DataFormatMixin() {}
  19124. /**
  19125. * Get params for formatter
  19126. */
  19127. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19128. var data = this.getData(dataType);
  19129. var rawValue = this.getRawValue(dataIndex, dataType);
  19130. var rawDataIndex = data.getRawIndex(dataIndex);
  19131. var name = data.getName(dataIndex);
  19132. var itemOpt = data.getRawDataItem(dataIndex);
  19133. var style = data.getItemVisual(dataIndex, 'style');
  19134. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19135. var borderColor = style && style.stroke;
  19136. var mainType = this.mainType;
  19137. var isSeries = mainType === 'series';
  19138. var userOutput = data.userOutput && data.userOutput.get();
  19139. return {
  19140. componentType: mainType,
  19141. componentSubType: this.subType,
  19142. componentIndex: this.componentIndex,
  19143. seriesType: isSeries ? this.subType : null,
  19144. seriesIndex: this.seriesIndex,
  19145. seriesId: isSeries ? this.id : null,
  19146. seriesName: isSeries ? this.name : null,
  19147. name: name,
  19148. dataIndex: rawDataIndex,
  19149. data: itemOpt,
  19150. dataType: dataType,
  19151. value: rawValue,
  19152. color: color,
  19153. borderColor: borderColor,
  19154. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19155. encode: userOutput ? userOutput.encode : null,
  19156. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19157. $vars: ['seriesName', 'name', 'value']
  19158. };
  19159. };
  19160. /**
  19161. * Format label
  19162. * @param dataIndex
  19163. * @param status 'normal' by default
  19164. * @param dataType
  19165. * @param labelDimIndex Only used in some chart that
  19166. * use formatter in different dimensions, like radar.
  19167. * @param formatter Formatter given outside.
  19168. * @return return null/undefined if no formatter
  19169. */
  19170. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19171. status = status || 'normal';
  19172. var data = this.getData(dataType);
  19173. var params = this.getDataParams(dataIndex, dataType);
  19174. if (extendParams) {
  19175. params.value = extendParams.interpolatedValue;
  19176. }
  19177. if (labelDimIndex != null && isArray(params.value)) {
  19178. params.value = params.value[labelDimIndex];
  19179. }
  19180. if (!formatter) {
  19181. var itemModel = data.getItemModel(dataIndex);
  19182. // @ts-ignore
  19183. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19184. }
  19185. if (isFunction(formatter)) {
  19186. params.status = status;
  19187. params.dimensionIndex = labelDimIndex;
  19188. return formatter(params);
  19189. } else if (isString(formatter)) {
  19190. var str = formatTpl(formatter, params);
  19191. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19192. // Do not support '}' in dim name util have to.
  19193. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19194. var len = dimStr.length;
  19195. var dimLoose = dimStr;
  19196. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19197. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19198. if ("development" !== 'production') {
  19199. if (isNaN(dimLoose)) {
  19200. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19201. }
  19202. }
  19203. }
  19204. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19205. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19206. var dimIndex = data.getDimensionIndex(dimLoose);
  19207. if (dimIndex >= 0) {
  19208. val = extendParams.interpolatedValue[dimIndex];
  19209. }
  19210. }
  19211. return val != null ? val + '' : '';
  19212. });
  19213. }
  19214. };
  19215. /**
  19216. * Get raw value in option
  19217. */
  19218. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19219. return retrieveRawValue(this.getData(dataType), idx);
  19220. };
  19221. /**
  19222. * Should be implemented.
  19223. * @param {number} dataIndex
  19224. * @param {boolean} [multipleSeries=false]
  19225. * @param {string} [dataType]
  19226. */
  19227. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19228. // Empty function
  19229. return;
  19230. };
  19231. return DataFormatMixin;
  19232. }();
  19233. /**
  19234. * @param {Object} define
  19235. * @return See the return of `createTask`.
  19236. */
  19237. function createTask(define) {
  19238. return new Task(define);
  19239. }
  19240. var Task = /** @class */function () {
  19241. function Task(define) {
  19242. define = define || {};
  19243. this._reset = define.reset;
  19244. this._plan = define.plan;
  19245. this._count = define.count;
  19246. this._onDirty = define.onDirty;
  19247. this._dirty = true;
  19248. }
  19249. /**
  19250. * @param step Specified step.
  19251. * @param skip Skip customer perform call.
  19252. * @param modBy Sampling window size.
  19253. * @param modDataCount Sampling count.
  19254. * @return whether unfinished.
  19255. */
  19256. Task.prototype.perform = function (performArgs) {
  19257. var upTask = this._upstream;
  19258. var skip = performArgs && performArgs.skip;
  19259. // TODO some refactor.
  19260. // Pull data. Must pull data each time, because context.data
  19261. // may be updated by Series.setData.
  19262. if (this._dirty && upTask) {
  19263. var context = this.context;
  19264. context.data = context.outputData = upTask.context.outputData;
  19265. }
  19266. if (this.__pipeline) {
  19267. this.__pipeline.currentTask = this;
  19268. }
  19269. var planResult;
  19270. if (this._plan && !skip) {
  19271. planResult = this._plan(this.context);
  19272. }
  19273. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19274. // elements uniformed distributed when progress, especially when moving or zooming.
  19275. var lastModBy = normalizeModBy(this._modBy);
  19276. var lastModDataCount = this._modDataCount || 0;
  19277. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19278. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19279. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19280. planResult = 'reset';
  19281. }
  19282. function normalizeModBy(val) {
  19283. !(val >= 1) && (val = 1); // jshint ignore:line
  19284. return val;
  19285. }
  19286. var forceFirstProgress;
  19287. if (this._dirty || planResult === 'reset') {
  19288. this._dirty = false;
  19289. forceFirstProgress = this._doReset(skip);
  19290. }
  19291. this._modBy = modBy;
  19292. this._modDataCount = modDataCount;
  19293. var step = performArgs && performArgs.step;
  19294. if (upTask) {
  19295. if ("development" !== 'production') {
  19296. assert(upTask._outputDueEnd != null);
  19297. }
  19298. this._dueEnd = upTask._outputDueEnd;
  19299. }
  19300. // DataTask or overallTask
  19301. else {
  19302. if ("development" !== 'production') {
  19303. assert(!this._progress || this._count);
  19304. }
  19305. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19306. }
  19307. // Note: Stubs, that its host overall task let it has progress, has progress.
  19308. // If no progress, pass index from upstream to downstream each time plan called.
  19309. if (this._progress) {
  19310. var start = this._dueIndex;
  19311. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19312. if (!skip && (forceFirstProgress || start < end)) {
  19313. var progress = this._progress;
  19314. if (isArray(progress)) {
  19315. for (var i = 0; i < progress.length; i++) {
  19316. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19317. }
  19318. } else {
  19319. this._doProgress(progress, start, end, modBy, modDataCount);
  19320. }
  19321. }
  19322. this._dueIndex = end;
  19323. // If no `outputDueEnd`, assume that output data and
  19324. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19325. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19326. if ("development" !== 'production') {
  19327. // ??? Can not rollback.
  19328. assert(outputDueEnd >= this._outputDueEnd);
  19329. }
  19330. this._outputDueEnd = outputDueEnd;
  19331. } else {
  19332. // (1) Some overall task has no progress.
  19333. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19334. // This should always be performed so it can be passed to downstream.
  19335. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19336. }
  19337. return this.unfinished();
  19338. };
  19339. Task.prototype.dirty = function () {
  19340. this._dirty = true;
  19341. this._onDirty && this._onDirty(this.context);
  19342. };
  19343. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19344. iterator.reset(start, end, modBy, modDataCount);
  19345. this._callingProgress = progress;
  19346. this._callingProgress({
  19347. start: start,
  19348. end: end,
  19349. count: end - start,
  19350. next: iterator.next
  19351. }, this.context);
  19352. };
  19353. Task.prototype._doReset = function (skip) {
  19354. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19355. this._settedOutputEnd = null;
  19356. var progress;
  19357. var forceFirstProgress;
  19358. if (!skip && this._reset) {
  19359. progress = this._reset(this.context);
  19360. if (progress && progress.progress) {
  19361. forceFirstProgress = progress.forceFirstProgress;
  19362. progress = progress.progress;
  19363. }
  19364. // To simplify no progress checking, array must has item.
  19365. if (isArray(progress) && !progress.length) {
  19366. progress = null;
  19367. }
  19368. }
  19369. this._progress = progress;
  19370. this._modBy = this._modDataCount = null;
  19371. var downstream = this._downstream;
  19372. downstream && downstream.dirty();
  19373. return forceFirstProgress;
  19374. };
  19375. Task.prototype.unfinished = function () {
  19376. return this._progress && this._dueIndex < this._dueEnd;
  19377. };
  19378. /**
  19379. * @param downTask The downstream task.
  19380. * @return The downstream task.
  19381. */
  19382. Task.prototype.pipe = function (downTask) {
  19383. if ("development" !== 'production') {
  19384. assert(downTask && !downTask._disposed && downTask !== this);
  19385. }
  19386. // If already downstream, do not dirty downTask.
  19387. if (this._downstream !== downTask || this._dirty) {
  19388. this._downstream = downTask;
  19389. downTask._upstream = this;
  19390. downTask.dirty();
  19391. }
  19392. };
  19393. Task.prototype.dispose = function () {
  19394. if (this._disposed) {
  19395. return;
  19396. }
  19397. this._upstream && (this._upstream._downstream = null);
  19398. this._downstream && (this._downstream._upstream = null);
  19399. this._dirty = false;
  19400. this._disposed = true;
  19401. };
  19402. Task.prototype.getUpstream = function () {
  19403. return this._upstream;
  19404. };
  19405. Task.prototype.getDownstream = function () {
  19406. return this._downstream;
  19407. };
  19408. Task.prototype.setOutputEnd = function (end) {
  19409. // This only happens in dataTask, dataZoom, map, currently.
  19410. // where dataZoom do not set end each time, but only set
  19411. // when reset. So we should record the set end, in case
  19412. // that the stub of dataZoom perform again and earse the
  19413. // set end by upstream.
  19414. this._outputDueEnd = this._settedOutputEnd = end;
  19415. };
  19416. return Task;
  19417. }();
  19418. var iterator = function () {
  19419. var end;
  19420. var current;
  19421. var modBy;
  19422. var modDataCount;
  19423. var winCount;
  19424. var it = {
  19425. reset: function (s, e, sStep, sCount) {
  19426. current = s;
  19427. end = e;
  19428. modBy = sStep;
  19429. modDataCount = sCount;
  19430. winCount = Math.ceil(modDataCount / modBy);
  19431. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19432. }
  19433. };
  19434. return it;
  19435. function sequentialNext() {
  19436. return current < end ? current++ : null;
  19437. }
  19438. function modNext() {
  19439. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19440. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex
  19441. // If modDataCount is smaller than data.count() (consider `appendData` case),
  19442. // Use normal linear rendering mode.
  19443. : current;
  19444. current++;
  19445. return result;
  19446. }
  19447. }();
  19448. // -----------------------------------------------------------------------------
  19449. // For stream debug (Should be commented out after used!)
  19450. // @usage: printTask(this, 'begin');
  19451. // @usage: printTask(this, null, {someExtraProp});
  19452. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19453. //
  19454. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19455. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19456. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19457. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19458. // let props = [];
  19459. // if (task.__pipeline) {
  19460. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19461. // props.push({text: '__idxInPipeline/total', value: val});
  19462. // } else {
  19463. // let stubCount = 0;
  19464. // task.agentStubMap.each(() => stubCount++);
  19465. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19466. // }
  19467. // props.push({text: 'uid', value: task.uidDebug});
  19468. // if (task.__pipeline) {
  19469. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19470. // task.agent && props.push(
  19471. // {text: 'stubFor', value: task.agent.uidDebug}
  19472. // );
  19473. // }
  19474. // props.push(
  19475. // {text: 'dirty', value: task._dirty},
  19476. // {text: 'dueIndex', value: task._dueIndex},
  19477. // {text: 'dueEnd', value: task._dueEnd},
  19478. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19479. // );
  19480. // if (extra) {
  19481. // Object.keys(extra).forEach(key => {
  19482. // props.push({text: key, value: extra[key]});
  19483. // });
  19484. // }
  19485. // let args = ['color: blue'];
  19486. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19487. // args.push('color: green', 'color: red'),
  19488. // `${item.text}: %c${item.value}`
  19489. // )).join('%c, ');
  19490. // console.log.apply(console, [msg].concat(args));
  19491. // // console.log(this);
  19492. // };
  19493. // window.printPipeline = function (task: any, prefix: string) {
  19494. // const pipeline = task.__pipeline;
  19495. // let currTask = pipeline.head;
  19496. // while (currTask) {
  19497. // window.printTask(currTask, prefix);
  19498. // currTask = currTask._downstream;
  19499. // }
  19500. // };
  19501. // window.showChain = function (chainHeadTask) {
  19502. // var chain = [];
  19503. // var task = chainHeadTask;
  19504. // while (task) {
  19505. // chain.push({
  19506. // task: task,
  19507. // up: task._upstream,
  19508. // down: task._downstream,
  19509. // idxInPipeline: task.__idxInPipeline
  19510. // });
  19511. // task = task._downstream;
  19512. // }
  19513. // return chain;
  19514. // };
  19515. // window.findTaskInChain = function (task, chainHeadTask) {
  19516. // let chain = window.showChain(chainHeadTask);
  19517. // let result = [];
  19518. // for (let i = 0; i < chain.length; i++) {
  19519. // let chainItem = chain[i];
  19520. // if (chainItem.task === task) {
  19521. // result.push(i);
  19522. // }
  19523. // }
  19524. // return result;
  19525. // };
  19526. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19527. // let chainA = window.showChain(chainHeadTaskA);
  19528. // for (let i = 0; i < chainA.length; i++) {
  19529. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19530. // }
  19531. // };
  19532. /**
  19533. * Convert raw the value in to inner value in List.
  19534. *
  19535. * [Performance sensitive]
  19536. *
  19537. * [Caution]: this is the key logic of user value parser.
  19538. * For backward compatibility, do not modify it until you have to!
  19539. */
  19540. function parseDataValue(value,
  19541. // For high performance, do not omit the second param.
  19542. opt) {
  19543. // Performance sensitive.
  19544. var dimType = opt && opt.type;
  19545. if (dimType === 'ordinal') {
  19546. // If given value is a category string
  19547. return value;
  19548. }
  19549. if (dimType === 'time'
  19550. // spead up when using timestamp
  19551. && !isNumber(value) && value != null && value !== '-') {
  19552. value = +parseDate(value);
  19553. }
  19554. // dimType defaults 'number'.
  19555. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19556. // parse to NaN.
  19557. // number-like string (like ' 123 ') can be converted to a number.
  19558. // where null/undefined or other string will be converted to NaN.
  19559. return value == null || value === '' ? NaN
  19560. // If string (like '-'), using '+' parse to NaN
  19561. // If object, also parse to NaN
  19562. : Number(value);
  19563. }
  19564. var valueParserMap = createHashMap({
  19565. 'number': function (val) {
  19566. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  19567. // Here the number parser can have loose rule:
  19568. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19569. return parseFloat(val);
  19570. },
  19571. 'time': function (val) {
  19572. // return timestamp.
  19573. return +parseDate(val);
  19574. },
  19575. 'trim': function (val) {
  19576. return isString(val) ? trim(val) : val;
  19577. }
  19578. });
  19579. /**
  19580. * TODO: disable writable.
  19581. * This structure will be exposed to users.
  19582. */
  19583. var ExternalSource = /** @class */function () {
  19584. function ExternalSource() {}
  19585. ExternalSource.prototype.getRawData = function () {
  19586. // Only built-in transform available.
  19587. throw new Error('not supported');
  19588. };
  19589. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  19590. // Only built-in transform available.
  19591. throw new Error('not supported');
  19592. };
  19593. ExternalSource.prototype.cloneRawData = function () {
  19594. return;
  19595. };
  19596. /**
  19597. * @return If dimension not found, return null/undefined.
  19598. */
  19599. ExternalSource.prototype.getDimensionInfo = function (dim) {
  19600. return;
  19601. };
  19602. /**
  19603. * dimensions defined if and only if either:
  19604. * (a) dataset.dimensions are declared.
  19605. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  19606. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  19607. * the defined dimensions.
  19608. * Otherwise, `dimensionInfoAll` is determined by data columns.
  19609. * @return Always return an array (even empty array).
  19610. */
  19611. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  19612. return;
  19613. };
  19614. ExternalSource.prototype.count = function () {
  19615. return;
  19616. };
  19617. /**
  19618. * Only support by dimension index.
  19619. * No need to support by dimension name in transform function,
  19620. * because transform function is not case-specific, no need to use name literally.
  19621. */
  19622. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  19623. return;
  19624. };
  19625. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  19626. return;
  19627. };
  19628. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  19629. return parseDataValue(rawVal, dimInfo);
  19630. };
  19631. return ExternalSource;
  19632. }();
  19633. function createExternalSource(internalSource, externalTransform) {
  19634. var extSource = new ExternalSource();
  19635. var data = internalSource.data;
  19636. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  19637. var sourceHeaderCount = internalSource.startIndex;
  19638. var errMsg = '';
  19639. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  19640. // For the logic simplicity in transformer, only 'culumn' is
  19641. // supported in data transform. Otherwise, the `dimensionsDefine`
  19642. // might be detected by 'row', which probably confuses users.
  19643. if ("development" !== 'production') {
  19644. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  19645. }
  19646. throwError(errMsg);
  19647. }
  19648. // [MEMO]
  19649. // Create a new dimensions structure for exposing.
  19650. // Do not expose all dimension info to users directly.
  19651. // Because the dimension is probably auto detected from data and not might reliable.
  19652. // Should not lead the transformers to think that is reliable and return it.
  19653. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19654. var dimensions = [];
  19655. var dimsByName = {};
  19656. var dimsDef = internalSource.dimensionsDefine;
  19657. if (dimsDef) {
  19658. each(dimsDef, function (dimDef, idx) {
  19659. var name = dimDef.name;
  19660. var dimDefExt = {
  19661. index: idx,
  19662. name: name,
  19663. displayName: dimDef.displayName
  19664. };
  19665. dimensions.push(dimDefExt);
  19666. // Users probably do not specify dimension name. For simplicity, data transform
  19667. // does not generate dimension name.
  19668. if (name != null) {
  19669. // Dimension name should not be duplicated.
  19670. // For simplicity, data transform forbids name duplication, do not generate
  19671. // new name like module `completeDimensions.ts` did, but just tell users.
  19672. var errMsg_1 = '';
  19673. if (hasOwn(dimsByName, name)) {
  19674. if ("development" !== 'production') {
  19675. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  19676. }
  19677. throwError(errMsg_1);
  19678. }
  19679. dimsByName[name] = dimDefExt;
  19680. }
  19681. });
  19682. }
  19683. // If dimension definitions are not defined and can not be detected.
  19684. // e.g., pure data `[[11, 22], ...]`.
  19685. else {
  19686. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  19687. // Do not generete name or anything others. The consequence process in
  19688. // `transform` or `series` probably have there own name generation strategry.
  19689. dimensions.push({
  19690. index: i
  19691. });
  19692. }
  19693. }
  19694. // Implement public methods:
  19695. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19696. if (externalTransform.__isBuiltIn) {
  19697. extSource.getRawDataItem = function (dataIndex) {
  19698. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19699. };
  19700. extSource.getRawData = bind(getRawData, null, internalSource);
  19701. }
  19702. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  19703. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19704. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  19705. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  19706. extSource.retrieveValue = function (dataIndex, dimIndex) {
  19707. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19708. return retrieveValueFromItem(rawItem, dimIndex);
  19709. };
  19710. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  19711. if (dataItem == null) {
  19712. return;
  19713. }
  19714. var dimDef = dimensions[dimIndex];
  19715. // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  19716. if (dimDef) {
  19717. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  19718. }
  19719. };
  19720. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  19721. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  19722. return extSource;
  19723. }
  19724. function getRawData(upstream) {
  19725. var sourceFormat = upstream.sourceFormat;
  19726. if (!isSupportedSourceFormat(sourceFormat)) {
  19727. var errMsg = '';
  19728. if ("development" !== 'production') {
  19729. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  19730. }
  19731. throwError(errMsg);
  19732. }
  19733. return upstream.data;
  19734. }
  19735. function cloneRawData(upstream) {
  19736. var sourceFormat = upstream.sourceFormat;
  19737. var data = upstream.data;
  19738. if (!isSupportedSourceFormat(sourceFormat)) {
  19739. var errMsg = '';
  19740. if ("development" !== 'production') {
  19741. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  19742. }
  19743. throwError(errMsg);
  19744. }
  19745. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19746. var result = [];
  19747. for (var i = 0, len = data.length; i < len; i++) {
  19748. // Not strictly clone for performance
  19749. result.push(data[i].slice());
  19750. }
  19751. return result;
  19752. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19753. var result = [];
  19754. for (var i = 0, len = data.length; i < len; i++) {
  19755. // Not strictly clone for performance
  19756. result.push(extend({}, data[i]));
  19757. }
  19758. return result;
  19759. }
  19760. }
  19761. function getDimensionInfo(dimensions, dimsByName, dim) {
  19762. if (dim == null) {
  19763. return;
  19764. }
  19765. // Keep the same logic as `List::getDimension` did.
  19766. if (isNumber(dim)
  19767. // If being a number-like string but not being defined a dimension name.
  19768. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  19769. return dimensions[dim];
  19770. } else if (hasOwn(dimsByName, dim)) {
  19771. return dimsByName[dim];
  19772. }
  19773. }
  19774. function cloneAllDimensionInfo(dimensions) {
  19775. return clone(dimensions);
  19776. }
  19777. var externalTransformMap = createHashMap();
  19778. function registerExternalTransform(externalTransform) {
  19779. externalTransform = clone(externalTransform);
  19780. var type = externalTransform.type;
  19781. var errMsg = '';
  19782. if (!type) {
  19783. if ("development" !== 'production') {
  19784. errMsg = 'Must have a `type` when `registerTransform`.';
  19785. }
  19786. throwError(errMsg);
  19787. }
  19788. var typeParsed = type.split(':');
  19789. if (typeParsed.length !== 2) {
  19790. if ("development" !== 'production') {
  19791. errMsg = 'Name must include namespace like "ns:regression".';
  19792. }
  19793. throwError(errMsg);
  19794. }
  19795. // Namespace 'echarts:xxx' is official namespace, where the transforms should
  19796. // be called directly via 'xxx' rather than 'echarts:xxx'.
  19797. var isBuiltIn = false;
  19798. if (typeParsed[0] === 'echarts') {
  19799. type = typeParsed[1];
  19800. isBuiltIn = true;
  19801. }
  19802. externalTransform.__isBuiltIn = isBuiltIn;
  19803. externalTransformMap.set(type, externalTransform);
  19804. }
  19805. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  19806. var pipedTransOption = normalizeToArray(rawTransOption);
  19807. var pipeLen = pipedTransOption.length;
  19808. var errMsg = '';
  19809. if (!pipeLen) {
  19810. if ("development" !== 'production') {
  19811. errMsg = 'If `transform` declared, it should at least contain one transform.';
  19812. }
  19813. throwError(errMsg);
  19814. }
  19815. for (var i = 0, len = pipeLen; i < len; i++) {
  19816. var transOption = pipedTransOption[i];
  19817. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i);
  19818. // piped transform only support single input, except the fist one.
  19819. // piped transform only support single output, except the last one.
  19820. if (i !== len - 1) {
  19821. sourceList.length = Math.max(sourceList.length, 1);
  19822. }
  19823. }
  19824. return sourceList;
  19825. }
  19826. function applySingleDataTransform(transOption, upSourceList, infoForPrint,
  19827. // If `pipeIndex` is null/undefined, no piped transform.
  19828. pipeIndex) {
  19829. var errMsg = '';
  19830. if (!upSourceList.length) {
  19831. if ("development" !== 'production') {
  19832. errMsg = 'Must have at least one upstream dataset.';
  19833. }
  19834. throwError(errMsg);
  19835. }
  19836. if (!isObject(transOption)) {
  19837. if ("development" !== 'production') {
  19838. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  19839. }
  19840. throwError(errMsg);
  19841. }
  19842. var transType = transOption.type;
  19843. var externalTransform = externalTransformMap.get(transType);
  19844. if (!externalTransform) {
  19845. if ("development" !== 'production') {
  19846. errMsg = 'Can not find transform on type "' + transType + '".';
  19847. }
  19848. throwError(errMsg);
  19849. }
  19850. // Prepare source
  19851. var extUpSourceList = map(upSourceList, function (upSource) {
  19852. return createExternalSource(upSource, externalTransform);
  19853. });
  19854. var resultList = normalizeToArray(externalTransform.transform({
  19855. upstream: extUpSourceList[0],
  19856. upstreamList: extUpSourceList,
  19857. config: clone(transOption.config)
  19858. }));
  19859. if ("development" !== 'production') {
  19860. if (transOption.print) {
  19861. var printStrArr = map(resultList, function (extSource) {
  19862. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  19863. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  19864. }).join('\n');
  19865. log(printStrArr);
  19866. }
  19867. }
  19868. return map(resultList, function (result, resultIndex) {
  19869. var errMsg = '';
  19870. if (!isObject(result)) {
  19871. if ("development" !== 'production') {
  19872. errMsg = 'A transform should not return some empty results.';
  19873. }
  19874. throwError(errMsg);
  19875. }
  19876. if (!result.data) {
  19877. if ("development" !== 'production') {
  19878. errMsg = 'Transform result data should be not be null or undefined';
  19879. }
  19880. throwError(errMsg);
  19881. }
  19882. var sourceFormat = detectSourceFormat(result.data);
  19883. if (!isSupportedSourceFormat(sourceFormat)) {
  19884. if ("development" !== 'production') {
  19885. errMsg = 'Transform result data should be array rows or object rows.';
  19886. }
  19887. throwError(errMsg);
  19888. }
  19889. var resultMetaRawOption;
  19890. var firstUpSource = upSourceList[0];
  19891. /**
  19892. * Intuitively, the end users known the content of the original `dataset.source`,
  19893. * calucating the transform result in mind.
  19894. * Suppose the original `dataset.source` is:
  19895. * ```js
  19896. * [
  19897. * ['product', '2012', '2013', '2014', '2015'],
  19898. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  19899. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  19900. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  19901. * ]
  19902. * ```
  19903. * The dimension info have to be detected from the source data.
  19904. * Some of the transformers (like filter, sort) will follow the dimension info
  19905. * of upstream, while others use new dimensions (like aggregate).
  19906. * Transformer can output a field `dimensions` to define the its own output dimensions.
  19907. * We also allow transformers to ignore the output `dimensions` field, and
  19908. * inherit the upstream dimensions definition. It can reduce the burden of handling
  19909. * dimensions in transformers.
  19910. *
  19911. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19912. */
  19913. if (firstUpSource && resultIndex === 0
  19914. // If transformer returns `dimensions`, it means that the transformer has different
  19915. // dimensions definitions. We do not inherit anything from upstream.
  19916. && !result.dimensions) {
  19917. var startIndex = firstUpSource.startIndex;
  19918. // We copy the header of upstream to the result, because:
  19919. // (1) The returned data always does not contain header line and can not be used
  19920. // as dimension-detection. In this case we can not use "detected dimensions" of
  19921. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  19922. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  19923. // So the original detected header should be add to the result, otherwise they can not be read.
  19924. if (startIndex) {
  19925. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  19926. }
  19927. resultMetaRawOption = {
  19928. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19929. sourceHeader: startIndex,
  19930. dimensions: firstUpSource.metaRawOption.dimensions
  19931. };
  19932. } else {
  19933. resultMetaRawOption = {
  19934. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19935. sourceHeader: 0,
  19936. dimensions: result.dimensions
  19937. };
  19938. }
  19939. return createSource(result.data, resultMetaRawOption, null);
  19940. });
  19941. }
  19942. function isSupportedSourceFormat(sourceFormat) {
  19943. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  19944. }
  19945. var UNDEFINED = 'undefined';
  19946. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  19947. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  19948. // different from the Ctor of typed array.
  19949. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  19950. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  19951. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  19952. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  19953. /**
  19954. * Multi dimensional data store
  19955. */
  19956. var dataCtors = {
  19957. 'float': CtorFloat64Array,
  19958. 'int': CtorInt32Array,
  19959. // Ordinal data type can be string or int
  19960. 'ordinal': Array,
  19961. 'number': Array,
  19962. 'time': CtorFloat64Array
  19963. };
  19964. var defaultDimValueGetters;
  19965. function getIndicesCtor(rawCount) {
  19966. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  19967. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  19968. }
  19969. function getInitialExtent() {
  19970. return [Infinity, -Infinity];
  19971. }
  19972. function cloneChunk(originalChunk) {
  19973. var Ctor = originalChunk.constructor;
  19974. // Only shallow clone is enough when Array.
  19975. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  19976. }
  19977. function prepareStore(store, dimIdx, dimType, end, append) {
  19978. var DataCtor = dataCtors[dimType || 'float'];
  19979. if (append) {
  19980. var oldStore = store[dimIdx];
  19981. var oldLen = oldStore && oldStore.length;
  19982. if (!(oldLen === end)) {
  19983. var newStore = new DataCtor(end);
  19984. // The cost of the copy is probably inconsiderable
  19985. // within the initial chunkSize.
  19986. for (var j = 0; j < oldLen; j++) {
  19987. newStore[j] = oldStore[j];
  19988. }
  19989. store[dimIdx] = newStore;
  19990. }
  19991. } else {
  19992. store[dimIdx] = new DataCtor(end);
  19993. }
  19994. }
  19995. /**
  19996. * Basically, DataStore API keep immutable.
  19997. */
  19998. var DataStore = /** @class */function () {
  19999. function DataStore() {
  20000. this._chunks = [];
  20001. // It will not be calculated until needed.
  20002. this._rawExtent = [];
  20003. this._extent = [];
  20004. this._count = 0;
  20005. this._rawCount = 0;
  20006. this._calcDimNameToIdx = createHashMap();
  20007. }
  20008. /**
  20009. * Initialize from data
  20010. */
  20011. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20012. if ("development" !== 'production') {
  20013. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  20014. }
  20015. this._provider = provider;
  20016. // Clear
  20017. this._chunks = [];
  20018. this._indices = null;
  20019. this.getRawIndex = this._getRawIdxIdentity;
  20020. var source = provider.getSource();
  20021. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat];
  20022. // Default dim value getter
  20023. this._dimValueGetter = dimValueGetter || defaultGetter;
  20024. // Reset raw extent.
  20025. this._rawExtent = [];
  20026. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20027. this._dimensions = map(inputDimensions, function (dim) {
  20028. if ("development" !== 'production') {
  20029. if (willRetrieveDataByName) {
  20030. assert(dim.property != null);
  20031. }
  20032. }
  20033. return {
  20034. // Only pick these two props. Not leak other properties like orderMeta.
  20035. type: dim.type,
  20036. property: dim.property
  20037. };
  20038. });
  20039. this._initDataFromProvider(0, provider.count());
  20040. };
  20041. DataStore.prototype.getProvider = function () {
  20042. return this._provider;
  20043. };
  20044. /**
  20045. * Caution: even when a `source` instance owned by a series, the created data store
  20046. * may still be shared by different sereis (the source hash does not use all `source`
  20047. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20048. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20049. * thus should not be fetch here.
  20050. */
  20051. DataStore.prototype.getSource = function () {
  20052. return this._provider.getSource();
  20053. };
  20054. /**
  20055. * @caution Only used in dataStack.
  20056. */
  20057. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20058. var calcDimNameToIdx = this._calcDimNameToIdx;
  20059. var dimensions = this._dimensions;
  20060. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20061. if (calcDimIdx != null) {
  20062. if (dimensions[calcDimIdx].type === type) {
  20063. return calcDimIdx;
  20064. }
  20065. } else {
  20066. calcDimIdx = dimensions.length;
  20067. }
  20068. dimensions[calcDimIdx] = {
  20069. type: type
  20070. };
  20071. calcDimNameToIdx.set(dimName, calcDimIdx);
  20072. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20073. this._rawExtent[calcDimIdx] = getInitialExtent();
  20074. return calcDimIdx;
  20075. };
  20076. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20077. var chunk = this._chunks[dimIdx];
  20078. var dim = this._dimensions[dimIdx];
  20079. var rawExtents = this._rawExtent;
  20080. var offset = dim.ordinalOffset || 0;
  20081. var len = chunk.length;
  20082. if (offset === 0) {
  20083. // We need to reset the rawExtent if collect is from start.
  20084. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20085. rawExtents[dimIdx] = getInitialExtent();
  20086. }
  20087. var dimRawExtent = rawExtents[dimIdx];
  20088. // Parse from previous data offset. len may be changed after appendData
  20089. for (var i = offset; i < len; i++) {
  20090. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20091. if (!isNaN(val)) {
  20092. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20093. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20094. }
  20095. }
  20096. dim.ordinalMeta = ordinalMeta;
  20097. dim.ordinalOffset = len;
  20098. dim.type = 'ordinal'; // Force to be ordinal
  20099. };
  20100. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20101. var dimInfo = this._dimensions[dimIdx];
  20102. var ordinalMeta = dimInfo.ordinalMeta;
  20103. return ordinalMeta;
  20104. };
  20105. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20106. var item = this._dimensions[dimIndex];
  20107. return item && item.property;
  20108. };
  20109. /**
  20110. * Caution: Can be only called on raw data (before `this._indices` created).
  20111. */
  20112. DataStore.prototype.appendData = function (data) {
  20113. if ("development" !== 'production') {
  20114. assert(!this._indices, 'appendData can only be called on raw data.');
  20115. }
  20116. var provider = this._provider;
  20117. var start = this.count();
  20118. provider.appendData(data);
  20119. var end = provider.count();
  20120. if (!provider.persistent) {
  20121. end += start;
  20122. }
  20123. if (start < end) {
  20124. this._initDataFromProvider(start, end, true);
  20125. }
  20126. return [start, end];
  20127. };
  20128. DataStore.prototype.appendValues = function (values, minFillLen) {
  20129. var chunks = this._chunks;
  20130. var dimensions = this._dimensions;
  20131. var dimLen = dimensions.length;
  20132. var rawExtent = this._rawExtent;
  20133. var start = this.count();
  20134. var end = start + Math.max(values.length, minFillLen || 0);
  20135. for (var i = 0; i < dimLen; i++) {
  20136. var dim = dimensions[i];
  20137. prepareStore(chunks, i, dim.type, end, true);
  20138. }
  20139. var emptyDataItem = [];
  20140. for (var idx = start; idx < end; idx++) {
  20141. var sourceIdx = idx - start;
  20142. // Store the data by dimensions
  20143. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20144. var dim = dimensions[dimIdx];
  20145. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20146. chunks[dimIdx][idx] = val;
  20147. var dimRawExtent = rawExtent[dimIdx];
  20148. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20149. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20150. }
  20151. }
  20152. this._rawCount = this._count = end;
  20153. return {
  20154. start: start,
  20155. end: end
  20156. };
  20157. };
  20158. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20159. var provider = this._provider;
  20160. var chunks = this._chunks;
  20161. var dimensions = this._dimensions;
  20162. var dimLen = dimensions.length;
  20163. var rawExtent = this._rawExtent;
  20164. var dimNames = map(dimensions, function (dim) {
  20165. return dim.property;
  20166. });
  20167. for (var i = 0; i < dimLen; i++) {
  20168. var dim = dimensions[i];
  20169. if (!rawExtent[i]) {
  20170. rawExtent[i] = getInitialExtent();
  20171. }
  20172. prepareStore(chunks, i, dim.type, end, append);
  20173. }
  20174. if (provider.fillStorage) {
  20175. provider.fillStorage(start, end, chunks, rawExtent);
  20176. } else {
  20177. var dataItem = [];
  20178. for (var idx = start; idx < end; idx++) {
  20179. // NOTICE: Try not to write things into dataItem
  20180. dataItem = provider.getItem(idx, dataItem);
  20181. // Each data item is value
  20182. // [1, 2]
  20183. // 2
  20184. // Bar chart, line chart which uses category axis
  20185. // only gives the 'y' value. 'x' value is the indices of category
  20186. // Use a tempValue to normalize the value to be a (x, y) value
  20187. // Store the data by dimensions
  20188. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20189. var dimStorage = chunks[dimIdx];
  20190. // PENDING NULL is empty or zero
  20191. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20192. dimStorage[idx] = val;
  20193. var dimRawExtent = rawExtent[dimIdx];
  20194. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20195. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20196. }
  20197. }
  20198. }
  20199. if (!provider.persistent && provider.clean) {
  20200. // Clean unused data if data source is typed array.
  20201. provider.clean();
  20202. }
  20203. this._rawCount = this._count = end;
  20204. // Reset data extent
  20205. this._extent = [];
  20206. };
  20207. DataStore.prototype.count = function () {
  20208. return this._count;
  20209. };
  20210. /**
  20211. * Get value. Return NaN if idx is out of range.
  20212. */
  20213. DataStore.prototype.get = function (dim, idx) {
  20214. if (!(idx >= 0 && idx < this._count)) {
  20215. return NaN;
  20216. }
  20217. var dimStore = this._chunks[dim];
  20218. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20219. };
  20220. DataStore.prototype.getValues = function (dimensions, idx) {
  20221. var values = [];
  20222. var dimArr = [];
  20223. if (idx == null) {
  20224. idx = dimensions;
  20225. // TODO get all from store?
  20226. dimensions = [];
  20227. // All dimensions
  20228. for (var i = 0; i < this._dimensions.length; i++) {
  20229. dimArr.push(i);
  20230. }
  20231. } else {
  20232. dimArr = dimensions;
  20233. }
  20234. for (var i = 0, len = dimArr.length; i < len; i++) {
  20235. values.push(this.get(dimArr[i], idx));
  20236. }
  20237. return values;
  20238. };
  20239. /**
  20240. * @param dim concrete dim
  20241. */
  20242. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20243. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20244. return NaN;
  20245. }
  20246. var dimStore = this._chunks[dim];
  20247. return dimStore ? dimStore[rawIdx] : NaN;
  20248. };
  20249. /**
  20250. * Get sum of data in one dimension
  20251. */
  20252. DataStore.prototype.getSum = function (dim) {
  20253. var dimData = this._chunks[dim];
  20254. var sum = 0;
  20255. if (dimData) {
  20256. for (var i = 0, len = this.count(); i < len; i++) {
  20257. var value = this.get(dim, i);
  20258. if (!isNaN(value)) {
  20259. sum += value;
  20260. }
  20261. }
  20262. }
  20263. return sum;
  20264. };
  20265. /**
  20266. * Get median of data in one dimension
  20267. */
  20268. DataStore.prototype.getMedian = function (dim) {
  20269. var dimDataArray = [];
  20270. // map all data of one dimension
  20271. this.each([dim], function (val) {
  20272. if (!isNaN(val)) {
  20273. dimDataArray.push(val);
  20274. }
  20275. });
  20276. // TODO
  20277. // Use quick select?
  20278. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20279. return a - b;
  20280. });
  20281. var len = this.count();
  20282. // calculate median
  20283. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20284. };
  20285. /**
  20286. * Retrieve the index with given raw data index.
  20287. */
  20288. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20289. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20290. return -1;
  20291. }
  20292. if (!this._indices) {
  20293. return rawIndex;
  20294. }
  20295. // Indices are ascending
  20296. var indices = this._indices;
  20297. // If rawIndex === dataIndex
  20298. var rawDataIndex = indices[rawIndex];
  20299. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20300. return rawIndex;
  20301. }
  20302. var left = 0;
  20303. var right = this._count - 1;
  20304. while (left <= right) {
  20305. var mid = (left + right) / 2 | 0;
  20306. if (indices[mid] < rawIndex) {
  20307. left = mid + 1;
  20308. } else if (indices[mid] > rawIndex) {
  20309. right = mid - 1;
  20310. } else {
  20311. return mid;
  20312. }
  20313. }
  20314. return -1;
  20315. };
  20316. /**
  20317. * Retrieve the index of nearest value.
  20318. * @param dim
  20319. * @param value
  20320. * @param [maxDistance=Infinity]
  20321. * @return If and only if multiple indices have
  20322. * the same value, they are put to the result.
  20323. */
  20324. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20325. var chunks = this._chunks;
  20326. var dimData = chunks[dim];
  20327. var nearestIndices = [];
  20328. if (!dimData) {
  20329. return nearestIndices;
  20330. }
  20331. if (maxDistance == null) {
  20332. maxDistance = Infinity;
  20333. }
  20334. var minDist = Infinity;
  20335. var minDiff = -1;
  20336. var nearestIndicesLen = 0;
  20337. // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20338. for (var i = 0, len = this.count(); i < len; i++) {
  20339. var dataIndex = this.getRawIndex(i);
  20340. var diff = value - dimData[dataIndex];
  20341. var dist = Math.abs(diff);
  20342. if (dist <= maxDistance) {
  20343. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20344. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20345. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20346. // So we choose the one that `diff >= 0` in this case.
  20347. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20348. // should be push to `nearestIndices`.
  20349. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20350. minDist = dist;
  20351. minDiff = diff;
  20352. nearestIndicesLen = 0;
  20353. }
  20354. if (diff === minDiff) {
  20355. nearestIndices[nearestIndicesLen++] = i;
  20356. }
  20357. }
  20358. }
  20359. nearestIndices.length = nearestIndicesLen;
  20360. return nearestIndices;
  20361. };
  20362. DataStore.prototype.getIndices = function () {
  20363. var newIndices;
  20364. var indices = this._indices;
  20365. if (indices) {
  20366. var Ctor = indices.constructor;
  20367. var thisCount = this._count;
  20368. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20369. if (Ctor === Array) {
  20370. newIndices = new Ctor(thisCount);
  20371. for (var i = 0; i < thisCount; i++) {
  20372. newIndices[i] = indices[i];
  20373. }
  20374. } else {
  20375. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20376. }
  20377. } else {
  20378. var Ctor = getIndicesCtor(this._rawCount);
  20379. newIndices = new Ctor(this.count());
  20380. for (var i = 0; i < newIndices.length; i++) {
  20381. newIndices[i] = i;
  20382. }
  20383. }
  20384. return newIndices;
  20385. };
  20386. /**
  20387. * Data filter.
  20388. */
  20389. DataStore.prototype.filter = function (dims, cb) {
  20390. if (!this._count) {
  20391. return this;
  20392. }
  20393. var newStore = this.clone();
  20394. var count = newStore.count();
  20395. var Ctor = getIndicesCtor(newStore._rawCount);
  20396. var newIndices = new Ctor(count);
  20397. var value = [];
  20398. var dimSize = dims.length;
  20399. var offset = 0;
  20400. var dim0 = dims[0];
  20401. var chunks = newStore._chunks;
  20402. for (var i = 0; i < count; i++) {
  20403. var keep = void 0;
  20404. var rawIdx = newStore.getRawIndex(i);
  20405. // Simple optimization
  20406. if (dimSize === 0) {
  20407. keep = cb(i);
  20408. } else if (dimSize === 1) {
  20409. var val = chunks[dim0][rawIdx];
  20410. keep = cb(val, i);
  20411. } else {
  20412. var k = 0;
  20413. for (; k < dimSize; k++) {
  20414. value[k] = chunks[dims[k]][rawIdx];
  20415. }
  20416. value[k] = i;
  20417. keep = cb.apply(null, value);
  20418. }
  20419. if (keep) {
  20420. newIndices[offset++] = rawIdx;
  20421. }
  20422. }
  20423. // Set indices after filtered.
  20424. if (offset < count) {
  20425. newStore._indices = newIndices;
  20426. }
  20427. newStore._count = offset;
  20428. // Reset data extent
  20429. newStore._extent = [];
  20430. newStore._updateGetRawIdx();
  20431. return newStore;
  20432. };
  20433. /**
  20434. * Select data in range. (For optimization of filter)
  20435. * (Manually inline code, support 5 million data filtering in data zoom.)
  20436. */
  20437. DataStore.prototype.selectRange = function (range) {
  20438. var newStore = this.clone();
  20439. var len = newStore._count;
  20440. if (!len) {
  20441. return this;
  20442. }
  20443. var dims = keys(range);
  20444. var dimSize = dims.length;
  20445. if (!dimSize) {
  20446. return this;
  20447. }
  20448. var originalCount = newStore.count();
  20449. var Ctor = getIndicesCtor(newStore._rawCount);
  20450. var newIndices = new Ctor(originalCount);
  20451. var offset = 0;
  20452. var dim0 = dims[0];
  20453. var min = range[dim0][0];
  20454. var max = range[dim0][1];
  20455. var storeArr = newStore._chunks;
  20456. var quickFinished = false;
  20457. if (!newStore._indices) {
  20458. // Extreme optimization for common case. About 2x faster in chrome.
  20459. var idx = 0;
  20460. if (dimSize === 1) {
  20461. var dimStorage = storeArr[dims[0]];
  20462. for (var i = 0; i < len; i++) {
  20463. var val = dimStorage[i];
  20464. // NaN will not be filtered. Consider the case, in line chart, empty
  20465. // value indicates the line should be broken. But for the case like
  20466. // scatter plot, a data item with empty value will not be rendered,
  20467. // but the axis extent may be effected if some other dim of the data
  20468. // item has value. Fortunately it is not a significant negative effect.
  20469. if (val >= min && val <= max || isNaN(val)) {
  20470. newIndices[offset++] = idx;
  20471. }
  20472. idx++;
  20473. }
  20474. quickFinished = true;
  20475. } else if (dimSize === 2) {
  20476. var dimStorage = storeArr[dims[0]];
  20477. var dimStorage2 = storeArr[dims[1]];
  20478. var min2 = range[dims[1]][0];
  20479. var max2 = range[dims[1]][1];
  20480. for (var i = 0; i < len; i++) {
  20481. var val = dimStorage[i];
  20482. var val2 = dimStorage2[i];
  20483. // Do not filter NaN, see comment above.
  20484. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20485. newIndices[offset++] = idx;
  20486. }
  20487. idx++;
  20488. }
  20489. quickFinished = true;
  20490. }
  20491. }
  20492. if (!quickFinished) {
  20493. if (dimSize === 1) {
  20494. for (var i = 0; i < originalCount; i++) {
  20495. var rawIndex = newStore.getRawIndex(i);
  20496. var val = storeArr[dims[0]][rawIndex];
  20497. // Do not filter NaN, see comment above.
  20498. if (val >= min && val <= max || isNaN(val)) {
  20499. newIndices[offset++] = rawIndex;
  20500. }
  20501. }
  20502. } else {
  20503. for (var i = 0; i < originalCount; i++) {
  20504. var keep = true;
  20505. var rawIndex = newStore.getRawIndex(i);
  20506. for (var k = 0; k < dimSize; k++) {
  20507. var dimk = dims[k];
  20508. var val = storeArr[dimk][rawIndex];
  20509. // Do not filter NaN, see comment above.
  20510. if (val < range[dimk][0] || val > range[dimk][1]) {
  20511. keep = false;
  20512. }
  20513. }
  20514. if (keep) {
  20515. newIndices[offset++] = newStore.getRawIndex(i);
  20516. }
  20517. }
  20518. }
  20519. }
  20520. // Set indices after filtered.
  20521. if (offset < originalCount) {
  20522. newStore._indices = newIndices;
  20523. }
  20524. newStore._count = offset;
  20525. // Reset data extent
  20526. newStore._extent = [];
  20527. newStore._updateGetRawIdx();
  20528. return newStore;
  20529. };
  20530. // /**
  20531. // * Data mapping to a plain array
  20532. // */
  20533. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  20534. // const result: any[] = [];
  20535. // this.each(dims, function () {
  20536. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  20537. // });
  20538. // return result;
  20539. // }
  20540. /**
  20541. * Data mapping to a new List with given dimensions
  20542. */
  20543. DataStore.prototype.map = function (dims, cb) {
  20544. // TODO only clone picked chunks.
  20545. var target = this.clone(dims);
  20546. this._updateDims(target, dims, cb);
  20547. return target;
  20548. };
  20549. /**
  20550. * @caution Danger!! Only used in dataStack.
  20551. */
  20552. DataStore.prototype.modify = function (dims, cb) {
  20553. this._updateDims(this, dims, cb);
  20554. };
  20555. DataStore.prototype._updateDims = function (target, dims, cb) {
  20556. var targetChunks = target._chunks;
  20557. var tmpRetValue = [];
  20558. var dimSize = dims.length;
  20559. var dataCount = target.count();
  20560. var values = [];
  20561. var rawExtent = target._rawExtent;
  20562. for (var i = 0; i < dims.length; i++) {
  20563. rawExtent[dims[i]] = getInitialExtent();
  20564. }
  20565. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  20566. var rawIndex = target.getRawIndex(dataIndex);
  20567. for (var k = 0; k < dimSize; k++) {
  20568. values[k] = targetChunks[dims[k]][rawIndex];
  20569. }
  20570. values[dimSize] = dataIndex;
  20571. var retValue = cb && cb.apply(null, values);
  20572. if (retValue != null) {
  20573. // a number or string (in oridinal dimension)?
  20574. if (typeof retValue !== 'object') {
  20575. tmpRetValue[0] = retValue;
  20576. retValue = tmpRetValue;
  20577. }
  20578. for (var i = 0; i < retValue.length; i++) {
  20579. var dim = dims[i];
  20580. var val = retValue[i];
  20581. var rawExtentOnDim = rawExtent[dim];
  20582. var dimStore = targetChunks[dim];
  20583. if (dimStore) {
  20584. dimStore[rawIndex] = val;
  20585. }
  20586. if (val < rawExtentOnDim[0]) {
  20587. rawExtentOnDim[0] = val;
  20588. }
  20589. if (val > rawExtentOnDim[1]) {
  20590. rawExtentOnDim[1] = val;
  20591. }
  20592. }
  20593. }
  20594. }
  20595. };
  20596. /**
  20597. * Large data down sampling using largest-triangle-three-buckets
  20598. * @param {string} valueDimension
  20599. * @param {number} targetCount
  20600. */
  20601. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  20602. var target = this.clone([valueDimension], true);
  20603. var targetStorage = target._chunks;
  20604. var dimStore = targetStorage[valueDimension];
  20605. var len = this.count();
  20606. var sampledIndex = 0;
  20607. var frameSize = Math.floor(1 / rate);
  20608. var currentRawIndex = this.getRawIndex(0);
  20609. var maxArea;
  20610. var area;
  20611. var nextRawIndex;
  20612. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len));
  20613. // First frame use the first data.
  20614. newIndices[sampledIndex++] = currentRawIndex;
  20615. for (var i = 1; i < len - 1; i += frameSize) {
  20616. var nextFrameStart = Math.min(i + frameSize, len - 1);
  20617. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  20618. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  20619. var avgY = 0;
  20620. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  20621. var rawIndex = this.getRawIndex(idx);
  20622. var y = dimStore[rawIndex];
  20623. if (isNaN(y)) {
  20624. continue;
  20625. }
  20626. avgY += y;
  20627. }
  20628. avgY /= nextFrameEnd - nextFrameStart;
  20629. var frameStart = i;
  20630. var frameEnd = Math.min(i + frameSize, len);
  20631. var pointAX = i - 1;
  20632. var pointAY = dimStore[currentRawIndex];
  20633. maxArea = -1;
  20634. nextRawIndex = frameStart;
  20635. var firstNaNIndex = -1;
  20636. var countNaN = 0;
  20637. // Find a point from current frame that construct a triangle with largest area with previous selected point
  20638. // And the average of next frame.
  20639. for (var idx = frameStart; idx < frameEnd; idx++) {
  20640. var rawIndex = this.getRawIndex(idx);
  20641. var y = dimStore[rawIndex];
  20642. if (isNaN(y)) {
  20643. countNaN++;
  20644. if (firstNaNIndex < 0) {
  20645. firstNaNIndex = rawIndex;
  20646. }
  20647. continue;
  20648. }
  20649. // Calculate triangle area over three buckets
  20650. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  20651. if (area > maxArea) {
  20652. maxArea = area;
  20653. nextRawIndex = rawIndex; // Next a is this b
  20654. }
  20655. }
  20656. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  20657. // Append first NaN point in every bucket.
  20658. // It is necessary to ensure the correct order of indices.
  20659. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  20660. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  20661. }
  20662. newIndices[sampledIndex++] = nextRawIndex;
  20663. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  20664. }
  20665. // First frame use the last data.
  20666. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  20667. target._count = sampledIndex;
  20668. target._indices = newIndices;
  20669. target.getRawIndex = this._getRawIdx;
  20670. return target;
  20671. };
  20672. /**
  20673. * Large data down sampling on given dimension
  20674. * @param sampleIndex Sample index for name and id
  20675. */
  20676. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  20677. var target = this.clone([dimension], true);
  20678. var targetStorage = target._chunks;
  20679. var frameValues = [];
  20680. var frameSize = Math.floor(1 / rate);
  20681. var dimStore = targetStorage[dimension];
  20682. var len = this.count();
  20683. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  20684. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  20685. var offset = 0;
  20686. for (var i = 0; i < len; i += frameSize) {
  20687. // Last frame
  20688. if (frameSize > len - i) {
  20689. frameSize = len - i;
  20690. frameValues.length = frameSize;
  20691. }
  20692. for (var k = 0; k < frameSize; k++) {
  20693. var dataIdx = this.getRawIndex(i + k);
  20694. frameValues[k] = dimStore[dataIdx];
  20695. }
  20696. var value = sampleValue(frameValues);
  20697. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1));
  20698. // Only write value on the filtered data
  20699. dimStore[sampleFrameIdx] = value;
  20700. if (value < rawExtentOnDim[0]) {
  20701. rawExtentOnDim[0] = value;
  20702. }
  20703. if (value > rawExtentOnDim[1]) {
  20704. rawExtentOnDim[1] = value;
  20705. }
  20706. newIndices[offset++] = sampleFrameIdx;
  20707. }
  20708. target._count = offset;
  20709. target._indices = newIndices;
  20710. target._updateGetRawIdx();
  20711. return target;
  20712. };
  20713. /**
  20714. * Data iteration
  20715. * @param ctx default this
  20716. * @example
  20717. * list.each('x', function (x, idx) {});
  20718. * list.each(['x', 'y'], function (x, y, idx) {});
  20719. * list.each(function (idx) {})
  20720. */
  20721. DataStore.prototype.each = function (dims, cb) {
  20722. if (!this._count) {
  20723. return;
  20724. }
  20725. var dimSize = dims.length;
  20726. var chunks = this._chunks;
  20727. for (var i = 0, len = this.count(); i < len; i++) {
  20728. var rawIdx = this.getRawIndex(i);
  20729. // Simple optimization
  20730. switch (dimSize) {
  20731. case 0:
  20732. cb(i);
  20733. break;
  20734. case 1:
  20735. cb(chunks[dims[0]][rawIdx], i);
  20736. break;
  20737. case 2:
  20738. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  20739. break;
  20740. default:
  20741. var k = 0;
  20742. var value = [];
  20743. for (; k < dimSize; k++) {
  20744. value[k] = chunks[dims[k]][rawIdx];
  20745. }
  20746. // Index
  20747. value[k] = i;
  20748. cb.apply(null, value);
  20749. }
  20750. }
  20751. };
  20752. /**
  20753. * Get extent of data in one dimension
  20754. */
  20755. DataStore.prototype.getDataExtent = function (dim) {
  20756. // Make sure use concrete dim as cache name.
  20757. var dimData = this._chunks[dim];
  20758. var initialExtent = getInitialExtent();
  20759. if (!dimData) {
  20760. return initialExtent;
  20761. }
  20762. // Make more strict checkings to ensure hitting cache.
  20763. var currEnd = this.count();
  20764. // Consider the most cases when using data zoom, `getDataExtent`
  20765. // happened before filtering. We cache raw extent, which is not
  20766. // necessary to be cleared and recalculated when restore data.
  20767. var useRaw = !this._indices;
  20768. var dimExtent;
  20769. if (useRaw) {
  20770. return this._rawExtent[dim].slice();
  20771. }
  20772. dimExtent = this._extent[dim];
  20773. if (dimExtent) {
  20774. return dimExtent.slice();
  20775. }
  20776. dimExtent = initialExtent;
  20777. var min = dimExtent[0];
  20778. var max = dimExtent[1];
  20779. for (var i = 0; i < currEnd; i++) {
  20780. var rawIdx = this.getRawIndex(i);
  20781. var value = dimData[rawIdx];
  20782. value < min && (min = value);
  20783. value > max && (max = value);
  20784. }
  20785. dimExtent = [min, max];
  20786. this._extent[dim] = dimExtent;
  20787. return dimExtent;
  20788. };
  20789. /**
  20790. * Get raw data item
  20791. */
  20792. DataStore.prototype.getRawDataItem = function (idx) {
  20793. var rawIdx = this.getRawIndex(idx);
  20794. if (!this._provider.persistent) {
  20795. var val = [];
  20796. var chunks = this._chunks;
  20797. for (var i = 0; i < chunks.length; i++) {
  20798. val.push(chunks[i][rawIdx]);
  20799. }
  20800. return val;
  20801. } else {
  20802. return this._provider.getItem(rawIdx);
  20803. }
  20804. };
  20805. /**
  20806. * Clone shallow.
  20807. *
  20808. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  20809. */
  20810. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  20811. var target = new DataStore();
  20812. var chunks = this._chunks;
  20813. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  20814. obj[dimIdx] = true;
  20815. return obj;
  20816. }, {});
  20817. if (clonedDimsMap) {
  20818. for (var i = 0; i < chunks.length; i++) {
  20819. // Not clone if dim is not picked.
  20820. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  20821. }
  20822. } else {
  20823. target._chunks = chunks;
  20824. }
  20825. this._copyCommonProps(target);
  20826. if (!ignoreIndices) {
  20827. target._indices = this._cloneIndices();
  20828. }
  20829. target._updateGetRawIdx();
  20830. return target;
  20831. };
  20832. DataStore.prototype._copyCommonProps = function (target) {
  20833. target._count = this._count;
  20834. target._rawCount = this._rawCount;
  20835. target._provider = this._provider;
  20836. target._dimensions = this._dimensions;
  20837. target._extent = clone(this._extent);
  20838. target._rawExtent = clone(this._rawExtent);
  20839. };
  20840. DataStore.prototype._cloneIndices = function () {
  20841. if (this._indices) {
  20842. var Ctor = this._indices.constructor;
  20843. var indices = void 0;
  20844. if (Ctor === Array) {
  20845. var thisCount = this._indices.length;
  20846. indices = new Ctor(thisCount);
  20847. for (var i = 0; i < thisCount; i++) {
  20848. indices[i] = this._indices[i];
  20849. }
  20850. } else {
  20851. indices = new Ctor(this._indices);
  20852. }
  20853. return indices;
  20854. }
  20855. return null;
  20856. };
  20857. DataStore.prototype._getRawIdxIdentity = function (idx) {
  20858. return idx;
  20859. };
  20860. DataStore.prototype._getRawIdx = function (idx) {
  20861. if (idx < this._count && idx >= 0) {
  20862. return this._indices[idx];
  20863. }
  20864. return -1;
  20865. };
  20866. DataStore.prototype._updateGetRawIdx = function () {
  20867. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  20868. };
  20869. DataStore.internalField = function () {
  20870. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  20871. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  20872. }
  20873. defaultDimValueGetters = {
  20874. arrayRows: getDimValueSimply,
  20875. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  20876. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  20877. },
  20878. keyedColumns: getDimValueSimply,
  20879. original: function (dataItem, property, dataIndex, dimIndex) {
  20880. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20881. // If dataItem is an plain object with no value field, the let `value`
  20882. // will be assigned with the object, but it will be tread correctly
  20883. // in the `convertValue`.
  20884. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20885. return parseDataValue(value instanceof Array ? value[dimIndex]
  20886. // If value is a single number or something else not array.
  20887. : value, this._dimensions[dimIndex]);
  20888. },
  20889. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  20890. return dataItem[dimIndex];
  20891. }
  20892. };
  20893. }();
  20894. return DataStore;
  20895. }();
  20896. /**
  20897. * [REQUIREMENT_MEMO]:
  20898. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  20899. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  20900. * `root-dataset`. Them on `series` has higher priority.
  20901. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  20902. * confuse users: whether those props indicate how to visit the upstream source or visit
  20903. * the transform result source, and some transforms has nothing to do with these props,
  20904. * and some transforms might have multiple upstream.
  20905. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  20906. * declared in `root-dataset`.
  20907. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  20908. * That is for reducing complexity in transforms.
  20909. * PENDING: Whether to provide transposition transform?
  20910. *
  20911. * [IMPLEMENTAION_MEMO]:
  20912. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  20913. * They will not be calculated until `source` is about to be visited (to prevent from
  20914. * duplicate calcuation). `source` is visited only in series and input to transforms.
  20915. *
  20916. * [DIMENSION_INHERIT_RULE]:
  20917. * By default the dimensions are inherited from ancestors, unless a transform return
  20918. * a new dimensions definition.
  20919. * Consider the case:
  20920. * ```js
  20921. * dataset: [{
  20922. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  20923. * }, {
  20924. * transform: { type: 'filter', ... }
  20925. * }]
  20926. * dataset: [{
  20927. * dimension: ['Product', 'Sales', 'Prise'],
  20928. * source: [ ['Cookies', 321, 44.21], ...]
  20929. * }, {
  20930. * transform: { type: 'filter', ... }
  20931. * }]
  20932. * ```
  20933. * The two types of option should have the same behavior after transform.
  20934. *
  20935. *
  20936. * [SCENARIO]:
  20937. * (1) Provide source data directly:
  20938. * ```js
  20939. * series: {
  20940. * encode: {...},
  20941. * dimensions: [...]
  20942. * seriesLayoutBy: 'row',
  20943. * data: [[...]]
  20944. * }
  20945. * ```
  20946. * (2) Series refer to dataset.
  20947. * ```js
  20948. * series: [{
  20949. * encode: {...}
  20950. * // Ignore datasetIndex means `datasetIndex: 0`
  20951. * // and the dimensions defination in dataset is used
  20952. * }, {
  20953. * encode: {...},
  20954. * seriesLayoutBy: 'column',
  20955. * datasetIndex: 1
  20956. * }]
  20957. * ```
  20958. * (3) dataset transform
  20959. * ```js
  20960. * dataset: [{
  20961. * source: [...]
  20962. * }, {
  20963. * source: [...]
  20964. * }, {
  20965. * // By default from 0.
  20966. * transform: { type: 'filter', config: {...} }
  20967. * }, {
  20968. * // Piped.
  20969. * transform: [
  20970. * { type: 'filter', config: {...} },
  20971. * { type: 'sort', config: {...} }
  20972. * ]
  20973. * }, {
  20974. * id: 'regressionData',
  20975. * fromDatasetIndex: 1,
  20976. * // Third-party transform
  20977. * transform: { type: 'ecStat:regression', config: {...} }
  20978. * }, {
  20979. * // retrieve the extra result.
  20980. * id: 'regressionFormula',
  20981. * fromDatasetId: 'regressionData',
  20982. * fromTransformResult: 1
  20983. * }]
  20984. * ```
  20985. */
  20986. var SourceManager = /** @class */function () {
  20987. function SourceManager(sourceHost) {
  20988. // Cached source. Do not repeat calculating if not dirty.
  20989. this._sourceList = [];
  20990. this._storeList = [];
  20991. // version sign of each upstream source manager.
  20992. this._upstreamSignList = [];
  20993. this._versionSignBase = 0;
  20994. this._dirty = true;
  20995. this._sourceHost = sourceHost;
  20996. }
  20997. /**
  20998. * Mark dirty.
  20999. */
  21000. SourceManager.prototype.dirty = function () {
  21001. this._setLocalSource([], []);
  21002. this._storeList = [];
  21003. this._dirty = true;
  21004. };
  21005. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21006. this._sourceList = sourceList;
  21007. this._upstreamSignList = upstreamSignList;
  21008. this._versionSignBase++;
  21009. if (this._versionSignBase > 9e10) {
  21010. this._versionSignBase = 0;
  21011. }
  21012. };
  21013. /**
  21014. * For detecting whether the upstream source is dirty, so that
  21015. * the local cached source (in `_sourceList`) should be discarded.
  21016. */
  21017. SourceManager.prototype._getVersionSign = function () {
  21018. return this._sourceHost.uid + '_' + this._versionSignBase;
  21019. };
  21020. /**
  21021. * Always return a source instance. Otherwise throw error.
  21022. */
  21023. SourceManager.prototype.prepareSource = function () {
  21024. // For the case that call `setOption` multiple time but no data changed,
  21025. // cache the result source to prevent from repeating transform.
  21026. if (this._isDirty()) {
  21027. this._createSource();
  21028. this._dirty = false;
  21029. }
  21030. };
  21031. SourceManager.prototype._createSource = function () {
  21032. this._setLocalSource([], []);
  21033. var sourceHost = this._sourceHost;
  21034. var upSourceMgrList = this._getUpstreamSourceManagers();
  21035. var hasUpstream = !!upSourceMgrList.length;
  21036. var resultSourceList;
  21037. var upstreamSignList;
  21038. if (isSeries(sourceHost)) {
  21039. var seriesModel = sourceHost;
  21040. var data = void 0;
  21041. var sourceFormat = void 0;
  21042. var upSource = void 0;
  21043. // Has upstream dataset
  21044. if (hasUpstream) {
  21045. var upSourceMgr = upSourceMgrList[0];
  21046. upSourceMgr.prepareSource();
  21047. upSource = upSourceMgr.getSource();
  21048. data = upSource.data;
  21049. sourceFormat = upSource.sourceFormat;
  21050. upstreamSignList = [upSourceMgr._getVersionSign()];
  21051. }
  21052. // Series data is from own.
  21053. else {
  21054. data = seriesModel.get('data', true);
  21055. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21056. upstreamSignList = [];
  21057. }
  21058. // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21059. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21060. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21061. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21062. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader);
  21063. // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21064. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21065. // but series need `seriesLayoutBy: 'row'`.
  21066. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions);
  21067. // We share source with dataset as much as possible
  21068. // to avoid extra memory cost of high dimensional data.
  21069. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21070. resultSourceList = needsCreateSource ? [createSource(data, {
  21071. seriesLayoutBy: seriesLayoutBy,
  21072. sourceHeader: sourceHeader,
  21073. dimensions: dimensions
  21074. }, sourceFormat)] : [];
  21075. } else {
  21076. var datasetModel = sourceHost;
  21077. // Has upstream dataset.
  21078. if (hasUpstream) {
  21079. var result = this._applyTransform(upSourceMgrList);
  21080. resultSourceList = result.sourceList;
  21081. upstreamSignList = result.upstreamSignList;
  21082. }
  21083. // Is root dataset.
  21084. else {
  21085. var sourceData = datasetModel.get('source', true);
  21086. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21087. upstreamSignList = [];
  21088. }
  21089. }
  21090. if ("development" !== 'production') {
  21091. assert(resultSourceList && upstreamSignList);
  21092. }
  21093. this._setLocalSource(resultSourceList, upstreamSignList);
  21094. };
  21095. SourceManager.prototype._applyTransform = function (upMgrList) {
  21096. var datasetModel = this._sourceHost;
  21097. var transformOption = datasetModel.get('transform', true);
  21098. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21099. if ("development" !== 'production') {
  21100. assert(fromTransformResult != null || transformOption != null);
  21101. }
  21102. if (fromTransformResult != null) {
  21103. var errMsg = '';
  21104. if (upMgrList.length !== 1) {
  21105. if ("development" !== 'production') {
  21106. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21107. }
  21108. doThrow(errMsg);
  21109. }
  21110. }
  21111. var sourceList;
  21112. var upSourceList = [];
  21113. var upstreamSignList = [];
  21114. each(upMgrList, function (upMgr) {
  21115. upMgr.prepareSource();
  21116. var upSource = upMgr.getSource(fromTransformResult || 0);
  21117. var errMsg = '';
  21118. if (fromTransformResult != null && !upSource) {
  21119. if ("development" !== 'production') {
  21120. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21121. }
  21122. doThrow(errMsg);
  21123. }
  21124. upSourceList.push(upSource);
  21125. upstreamSignList.push(upMgr._getVersionSign());
  21126. });
  21127. if (transformOption) {
  21128. sourceList = applyDataTransform(transformOption, upSourceList, {
  21129. datasetIndex: datasetModel.componentIndex
  21130. });
  21131. } else if (fromTransformResult != null) {
  21132. sourceList = [cloneSourceShallow(upSourceList[0])];
  21133. }
  21134. return {
  21135. sourceList: sourceList,
  21136. upstreamSignList: upstreamSignList
  21137. };
  21138. };
  21139. SourceManager.prototype._isDirty = function () {
  21140. if (this._dirty) {
  21141. return true;
  21142. }
  21143. // All sourceList is from the some upstream.
  21144. var upSourceMgrList = this._getUpstreamSourceManagers();
  21145. for (var i = 0; i < upSourceMgrList.length; i++) {
  21146. var upSrcMgr = upSourceMgrList[i];
  21147. if (
  21148. // Consider the case that there is ancestor diry, call it recursively.
  21149. // The performance is probably not an issue because usually the chain is not long.
  21150. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21151. return true;
  21152. }
  21153. }
  21154. };
  21155. /**
  21156. * @param sourceIndex By default 0, means "main source".
  21157. * In most cases there is only one source.
  21158. */
  21159. SourceManager.prototype.getSource = function (sourceIndex) {
  21160. sourceIndex = sourceIndex || 0;
  21161. var source = this._sourceList[sourceIndex];
  21162. if (!source) {
  21163. // Series may share source instance with dataset.
  21164. var upSourceMgrList = this._getUpstreamSourceManagers();
  21165. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21166. }
  21167. return source;
  21168. };
  21169. /**
  21170. *
  21171. * Get a data store which can be shared across series.
  21172. * Only available for series.
  21173. *
  21174. * @param seriesDimRequest Dimensions that are generated in series.
  21175. * Should have been sorted by `storeDimIndex` asc.
  21176. */
  21177. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21178. if ("development" !== 'production') {
  21179. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21180. }
  21181. var schema = seriesDimRequest.makeStoreSchema();
  21182. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21183. };
  21184. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21185. // TODO Can use other sourceIndex?
  21186. var sourceIndex = 0;
  21187. var storeList = this._storeList;
  21188. var cachedStoreMap = storeList[sourceIndex];
  21189. if (!cachedStoreMap) {
  21190. cachedStoreMap = storeList[sourceIndex] = {};
  21191. }
  21192. var cachedStore = cachedStoreMap[sourceReadKey];
  21193. if (!cachedStore) {
  21194. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21195. if (isSeries(this._sourceHost) && upSourceMgr) {
  21196. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21197. } else {
  21198. cachedStore = new DataStore();
  21199. // Always create store from source of series.
  21200. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21201. }
  21202. cachedStoreMap[sourceReadKey] = cachedStore;
  21203. }
  21204. return cachedStore;
  21205. };
  21206. /**
  21207. * PENDING: Is it fast enough?
  21208. * If no upstream, return empty array.
  21209. */
  21210. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21211. // Always get the relationship from the raw option.
  21212. // Do not cache the link of the dependency graph, so that
  21213. // there is no need to update them when change happens.
  21214. var sourceHost = this._sourceHost;
  21215. if (isSeries(sourceHost)) {
  21216. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21217. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21218. } else {
  21219. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21220. return datasetModel.getSourceManager();
  21221. });
  21222. }
  21223. };
  21224. SourceManager.prototype._getSourceMetaRawOption = function () {
  21225. var sourceHost = this._sourceHost;
  21226. var seriesLayoutBy;
  21227. var sourceHeader;
  21228. var dimensions;
  21229. if (isSeries(sourceHost)) {
  21230. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21231. sourceHeader = sourceHost.get('sourceHeader', true);
  21232. dimensions = sourceHost.get('dimensions', true);
  21233. }
  21234. // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21235. else if (!this._getUpstreamSourceManagers().length) {
  21236. var model = sourceHost;
  21237. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21238. sourceHeader = model.get('sourceHeader', true);
  21239. dimensions = model.get('dimensions', true);
  21240. }
  21241. return {
  21242. seriesLayoutBy: seriesLayoutBy,
  21243. sourceHeader: sourceHeader,
  21244. dimensions: dimensions
  21245. };
  21246. };
  21247. return SourceManager;
  21248. }();
  21249. // Call this method after `super.init` and `super.mergeOption` to
  21250. // disable the transform merge, but do not disable transform clone from rawOption.
  21251. function disableTransformOptionMerge(datasetModel) {
  21252. var transformOption = datasetModel.option.transform;
  21253. transformOption && setAsPrimitive(datasetModel.option.transform);
  21254. }
  21255. function isSeries(sourceHost) {
  21256. // Avoid circular dependency with Series.ts
  21257. return sourceHost.mainType === 'series';
  21258. }
  21259. function doThrow(errMsg) {
  21260. throw new Error(errMsg);
  21261. }
  21262. // eslint-disable-next-line max-len
  21263. function createTooltipMarkup(type, option) {
  21264. option.type = type;
  21265. return option;
  21266. }
  21267. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  21268. var style = series.getData().getItemVisual(dataIndex, 'style');
  21269. var color = style[series.visualDrawType];
  21270. return convertToColorString(color);
  21271. }
  21272. function defaultSeriesFormatTooltip(opt) {
  21273. var series = opt.series;
  21274. var dataIndex = opt.dataIndex;
  21275. var multipleSeries = opt.multipleSeries;
  21276. var data = series.getData();
  21277. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  21278. var tooltipDimLen = tooltipDims.length;
  21279. var value = series.getRawValue(dataIndex);
  21280. var isValueArr = isArray(value);
  21281. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex);
  21282. // Complicated rule for pretty tooltip.
  21283. var inlineValue;
  21284. var inlineValueType;
  21285. var subBlocks;
  21286. var sortParam;
  21287. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  21288. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  21289. inlineValue = formatArrResult.inlineValues;
  21290. inlineValueType = formatArrResult.inlineValueTypes;
  21291. subBlocks = formatArrResult.blocks;
  21292. // Only support tooltip sort by the first inline value. It's enough in most cases.
  21293. sortParam = formatArrResult.inlineValues[0];
  21294. } else if (tooltipDimLen) {
  21295. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  21296. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  21297. inlineValueType = dimInfo.type;
  21298. } else {
  21299. sortParam = inlineValue = isValueArr ? value[0] : value;
  21300. }
  21301. // Do not show generated series name. It might not be readable.
  21302. var seriesNameSpecified = isNameSpecified(series);
  21303. var seriesName = seriesNameSpecified && series.name || '';
  21304. var itemName = data.getName(dataIndex);
  21305. var inlineName = multipleSeries ? seriesName : itemName;
  21306. return createTooltipMarkup('section', {
  21307. header: seriesName,
  21308. // When series name is not specified, do not show a header line with only '-'.
  21309. // This case always happens in tooltip.trigger: 'item'.
  21310. noHeader: multipleSeries || !seriesNameSpecified,
  21311. sortParam: sortParam,
  21312. blocks: [createTooltipMarkup('nameValue', {
  21313. markerType: 'item',
  21314. markerColor: markerColor,
  21315. // Do not mix display seriesName and itemName in one tooltip,
  21316. // which might confuses users.
  21317. name: inlineName,
  21318. // name dimension might be auto assigned, where the name might
  21319. // be not readable. So we check trim here.
  21320. noName: !trim(inlineName),
  21321. value: inlineValue,
  21322. valueType: inlineValueType,
  21323. dataIndex: dataIndex
  21324. })].concat(subBlocks || [])
  21325. });
  21326. }
  21327. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  21328. // check: category-no-encode-has-axis-data in dataset.html
  21329. var data = series.getData();
  21330. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  21331. var dimItem = data.getDimensionInfo(idx);
  21332. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21333. }, false);
  21334. var inlineValues = [];
  21335. var inlineValueTypes = [];
  21336. var blocks = [];
  21337. tooltipDims.length ? each(tooltipDims, function (dim) {
  21338. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21339. })
  21340. // By default, all dims is used on tooltip.
  21341. : each(value, setEachItem);
  21342. function setEachItem(val, dim) {
  21343. var dimInfo = data.getDimensionInfo(dim);
  21344. // If `dimInfo.tooltip` is not set, show tooltip.
  21345. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21346. return;
  21347. }
  21348. if (isValueMultipleLine) {
  21349. blocks.push(createTooltipMarkup('nameValue', {
  21350. markerType: 'subItem',
  21351. markerColor: colorStr,
  21352. name: dimInfo.displayName,
  21353. value: val,
  21354. valueType: dimInfo.type
  21355. }));
  21356. } else {
  21357. inlineValues.push(val);
  21358. inlineValueTypes.push(dimInfo.type);
  21359. }
  21360. }
  21361. return {
  21362. inlineValues: inlineValues,
  21363. inlineValueTypes: inlineValueTypes,
  21364. blocks: blocks
  21365. };
  21366. }
  21367. var inner$1 = makeInner();
  21368. function getSelectionKey(data, dataIndex) {
  21369. return data.getName(dataIndex) || data.getId(dataIndex);
  21370. }
  21371. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  21372. var SeriesModel = /** @class */function (_super) {
  21373. __extends(SeriesModel, _super);
  21374. function SeriesModel() {
  21375. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  21376. // the class members must not be initialized in constructor or declaration place.
  21377. // Otherwise there is bad case:
  21378. // class A {xxx = 1;}
  21379. // enableClassExtend(A);
  21380. // class B extends A {}
  21381. // var C = B.extend({xxx: 5});
  21382. // var c = new C();
  21383. // console.log(c.xxx); // expect 5 but always 1.
  21384. var _this = _super !== null && _super.apply(this, arguments) || this;
  21385. // ---------------------------------------
  21386. // Props about data selection
  21387. // ---------------------------------------
  21388. _this._selectedDataIndicesMap = {};
  21389. return _this;
  21390. }
  21391. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  21392. this.seriesIndex = this.componentIndex;
  21393. this.dataTask = createTask({
  21394. count: dataTaskCount,
  21395. reset: dataTaskReset
  21396. });
  21397. this.dataTask.context = {
  21398. model: this
  21399. };
  21400. this.mergeDefaultAndTheme(option, ecModel);
  21401. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  21402. sourceManager.prepareSource();
  21403. var data = this.getInitialData(option, ecModel);
  21404. wrapData(data, this);
  21405. this.dataTask.context.data = data;
  21406. if ("development" !== 'production') {
  21407. assert(data, 'getInitialData returned invalid data.');
  21408. }
  21409. inner$1(this).dataBeforeProcessed = data;
  21410. // If we reverse the order (make data firstly, and then make
  21411. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21412. // cause data.graph.data !== data when using
  21413. // module:echarts/data/Graph or module:echarts/data/Tree.
  21414. // See module:echarts/data/helper/linkSeriesData
  21415. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21416. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21417. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21418. // Call `seriesModel.getRawData()` instead.
  21419. // this.restoreData();
  21420. autoSeriesName(this);
  21421. this._initSelectedMapFromData(data);
  21422. };
  21423. /**
  21424. * Util for merge default and theme to option
  21425. */
  21426. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  21427. var layoutMode = fetchLayoutMode(this);
  21428. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  21429. // Backward compat: using subType on theme.
  21430. // But if name duplicate between series subType
  21431. // (for example: parallel) add component mainType,
  21432. // add suffix 'Series'.
  21433. var themeSubType = this.subType;
  21434. if (ComponentModel.hasClass(themeSubType)) {
  21435. themeSubType += 'Series';
  21436. }
  21437. merge(option, ecModel.getTheme().get(this.subType));
  21438. merge(option, this.getDefaultOption());
  21439. // Default label emphasis `show`
  21440. defaultEmphasis(option, 'label', ['show']);
  21441. this.fillDataTextStyle(option.data);
  21442. if (layoutMode) {
  21443. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21444. }
  21445. };
  21446. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  21447. // this.settingTask.dirty();
  21448. newSeriesOption = merge(this.option, newSeriesOption, true);
  21449. this.fillDataTextStyle(newSeriesOption.data);
  21450. var layoutMode = fetchLayoutMode(this);
  21451. if (layoutMode) {
  21452. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21453. }
  21454. var sourceManager = inner$1(this).sourceManager;
  21455. sourceManager.dirty();
  21456. sourceManager.prepareSource();
  21457. var data = this.getInitialData(newSeriesOption, ecModel);
  21458. wrapData(data, this);
  21459. this.dataTask.dirty();
  21460. this.dataTask.context.data = data;
  21461. inner$1(this).dataBeforeProcessed = data;
  21462. autoSeriesName(this);
  21463. this._initSelectedMapFromData(data);
  21464. };
  21465. SeriesModel.prototype.fillDataTextStyle = function (data) {
  21466. // Default data label emphasis `show`
  21467. // FIXME Tree structure data ?
  21468. // FIXME Performance ?
  21469. if (data && !isTypedArray(data)) {
  21470. var props = ['show'];
  21471. for (var i = 0; i < data.length; i++) {
  21472. if (data[i] && data[i].label) {
  21473. defaultEmphasis(data[i], 'label', props);
  21474. }
  21475. }
  21476. }
  21477. };
  21478. /**
  21479. * Init a data structure from data related option in series
  21480. * Must be overridden.
  21481. */
  21482. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  21483. return;
  21484. };
  21485. /**
  21486. * Append data to list
  21487. */
  21488. SeriesModel.prototype.appendData = function (params) {
  21489. // FIXME ???
  21490. // (1) If data from dataset, forbidden append.
  21491. // (2) support append data of dataset.
  21492. var data = this.getRawData();
  21493. data.appendData(params.data);
  21494. };
  21495. /**
  21496. * Consider some method like `filter`, `map` need make new data,
  21497. * We should make sure that `seriesModel.getData()` get correct
  21498. * data in the stream procedure. So we fetch data from upstream
  21499. * each time `task.perform` called.
  21500. */
  21501. SeriesModel.prototype.getData = function (dataType) {
  21502. var task = getCurrentTask(this);
  21503. if (task) {
  21504. var data = task.context.data;
  21505. return dataType == null || !data.getLinkedData ? data : data.getLinkedData(dataType);
  21506. } else {
  21507. // When series is not alive (that may happen when click toolbox
  21508. // restore or setOption with not merge mode), series data may
  21509. // be still need to judge animation or something when graphic
  21510. // elements want to know whether fade out.
  21511. return inner$1(this).data;
  21512. }
  21513. };
  21514. SeriesModel.prototype.getAllData = function () {
  21515. var mainData = this.getData();
  21516. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  21517. data: mainData
  21518. }];
  21519. };
  21520. SeriesModel.prototype.setData = function (data) {
  21521. var task = getCurrentTask(this);
  21522. if (task) {
  21523. var context = task.context;
  21524. // Consider case: filter, data sample.
  21525. // FIXME:TS never used, so comment it
  21526. // if (context.data !== data && task.modifyOutputEnd) {
  21527. // task.setOutputEnd(data.count());
  21528. // }
  21529. context.outputData = data;
  21530. // Caution: setData should update context.data,
  21531. // Because getData may be called multiply in a
  21532. // single stage and expect to get the data just
  21533. // set. (For example, AxisProxy, x y both call
  21534. // getData and setDate sequentially).
  21535. // So the context.data should be fetched from
  21536. // upstream each time when a stage starts to be
  21537. // performed.
  21538. if (task !== this.dataTask) {
  21539. context.data = data;
  21540. }
  21541. }
  21542. inner$1(this).data = data;
  21543. };
  21544. SeriesModel.prototype.getEncode = function () {
  21545. var encode = this.get('encode', true);
  21546. if (encode) {
  21547. return createHashMap(encode);
  21548. }
  21549. };
  21550. SeriesModel.prototype.getSourceManager = function () {
  21551. return inner$1(this).sourceManager;
  21552. };
  21553. SeriesModel.prototype.getSource = function () {
  21554. return this.getSourceManager().getSource();
  21555. };
  21556. /**
  21557. * Get data before processed
  21558. */
  21559. SeriesModel.prototype.getRawData = function () {
  21560. return inner$1(this).dataBeforeProcessed;
  21561. };
  21562. SeriesModel.prototype.getColorBy = function () {
  21563. var colorBy = this.get('colorBy');
  21564. return colorBy || 'series';
  21565. };
  21566. SeriesModel.prototype.isColorBySeries = function () {
  21567. return this.getColorBy() === 'series';
  21568. };
  21569. /**
  21570. * Get base axis if has coordinate system and has axis.
  21571. * By default use coordSys.getBaseAxis();
  21572. * Can be overridden for some chart.
  21573. * @return {type} description
  21574. */
  21575. SeriesModel.prototype.getBaseAxis = function () {
  21576. var coordSys = this.coordinateSystem;
  21577. // @ts-ignore
  21578. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21579. };
  21580. /**
  21581. * Default tooltip formatter
  21582. *
  21583. * @param dataIndex
  21584. * @param multipleSeries
  21585. * @param dataType
  21586. * @param renderMode valid values: 'html'(by default) and 'richText'.
  21587. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21588. * string is used as DOM HTML content.
  21589. * 'richText' is used for rendering tooltip in rich text form, for those where
  21590. * DOM operation is not supported.
  21591. * @return formatted tooltip with `html` and `markers`
  21592. * Notice: The override method can also return string
  21593. */
  21594. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  21595. return defaultSeriesFormatTooltip({
  21596. series: this,
  21597. dataIndex: dataIndex,
  21598. multipleSeries: multipleSeries
  21599. });
  21600. };
  21601. SeriesModel.prototype.isAnimationEnabled = function () {
  21602. var ecModel = this.ecModel;
  21603. // Disable animation if using echarts in node but not give ssr flag.
  21604. // In ssr mode, renderToString will generate svg with css animation.
  21605. if (env.node && !(ecModel && ecModel.ssr)) {
  21606. return false;
  21607. }
  21608. var animationEnabled = this.getShallow('animation');
  21609. if (animationEnabled) {
  21610. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21611. animationEnabled = false;
  21612. }
  21613. }
  21614. return !!animationEnabled;
  21615. };
  21616. SeriesModel.prototype.restoreData = function () {
  21617. this.dataTask.dirty();
  21618. };
  21619. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  21620. var ecModel = this.ecModel;
  21621. // PENDING
  21622. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  21623. if (!color) {
  21624. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21625. }
  21626. return color;
  21627. };
  21628. /**
  21629. * Use `data.mapDimensionsAll(coordDim)` instead.
  21630. * @deprecated
  21631. */
  21632. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  21633. return this.getRawData().mapDimensionsAll(coordDim);
  21634. };
  21635. /**
  21636. * Get progressive rendering count each step
  21637. */
  21638. SeriesModel.prototype.getProgressive = function () {
  21639. return this.get('progressive');
  21640. };
  21641. /**
  21642. * Get progressive rendering count each step
  21643. */
  21644. SeriesModel.prototype.getProgressiveThreshold = function () {
  21645. return this.get('progressiveThreshold');
  21646. };
  21647. // PENGING If selectedMode is null ?
  21648. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  21649. this._innerSelect(this.getData(dataType), innerDataIndices);
  21650. };
  21651. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  21652. var selectedMap = this.option.selectedMap;
  21653. if (!selectedMap) {
  21654. return;
  21655. }
  21656. var selectedMode = this.option.selectedMode;
  21657. var data = this.getData(dataType);
  21658. if (selectedMode === 'series' || selectedMap === 'all') {
  21659. this.option.selectedMap = {};
  21660. this._selectedDataIndicesMap = {};
  21661. return;
  21662. }
  21663. for (var i = 0; i < innerDataIndices.length; i++) {
  21664. var dataIndex = innerDataIndices[i];
  21665. var nameOrId = getSelectionKey(data, dataIndex);
  21666. selectedMap[nameOrId] = false;
  21667. this._selectedDataIndicesMap[nameOrId] = -1;
  21668. }
  21669. };
  21670. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  21671. var tmpArr = [];
  21672. for (var i = 0; i < innerDataIndices.length; i++) {
  21673. tmpArr[0] = innerDataIndices[i];
  21674. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  21675. }
  21676. };
  21677. SeriesModel.prototype.getSelectedDataIndices = function () {
  21678. if (this.option.selectedMap === 'all') {
  21679. return [].slice.call(this.getData().getIndices());
  21680. }
  21681. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  21682. var nameOrIds = keys(selectedDataIndicesMap);
  21683. var dataIndices = [];
  21684. for (var i = 0; i < nameOrIds.length; i++) {
  21685. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  21686. if (dataIndex >= 0) {
  21687. dataIndices.push(dataIndex);
  21688. }
  21689. }
  21690. return dataIndices;
  21691. };
  21692. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  21693. var selectedMap = this.option.selectedMap;
  21694. if (!selectedMap) {
  21695. return false;
  21696. }
  21697. var data = this.getData(dataType);
  21698. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  21699. };
  21700. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  21701. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  21702. return true;
  21703. }
  21704. var universalTransitionOpt = this.option.universalTransition;
  21705. // Quick reject
  21706. if (!universalTransitionOpt) {
  21707. return false;
  21708. }
  21709. if (universalTransitionOpt === true) {
  21710. return true;
  21711. }
  21712. // Can be simply 'universalTransition: true'
  21713. return universalTransitionOpt && universalTransitionOpt.enabled;
  21714. };
  21715. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  21716. var _a, _b;
  21717. var option = this.option;
  21718. var selectedMode = option.selectedMode;
  21719. var len = innerDataIndices.length;
  21720. if (!selectedMode || !len) {
  21721. return;
  21722. }
  21723. if (selectedMode === 'series') {
  21724. option.selectedMap = 'all';
  21725. } else if (selectedMode === 'multiple') {
  21726. if (!isObject(option.selectedMap)) {
  21727. option.selectedMap = {};
  21728. }
  21729. var selectedMap = option.selectedMap;
  21730. for (var i = 0; i < len; i++) {
  21731. var dataIndex = innerDataIndices[i];
  21732. // TODO different types of data share same object.
  21733. var nameOrId = getSelectionKey(data, dataIndex);
  21734. selectedMap[nameOrId] = true;
  21735. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  21736. }
  21737. } else if (selectedMode === 'single' || selectedMode === true) {
  21738. var lastDataIndex = innerDataIndices[len - 1];
  21739. var nameOrId = getSelectionKey(data, lastDataIndex);
  21740. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  21741. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  21742. }
  21743. };
  21744. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  21745. // Ignore select info in data if selectedMap exists.
  21746. // NOTE It's only for legacy usage. edge data is not supported.
  21747. if (this.option.selectedMap) {
  21748. return;
  21749. }
  21750. var dataIndices = [];
  21751. if (data.hasItemOption) {
  21752. data.each(function (idx) {
  21753. var rawItem = data.getRawDataItem(idx);
  21754. if (rawItem && rawItem.selected) {
  21755. dataIndices.push(idx);
  21756. }
  21757. });
  21758. }
  21759. if (dataIndices.length > 0) {
  21760. this._innerSelect(data, dataIndices);
  21761. }
  21762. };
  21763. // /**
  21764. // * @see {module:echarts/stream/Scheduler}
  21765. // */
  21766. // abstract pipeTask: null
  21767. SeriesModel.registerClass = function (clz) {
  21768. return ComponentModel.registerClass(clz);
  21769. };
  21770. SeriesModel.protoInitialize = function () {
  21771. var proto = SeriesModel.prototype;
  21772. proto.type = 'series.__base__';
  21773. proto.seriesIndex = 0;
  21774. proto.ignoreStyleOnData = false;
  21775. proto.hasSymbolVisual = false;
  21776. proto.defaultSymbol = 'circle';
  21777. // Make sure the values can be accessed!
  21778. proto.visualStyleAccessPath = 'itemStyle';
  21779. proto.visualDrawType = 'fill';
  21780. }();
  21781. return SeriesModel;
  21782. }(ComponentModel);
  21783. mixin(SeriesModel, DataFormatMixin);
  21784. mixin(SeriesModel, PaletteMixin);
  21785. mountExtend(SeriesModel, ComponentModel);
  21786. /**
  21787. * MUST be called after `prepareSource` called
  21788. * Here we need to make auto series, especially for auto legend. But we
  21789. * do not modify series.name in option to avoid side effects.
  21790. */
  21791. function autoSeriesName(seriesModel) {
  21792. // User specified name has higher priority, otherwise it may cause
  21793. // series can not be queried unexpectedly.
  21794. var name = seriesModel.name;
  21795. if (!isNameSpecified(seriesModel)) {
  21796. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21797. }
  21798. }
  21799. function getSeriesAutoName(seriesModel) {
  21800. var data = seriesModel.getRawData();
  21801. var dataDims = data.mapDimensionsAll('seriesName');
  21802. var nameArr = [];
  21803. each(dataDims, function (dataDim) {
  21804. var dimInfo = data.getDimensionInfo(dataDim);
  21805. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21806. });
  21807. return nameArr.join(' ');
  21808. }
  21809. function dataTaskCount(context) {
  21810. return context.model.getRawData().count();
  21811. }
  21812. function dataTaskReset(context) {
  21813. var seriesModel = context.model;
  21814. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21815. return dataTaskProgress;
  21816. }
  21817. function dataTaskProgress(param, context) {
  21818. // Avoid repeat cloneShallow when data just created in reset.
  21819. if (context.outputData && param.end > context.outputData.count()) {
  21820. context.model.getRawData().cloneShallow(context.outputData);
  21821. }
  21822. }
  21823. // TODO refactor
  21824. function wrapData(data, seriesModel) {
  21825. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  21826. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  21827. });
  21828. }
  21829. function onDataChange(seriesModel, newList) {
  21830. var task = getCurrentTask(seriesModel);
  21831. if (task) {
  21832. // Consider case: filter, selectRange
  21833. task.setOutputEnd((newList || this).count());
  21834. }
  21835. return newList;
  21836. }
  21837. function getCurrentTask(seriesModel) {
  21838. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21839. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21840. if (pipeline) {
  21841. // When pipline finished, the currrentTask keep the last
  21842. // task (renderTask).
  21843. var task = pipeline.currentTask;
  21844. if (task) {
  21845. var agentStubMap = task.agentStubMap;
  21846. if (agentStubMap) {
  21847. task = agentStubMap.get(seriesModel.uid);
  21848. }
  21849. }
  21850. return task;
  21851. }
  21852. }
  21853. var ComponentView = /** @class */function () {
  21854. function ComponentView() {
  21855. this.group = new Group();
  21856. this.uid = getUID('viewComponent');
  21857. }
  21858. ComponentView.prototype.init = function (ecModel, api) {};
  21859. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  21860. ComponentView.prototype.dispose = function (ecModel, api) {};
  21861. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {
  21862. // Do nothing;
  21863. };
  21864. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {
  21865. // Do nothing;
  21866. };
  21867. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {
  21868. // Do nothing;
  21869. };
  21870. /**
  21871. * Hook for toggle blur target series.
  21872. * Can be used in marker for blur or leave blur the markers
  21873. */
  21874. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {
  21875. // Do nothing;
  21876. };
  21877. /**
  21878. * Traverse the new rendered elements.
  21879. *
  21880. * It will traverse the new added element in progressive rendering.
  21881. * And traverse all in normal rendering.
  21882. */
  21883. ComponentView.prototype.eachRendered = function (cb) {
  21884. var group = this.group;
  21885. if (group) {
  21886. group.traverse(cb);
  21887. }
  21888. };
  21889. return ComponentView;
  21890. }();
  21891. enableClassExtend(ComponentView);
  21892. enableClassManagement(ComponentView);
  21893. /**
  21894. * @return {string} If large mode changed, return string 'reset';
  21895. */
  21896. function createRenderPlanner() {
  21897. var inner = makeInner();
  21898. return function (seriesModel) {
  21899. var fields = inner(seriesModel);
  21900. var pipelineContext = seriesModel.pipelineContext;
  21901. var originalLarge = !!fields.large;
  21902. var originalProgressive = !!fields.progressiveRender;
  21903. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  21904. // exists. See #11611 . Probably we need to modify this structure, see the comment
  21905. // on `performRawSeries` in `Schedular.js`.
  21906. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  21907. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  21908. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  21909. };
  21910. }
  21911. var inner$2 = makeInner();
  21912. var renderPlanner = createRenderPlanner();
  21913. var ChartView = /** @class */function () {
  21914. function ChartView() {
  21915. this.group = new Group();
  21916. this.uid = getUID('viewChart');
  21917. this.renderTask = createTask({
  21918. plan: renderTaskPlan,
  21919. reset: renderTaskReset
  21920. });
  21921. this.renderTask.context = {
  21922. view: this
  21923. };
  21924. }
  21925. ChartView.prototype.init = function (ecModel, api) {};
  21926. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  21927. if ("development" !== 'production') {
  21928. throw new Error('render method must been implemented');
  21929. }
  21930. };
  21931. /**
  21932. * Highlight series or specified data item.
  21933. */
  21934. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  21935. var data = seriesModel.getData(payload && payload.dataType);
  21936. if (!data) {
  21937. if ("development" !== 'production') {
  21938. error("Unknown dataType " + payload.dataType);
  21939. }
  21940. return;
  21941. }
  21942. toggleHighlight(data, payload, 'emphasis');
  21943. };
  21944. /**
  21945. * Downplay series or specified data item.
  21946. */
  21947. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  21948. var data = seriesModel.getData(payload && payload.dataType);
  21949. if (!data) {
  21950. if ("development" !== 'production') {
  21951. error("Unknown dataType " + payload.dataType);
  21952. }
  21953. return;
  21954. }
  21955. toggleHighlight(data, payload, 'normal');
  21956. };
  21957. /**
  21958. * Remove self.
  21959. */
  21960. ChartView.prototype.remove = function (ecModel, api) {
  21961. this.group.removeAll();
  21962. };
  21963. /**
  21964. * Dispose self.
  21965. */
  21966. ChartView.prototype.dispose = function (ecModel, api) {};
  21967. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  21968. this.render(seriesModel, ecModel, api, payload);
  21969. };
  21970. // FIXME never used?
  21971. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  21972. this.render(seriesModel, ecModel, api, payload);
  21973. };
  21974. // FIXME never used?
  21975. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  21976. this.render(seriesModel, ecModel, api, payload);
  21977. };
  21978. /**
  21979. * Traverse the new rendered elements.
  21980. *
  21981. * It will traverse the new added element in progressive rendering.
  21982. * And traverse all in normal rendering.
  21983. */
  21984. ChartView.prototype.eachRendered = function (cb) {
  21985. traverseElements(this.group, cb);
  21986. };
  21987. ChartView.markUpdateMethod = function (payload, methodName) {
  21988. inner$2(payload).updateMethod = methodName;
  21989. };
  21990. ChartView.protoInitialize = function () {
  21991. var proto = ChartView.prototype;
  21992. proto.type = 'chart';
  21993. }();
  21994. return ChartView;
  21995. }();
  21996. /**
  21997. * Set state of single element
  21998. */
  21999. function elSetState(el, state, highlightDigit) {
  22000. if (el && isHighDownDispatcher(el)) {
  22001. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22002. }
  22003. }
  22004. function toggleHighlight(data, payload, state) {
  22005. var dataIndex = queryDataIndex(data, payload);
  22006. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22007. if (dataIndex != null) {
  22008. each(normalizeToArray(dataIndex), function (dataIdx) {
  22009. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22010. });
  22011. } else {
  22012. data.eachItemGraphicEl(function (el) {
  22013. elSetState(el, state, highlightDigit);
  22014. });
  22015. }
  22016. }
  22017. enableClassExtend(ChartView, ['dispose']);
  22018. enableClassManagement(ChartView);
  22019. function renderTaskPlan(context) {
  22020. return renderPlanner(context.model);
  22021. }
  22022. function renderTaskReset(context) {
  22023. var seriesModel = context.model;
  22024. var ecModel = context.ecModel;
  22025. var api = context.api;
  22026. var payload = context.payload;
  22027. // FIXME: remove updateView updateVisual
  22028. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22029. var view = context.view;
  22030. var updateMethod = payload && inner$2(payload).updateMethod;
  22031. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod
  22032. // `appendData` is also supported when data amount
  22033. // is less than progressive threshold.
  22034. : 'render';
  22035. if (methodName !== 'render') {
  22036. view[methodName](seriesModel, ecModel, api, payload);
  22037. }
  22038. return progressMethodMap[methodName];
  22039. }
  22040. var progressMethodMap = {
  22041. incrementalPrepareRender: {
  22042. progress: function (params, context) {
  22043. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22044. }
  22045. },
  22046. render: {
  22047. // Put view.render in `progress` to support appendData. But in this case
  22048. // view.render should not be called in reset, otherwise it will be called
  22049. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22050. // in any cases.
  22051. forceFirstProgress: true,
  22052. progress: function (params, context) {
  22053. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22054. }
  22055. }
  22056. };
  22057. /**
  22058. * @public
  22059. * @param {(Function)} fn
  22060. * @param {number} [delay=0] Unit: ms.
  22061. * @param {boolean} [debounce=false]
  22062. * true: If call interval less than `delay`, only the last call works.
  22063. * false: If call interval less than `delay, call works on fixed rate.
  22064. * @return {(Function)} throttled fn.
  22065. */
  22066. function throttle(fn, delay, debounce) {
  22067. var currCall;
  22068. var lastCall = 0;
  22069. var lastExec = 0;
  22070. var timer = null;
  22071. var diff;
  22072. var scope;
  22073. var args;
  22074. var debounceNextCall;
  22075. delay = delay || 0;
  22076. function exec() {
  22077. lastExec = new Date().getTime();
  22078. timer = null;
  22079. fn.apply(scope, args || []);
  22080. }
  22081. var cb = function () {
  22082. var cbArgs = [];
  22083. for (var _i = 0; _i < arguments.length; _i++) {
  22084. cbArgs[_i] = arguments[_i];
  22085. }
  22086. currCall = new Date().getTime();
  22087. scope = this;
  22088. args = cbArgs;
  22089. var thisDelay = debounceNextCall || delay;
  22090. var thisDebounce = debounceNextCall || debounce;
  22091. debounceNextCall = null;
  22092. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22093. clearTimeout(timer);
  22094. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22095. // than a new call of `cb`, that is, preserving the command order. Consider
  22096. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22097. // happens, either the `exec` is called dierectly, or the call is delayed.
  22098. // But the delayed call should never be later than next call of `cb`. Under
  22099. // this assurance, we can simply update view state each time `dispatchAction`
  22100. // triggered by user roaming, but not need to add extra code to avoid the
  22101. // state being "rolled-back".
  22102. if (thisDebounce) {
  22103. timer = setTimeout(exec, thisDelay);
  22104. } else {
  22105. if (diff >= 0) {
  22106. exec();
  22107. } else {
  22108. timer = setTimeout(exec, -diff);
  22109. }
  22110. }
  22111. lastCall = currCall;
  22112. };
  22113. /**
  22114. * Clear throttle.
  22115. * @public
  22116. */
  22117. cb.clear = function () {
  22118. if (timer) {
  22119. clearTimeout(timer);
  22120. timer = null;
  22121. }
  22122. };
  22123. /**
  22124. * Enable debounce once.
  22125. */
  22126. cb.debounceNextCall = function (debounceDelay) {
  22127. debounceNextCall = debounceDelay;
  22128. };
  22129. return cb;
  22130. }
  22131. var inner$3 = makeInner();
  22132. var defaultStyleMappers = {
  22133. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  22134. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  22135. };
  22136. var defaultColorKey = {
  22137. lineStyle: 'stroke',
  22138. itemStyle: 'fill'
  22139. };
  22140. function getStyleMapper(seriesModel, stylePath) {
  22141. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  22142. if (!styleMapper) {
  22143. console.warn("Unknown style type '" + stylePath + "'.");
  22144. return defaultStyleMappers.itemStyle;
  22145. }
  22146. return styleMapper;
  22147. }
  22148. function getDefaultColorKey(seriesModel, stylePath) {
  22149. // return defaultColorKey[stylePath] ||
  22150. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  22151. if (!colorKey) {
  22152. console.warn("Unknown style type '" + stylePath + "'.");
  22153. return 'fill';
  22154. }
  22155. return colorKey;
  22156. }
  22157. var seriesStyleTask = {
  22158. createOnAllSeries: true,
  22159. performRawSeries: true,
  22160. reset: function (seriesModel, ecModel) {
  22161. var data = seriesModel.getData();
  22162. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  22163. // Set in itemStyle
  22164. var styleModel = seriesModel.getModel(stylePath);
  22165. var getStyle = getStyleMapper(seriesModel, stylePath);
  22166. var globalStyle = getStyle(styleModel);
  22167. var decalOption = styleModel.getShallow('decal');
  22168. if (decalOption) {
  22169. data.setVisual('decal', decalOption);
  22170. decalOption.dirty = true;
  22171. }
  22172. // TODO
  22173. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22174. var color = globalStyle[colorKey];
  22175. // TODO style callback
  22176. var colorCallback = isFunction(color) ? color : null;
  22177. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto';
  22178. // Get from color palette by default.
  22179. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  22180. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  22181. // make it effect palette. Because some scenarios users need to make some series
  22182. // transparent or as background, which should better not effect the palette.
  22183. var colorPalette = seriesModel.getColorFromPalette(
  22184. // TODO series count changed.
  22185. seriesModel.name, null, ecModel.getSeriesCount());
  22186. if (!globalStyle[colorKey]) {
  22187. globalStyle[colorKey] = colorPalette;
  22188. data.setVisual('colorFromPalette', true);
  22189. }
  22190. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  22191. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  22192. }
  22193. data.setVisual('style', globalStyle);
  22194. data.setVisual('drawType', colorKey);
  22195. // Only visible series has each data be visual encoded
  22196. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  22197. data.setVisual('colorFromPalette', false);
  22198. return {
  22199. dataEach: function (data, idx) {
  22200. var dataParams = seriesModel.getDataParams(idx);
  22201. var itemStyle = extend({}, globalStyle);
  22202. itemStyle[colorKey] = colorCallback(dataParams);
  22203. data.setItemVisual(idx, 'style', itemStyle);
  22204. }
  22205. };
  22206. }
  22207. }
  22208. };
  22209. var sharedModel = new Model();
  22210. var dataStyleTask = {
  22211. createOnAllSeries: true,
  22212. performRawSeries: true,
  22213. reset: function (seriesModel, ecModel) {
  22214. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  22215. return;
  22216. }
  22217. var data = seriesModel.getData();
  22218. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  22219. // Set in itemStyle
  22220. var getStyle = getStyleMapper(seriesModel, stylePath);
  22221. var colorKey = data.getVisual('drawType');
  22222. return {
  22223. dataEach: data.hasItemOption ? function (data, idx) {
  22224. // Not use getItemModel for performance considuration
  22225. var rawItem = data.getRawDataItem(idx);
  22226. if (rawItem && rawItem[stylePath]) {
  22227. sharedModel.option = rawItem[stylePath];
  22228. var style = getStyle(sharedModel);
  22229. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  22230. extend(existsStyle, style);
  22231. if (sharedModel.option.decal) {
  22232. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  22233. sharedModel.option.decal.dirty = true;
  22234. }
  22235. if (colorKey in style) {
  22236. data.setItemVisual(idx, 'colorFromPalette', false);
  22237. }
  22238. }
  22239. } : null
  22240. };
  22241. }
  22242. };
  22243. // Pick color from palette for the data which has not been set with color yet.
  22244. // Note: do not support stream rendering. No such cases yet.
  22245. var dataColorPaletteTask = {
  22246. performRawSeries: true,
  22247. overallReset: function (ecModel) {
  22248. // Each type of series uses one scope.
  22249. // Pie and funnel are using different scopes.
  22250. var paletteScopeGroupByType = createHashMap();
  22251. ecModel.eachSeries(function (seriesModel) {
  22252. var colorBy = seriesModel.getColorBy();
  22253. if (seriesModel.isColorBySeries()) {
  22254. return;
  22255. }
  22256. var key = seriesModel.type + '-' + colorBy;
  22257. var colorScope = paletteScopeGroupByType.get(key);
  22258. if (!colorScope) {
  22259. colorScope = {};
  22260. paletteScopeGroupByType.set(key, colorScope);
  22261. }
  22262. inner$3(seriesModel).scope = colorScope;
  22263. });
  22264. ecModel.eachSeries(function (seriesModel) {
  22265. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  22266. return;
  22267. }
  22268. var dataAll = seriesModel.getRawData();
  22269. var idxMap = {};
  22270. var data = seriesModel.getData();
  22271. var colorScope = inner$3(seriesModel).scope;
  22272. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  22273. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22274. data.each(function (idx) {
  22275. var rawIdx = data.getRawIndex(idx);
  22276. idxMap[rawIdx] = idx;
  22277. });
  22278. // Iterate on data before filtered. To make sure color from palette can be
  22279. // Consistent when toggling legend.
  22280. dataAll.each(function (rawIdx) {
  22281. var idx = idxMap[rawIdx];
  22282. var fromPalette = data.getItemVisual(idx, 'colorFromPalette');
  22283. // Get color from palette for each data only when the color is inherited from series color, which is
  22284. // also picked from color palette. So following situation is not in the case:
  22285. // 1. series.itemStyle.color is set
  22286. // 2. color is encoded by visualMap
  22287. if (fromPalette) {
  22288. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  22289. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  22290. var dataCount = dataAll.count();
  22291. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  22292. }
  22293. });
  22294. });
  22295. }
  22296. };
  22297. var PI$3 = Math.PI;
  22298. /**
  22299. * @param {module:echarts/ExtensionAPI} api
  22300. * @param {Object} [opts]
  22301. * @param {string} [opts.text]
  22302. * @param {string} [opts.color]
  22303. * @param {string} [opts.textColor]
  22304. * @return {module:zrender/Element}
  22305. */
  22306. function defaultLoading(api, opts) {
  22307. opts = opts || {};
  22308. defaults(opts, {
  22309. text: 'loading',
  22310. textColor: '#000',
  22311. fontSize: 12,
  22312. fontWeight: 'normal',
  22313. fontStyle: 'normal',
  22314. fontFamily: 'sans-serif',
  22315. maskColor: 'rgba(255, 255, 255, 0.8)',
  22316. showSpinner: true,
  22317. color: '#5470c6',
  22318. spinnerRadius: 10,
  22319. lineWidth: 5,
  22320. zlevel: 0
  22321. });
  22322. var group = new Group();
  22323. var mask = new Rect({
  22324. style: {
  22325. fill: opts.maskColor
  22326. },
  22327. zlevel: opts.zlevel,
  22328. z: 10000
  22329. });
  22330. group.add(mask);
  22331. var textContent = new ZRText({
  22332. style: {
  22333. text: opts.text,
  22334. fill: opts.textColor,
  22335. fontSize: opts.fontSize,
  22336. fontWeight: opts.fontWeight,
  22337. fontStyle: opts.fontStyle,
  22338. fontFamily: opts.fontFamily
  22339. },
  22340. zlevel: opts.zlevel,
  22341. z: 10001
  22342. });
  22343. var labelRect = new Rect({
  22344. style: {
  22345. fill: 'none'
  22346. },
  22347. textContent: textContent,
  22348. textConfig: {
  22349. position: 'right',
  22350. distance: 10
  22351. },
  22352. zlevel: opts.zlevel,
  22353. z: 10001
  22354. });
  22355. group.add(labelRect);
  22356. var arc;
  22357. if (opts.showSpinner) {
  22358. arc = new Arc({
  22359. shape: {
  22360. startAngle: -PI$3 / 2,
  22361. endAngle: -PI$3 / 2 + 0.1,
  22362. r: opts.spinnerRadius
  22363. },
  22364. style: {
  22365. stroke: opts.color,
  22366. lineCap: 'round',
  22367. lineWidth: opts.lineWidth
  22368. },
  22369. zlevel: opts.zlevel,
  22370. z: 10001
  22371. });
  22372. arc.animateShape(true).when(1000, {
  22373. endAngle: PI$3 * 3 / 2
  22374. }).start('circularInOut');
  22375. arc.animateShape(true).when(1000, {
  22376. startAngle: PI$3 * 3 / 2
  22377. }).delay(300).start('circularInOut');
  22378. group.add(arc);
  22379. }
  22380. // Inject resize
  22381. group.resize = function () {
  22382. var textWidth = textContent.getBoundingRect().width;
  22383. var r = opts.showSpinner ? opts.spinnerRadius : 0;
  22384. // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  22385. // textDistance needs to be calculated when both animation and text exist
  22386. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2)
  22387. // only show the text
  22388. + (opts.showSpinner ? 0 : textWidth / 2)
  22389. // only show the spinner
  22390. + (textWidth ? 0 : r);
  22391. var cy = api.getHeight() / 2;
  22392. opts.showSpinner && arc.setShape({
  22393. cx: cx,
  22394. cy: cy
  22395. });
  22396. labelRect.setShape({
  22397. x: cx - r,
  22398. y: cy - r,
  22399. width: r * 2,
  22400. height: r * 2
  22401. });
  22402. mask.setShape({
  22403. x: 0,
  22404. y: 0,
  22405. width: api.getWidth(),
  22406. height: api.getHeight()
  22407. });
  22408. };
  22409. group.resize();
  22410. return group;
  22411. }
  22412. var Scheduler = /** @class */function () {
  22413. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22414. // key: handlerUID
  22415. this._stageTaskMap = createHashMap();
  22416. this.ecInstance = ecInstance;
  22417. this.api = api;
  22418. // Fix current processors in case that in some rear cases that
  22419. // processors might be registered after echarts instance created.
  22420. // Register processors incrementally for a echarts instance is
  22421. // not supported by this stream architecture.
  22422. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22423. visualHandlers = this._visualHandlers = visualHandlers.slice();
  22424. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22425. }
  22426. Scheduler.prototype.restoreData = function (ecModel, payload) {
  22427. // TODO: Only restore needed series and components, but not all components.
  22428. // Currently `restoreData` of all of the series and component will be called.
  22429. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22430. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22431. // and some components like coordinate system, axes, dataZoom, visualMap only
  22432. // need their target series refresh.
  22433. // (1) If we are implementing this feature some day, we should consider these cases:
  22434. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22435. // on the settings of `dataZoom`), it should be re-performed if the component
  22436. // is modified by `setOption`.
  22437. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22438. // it should be re-performed when the result array of `getTargetSeries` changed.
  22439. // We use `dependencies` to cover these issues.
  22440. // (3) How to update target series when coordinate system related components modified.
  22441. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22442. // and this case all of the tasks will be set as dirty.
  22443. ecModel.restoreData(payload);
  22444. // Theoretically an overall task not only depends on each of its target series, but also
  22445. // depends on all of the series.
  22446. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22447. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22448. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22449. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22450. // probably cause state chaos (consider `dataZoomProcessor`).
  22451. this._stageTaskMap.each(function (taskRecord) {
  22452. var overallTask = taskRecord.overallTask;
  22453. overallTask && overallTask.dirty();
  22454. });
  22455. };
  22456. // If seriesModel provided, incremental threshold is check by series data.
  22457. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  22458. // For overall task
  22459. if (!task.__pipeline) {
  22460. return;
  22461. }
  22462. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22463. var pCtx = pipeline.context;
  22464. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  22465. var step = incremental ? pipeline.step : null;
  22466. var modDataCount = pCtx && pCtx.modDataCount;
  22467. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22468. return {
  22469. step: step,
  22470. modBy: modBy,
  22471. modDataCount: modDataCount
  22472. };
  22473. };
  22474. Scheduler.prototype.getPipeline = function (pipelineId) {
  22475. return this._pipelineMap.get(pipelineId);
  22476. };
  22477. /**
  22478. * Current, progressive rendering starts from visual and layout.
  22479. * Always detect render mode in the same stage, avoiding that incorrect
  22480. * detection caused by data filtering.
  22481. * Caution:
  22482. * `updateStreamModes` use `seriesModel.getData()`.
  22483. */
  22484. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  22485. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22486. var data = seriesModel.getData();
  22487. var dataLen = data.count();
  22488. // `progressiveRender` means that can render progressively in each
  22489. // animation frame. Note that some types of series do not provide
  22490. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22491. // use the term `incremental` but not `progressive` to describe the
  22492. // case that `chart.appendData`.
  22493. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  22494. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22495. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22496. // see `test/candlestick-large3.html`
  22497. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22498. seriesModel.pipelineContext = pipeline.context = {
  22499. progressiveRender: progressiveRender,
  22500. modDataCount: modDataCount,
  22501. large: large
  22502. };
  22503. };
  22504. Scheduler.prototype.restorePipelines = function (ecModel) {
  22505. var scheduler = this;
  22506. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22507. ecModel.eachSeries(function (seriesModel) {
  22508. var progressive = seriesModel.getProgressive();
  22509. var pipelineId = seriesModel.uid;
  22510. pipelineMap.set(pipelineId, {
  22511. id: pipelineId,
  22512. head: null,
  22513. tail: null,
  22514. threshold: seriesModel.getProgressiveThreshold(),
  22515. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22516. blockIndex: -1,
  22517. step: Math.round(progressive || 700),
  22518. count: 0
  22519. });
  22520. scheduler._pipe(seriesModel, seriesModel.dataTask);
  22521. });
  22522. };
  22523. Scheduler.prototype.prepareStageTasks = function () {
  22524. var stageTaskMap = this._stageTaskMap;
  22525. var ecModel = this.api.getModel();
  22526. var api = this.api;
  22527. each(this._allHandlers, function (handler) {
  22528. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  22529. var errMsg = '';
  22530. if ("development" !== 'production') {
  22531. // Currently do not need to support to sepecify them both.
  22532. errMsg = '"reset" and "overallReset" must not be both specified.';
  22533. }
  22534. assert(!(handler.reset && handler.overallReset), errMsg);
  22535. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  22536. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  22537. }, this);
  22538. };
  22539. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  22540. var renderTask = view.renderTask;
  22541. var context = renderTask.context;
  22542. context.model = model;
  22543. context.ecModel = ecModel;
  22544. context.api = api;
  22545. renderTask.__block = !view.incrementalPrepareRender;
  22546. this._pipe(model, renderTask);
  22547. };
  22548. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  22549. // If we do not use `block` here, it should be considered when to update modes.
  22550. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  22551. block: true
  22552. });
  22553. };
  22554. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  22555. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  22556. };
  22557. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  22558. opt = opt || {};
  22559. var unfinished = false;
  22560. var scheduler = this;
  22561. each(stageHandlers, function (stageHandler, idx) {
  22562. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22563. return;
  22564. }
  22565. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22566. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22567. var overallTask = stageHandlerRecord.overallTask;
  22568. if (overallTask) {
  22569. var overallNeedDirty_1;
  22570. var agentStubMap = overallTask.agentStubMap;
  22571. agentStubMap.each(function (stub) {
  22572. if (needSetDirty(opt, stub)) {
  22573. stub.dirty();
  22574. overallNeedDirty_1 = true;
  22575. }
  22576. });
  22577. overallNeedDirty_1 && overallTask.dirty();
  22578. scheduler.updatePayload(overallTask, payload);
  22579. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block);
  22580. // Execute stubs firstly, which may set the overall task dirty,
  22581. // then execute the overall task. And stub will call seriesModel.setData,
  22582. // which ensures that in the overallTask seriesModel.getData() will not
  22583. // return incorrect data.
  22584. agentStubMap.each(function (stub) {
  22585. stub.perform(performArgs_1);
  22586. });
  22587. if (overallTask.perform(performArgs_1)) {
  22588. unfinished = true;
  22589. }
  22590. } else if (seriesTaskMap) {
  22591. seriesTaskMap.each(function (task, pipelineId) {
  22592. if (needSetDirty(opt, task)) {
  22593. task.dirty();
  22594. }
  22595. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22596. // FIXME
  22597. // if intending to declare `performRawSeries` in handlers, only
  22598. // stream-independent (specifically, data item independent) operations can be
  22599. // performed. Because if a series is filtered, most of the tasks will not
  22600. // be performed. A stream-dependent operation probably cause wrong biz logic.
  22601. // Perhaps we should not provide a separate callback for this case instead
  22602. // of providing the config `performRawSeries`. The stream-dependent operations
  22603. // and stream-independent operations should better not be mixed.
  22604. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  22605. scheduler.updatePayload(task, payload);
  22606. if (task.perform(performArgs)) {
  22607. unfinished = true;
  22608. }
  22609. });
  22610. }
  22611. });
  22612. function needSetDirty(opt, task) {
  22613. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22614. }
  22615. this.unfinished = unfinished || this.unfinished;
  22616. };
  22617. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  22618. var unfinished;
  22619. ecModel.eachSeries(function (seriesModel) {
  22620. // Progress to the end for dataInit and dataRestore.
  22621. unfinished = seriesModel.dataTask.perform() || unfinished;
  22622. });
  22623. this.unfinished = unfinished || this.unfinished;
  22624. };
  22625. Scheduler.prototype.plan = function () {
  22626. // Travel pipelines, check block.
  22627. this._pipelineMap.each(function (pipeline) {
  22628. var task = pipeline.tail;
  22629. do {
  22630. if (task.__block) {
  22631. pipeline.blockIndex = task.__idxInPipeline;
  22632. break;
  22633. }
  22634. task = task.getUpstream();
  22635. } while (task);
  22636. });
  22637. };
  22638. Scheduler.prototype.updatePayload = function (task, payload) {
  22639. payload !== 'remain' && (task.context.payload = payload);
  22640. };
  22641. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  22642. var scheduler = this;
  22643. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22644. // The count of stages are totally about only several dozen, so
  22645. // do not need to reuse the map.
  22646. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  22647. var seriesType = stageHandler.seriesType;
  22648. var getTargetSeries = stageHandler.getTargetSeries;
  22649. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22650. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22651. // it works but it may cause other irrelevant charts blocked.
  22652. if (stageHandler.createOnAllSeries) {
  22653. ecModel.eachRawSeries(create);
  22654. } else if (seriesType) {
  22655. ecModel.eachRawSeriesByType(seriesType, create);
  22656. } else if (getTargetSeries) {
  22657. getTargetSeries(ecModel, api).each(create);
  22658. }
  22659. function create(seriesModel) {
  22660. var pipelineId = seriesModel.uid;
  22661. // Init tasks for each seriesModel only once.
  22662. // Reuse original task instance.
  22663. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  22664. plan: seriesTaskPlan,
  22665. reset: seriesTaskReset,
  22666. count: seriesTaskCount
  22667. }));
  22668. task.context = {
  22669. model: seriesModel,
  22670. ecModel: ecModel,
  22671. api: api,
  22672. // PENDING: `useClearVisual` not used?
  22673. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22674. plan: stageHandler.plan,
  22675. reset: stageHandler.reset,
  22676. scheduler: scheduler
  22677. };
  22678. scheduler._pipe(seriesModel, task);
  22679. }
  22680. };
  22681. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  22682. var scheduler = this;
  22683. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22684. // For overall task, the function only be called on reset stage.
  22685. || createTask({
  22686. reset: overallTaskReset
  22687. });
  22688. overallTask.context = {
  22689. ecModel: ecModel,
  22690. api: api,
  22691. overallReset: stageHandler.overallReset,
  22692. scheduler: scheduler
  22693. };
  22694. var oldAgentStubMap = overallTask.agentStubMap;
  22695. // The count of stages are totally about only several dozen, so
  22696. // do not need to reuse the map.
  22697. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  22698. var seriesType = stageHandler.seriesType;
  22699. var getTargetSeries = stageHandler.getTargetSeries;
  22700. var overallProgress = true;
  22701. var shouldOverallTaskDirty = false;
  22702. // FIXME:TS never used, so comment it
  22703. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  22704. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22705. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22706. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22707. // we set the pipeline block.
  22708. var errMsg = '';
  22709. if ("development" !== 'production') {
  22710. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  22711. }
  22712. assert(!stageHandler.createOnAllSeries, errMsg);
  22713. if (seriesType) {
  22714. ecModel.eachRawSeriesByType(seriesType, createStub);
  22715. } else if (getTargetSeries) {
  22716. getTargetSeries(ecModel, api).each(createStub);
  22717. }
  22718. // Otherwise, (usually it is legacy case), the overall task will only be
  22719. // executed when upstream is dirty. Otherwise the progressive rendering of all
  22720. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22721. // dirty info from upstream.
  22722. else {
  22723. overallProgress = false;
  22724. each(ecModel.getSeries(), createStub);
  22725. }
  22726. function createStub(seriesModel) {
  22727. var pipelineId = seriesModel.uid;
  22728. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || (
  22729. // When the result of `getTargetSeries` changed, the overallTask
  22730. // should be set as dirty and re-performed.
  22731. shouldOverallTaskDirty = true, createTask({
  22732. reset: stubReset,
  22733. onDirty: stubOnDirty
  22734. })));
  22735. stub.context = {
  22736. model: seriesModel,
  22737. overallProgress: overallProgress
  22738. // FIXME:TS never used, so comment it
  22739. // modifyOutputEnd: modifyOutputEnd
  22740. };
  22741. stub.agent = overallTask;
  22742. stub.__block = overallProgress;
  22743. scheduler._pipe(seriesModel, stub);
  22744. }
  22745. if (shouldOverallTaskDirty) {
  22746. overallTask.dirty();
  22747. }
  22748. };
  22749. Scheduler.prototype._pipe = function (seriesModel, task) {
  22750. var pipelineId = seriesModel.uid;
  22751. var pipeline = this._pipelineMap.get(pipelineId);
  22752. !pipeline.head && (pipeline.head = task);
  22753. pipeline.tail && pipeline.tail.pipe(task);
  22754. pipeline.tail = task;
  22755. task.__idxInPipeline = pipeline.count++;
  22756. task.__pipeline = pipeline;
  22757. };
  22758. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22759. if (isFunction(stageHandler)) {
  22760. stageHandler = {
  22761. overallReset: stageHandler,
  22762. seriesType: detectSeriseType(stageHandler)
  22763. };
  22764. }
  22765. stageHandler.uid = getUID('stageHandler');
  22766. visualType && (stageHandler.visualType = visualType);
  22767. return stageHandler;
  22768. };
  22769. return Scheduler;
  22770. }();
  22771. function overallTaskReset(context) {
  22772. context.overallReset(context.ecModel, context.api, context.payload);
  22773. }
  22774. function stubReset(context) {
  22775. return context.overallProgress && stubProgress;
  22776. }
  22777. function stubProgress() {
  22778. this.agent.dirty();
  22779. this.getDownstream().dirty();
  22780. }
  22781. function stubOnDirty() {
  22782. this.agent && this.agent.dirty();
  22783. }
  22784. function seriesTaskPlan(context) {
  22785. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  22786. }
  22787. function seriesTaskReset(context) {
  22788. if (context.useClearVisual) {
  22789. context.data.clearAllVisual();
  22790. }
  22791. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  22792. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  22793. return makeSeriesTaskProgress(idx);
  22794. }) : singleSeriesTaskProgress;
  22795. }
  22796. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22797. function makeSeriesTaskProgress(resetDefineIdx) {
  22798. return function (params, context) {
  22799. var data = context.data;
  22800. var resetDefine = context.resetDefines[resetDefineIdx];
  22801. if (resetDefine && resetDefine.dataEach) {
  22802. for (var i = params.start; i < params.end; i++) {
  22803. resetDefine.dataEach(data, i);
  22804. }
  22805. } else if (resetDefine && resetDefine.progress) {
  22806. resetDefine.progress(params, data);
  22807. }
  22808. };
  22809. }
  22810. function seriesTaskCount(context) {
  22811. return context.data.count();
  22812. }
  22813. /**
  22814. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22815. * To ensure that they can work normally, they should work in block mode, that is,
  22816. * they should not be started util the previous tasks finished. So they cause the
  22817. * progressive rendering disabled. We try to detect the series type, to narrow down
  22818. * the block range to only the series type they concern, but not all series.
  22819. */
  22820. function detectSeriseType(legacyFunc) {
  22821. seriesType = null;
  22822. try {
  22823. // Assume there is no async when calling `eachSeriesByType`.
  22824. legacyFunc(ecModelMock, apiMock);
  22825. } catch (e) {}
  22826. return seriesType;
  22827. }
  22828. var ecModelMock = {};
  22829. var apiMock = {};
  22830. var seriesType;
  22831. mockMethods(ecModelMock, GlobalModel);
  22832. mockMethods(apiMock, ExtensionAPI);
  22833. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22834. seriesType = type;
  22835. };
  22836. ecModelMock.eachComponent = function (cond) {
  22837. if (cond.mainType === 'series' && cond.subType) {
  22838. seriesType = cond.subType;
  22839. }
  22840. };
  22841. function mockMethods(target, Clz) {
  22842. /* eslint-disable */
  22843. for (var name_1 in Clz.prototype) {
  22844. // Do not use hasOwnProperty
  22845. target[name_1] = noop;
  22846. }
  22847. /* eslint-enable */
  22848. }
  22849. /*
  22850. * Licensed to the Apache Software Foundation (ASF) under one
  22851. * or more contributor license agreements. See the NOTICE file
  22852. * distributed with this work for additional information
  22853. * regarding copyright ownership. The ASF licenses this file
  22854. * to you under the Apache License, Version 2.0 (the
  22855. * "License"); you may not use this file except in compliance
  22856. * with the License. You may obtain a copy of the License at
  22857. *
  22858. * http://www.apache.org/licenses/LICENSE-2.0
  22859. *
  22860. * Unless required by applicable law or agreed to in writing,
  22861. * software distributed under the License is distributed on an
  22862. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22863. * KIND, either express or implied. See the License for the
  22864. * specific language governing permissions and limitations
  22865. * under the License.
  22866. */
  22867. /**
  22868. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22869. */
  22870. /*
  22871. * Licensed to the Apache Software Foundation (ASF) under one
  22872. * or more contributor license agreements. See the NOTICE file
  22873. * distributed with this work for additional information
  22874. * regarding copyright ownership. The ASF licenses this file
  22875. * to you under the Apache License, Version 2.0 (the
  22876. * "License"); you may not use this file except in compliance
  22877. * with the License. You may obtain a copy of the License at
  22878. *
  22879. * http://www.apache.org/licenses/LICENSE-2.0
  22880. *
  22881. * Unless required by applicable law or agreed to in writing,
  22882. * software distributed under the License is distributed on an
  22883. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22884. * KIND, either express or implied. See the License for the
  22885. * specific language governing permissions and limitations
  22886. * under the License.
  22887. */
  22888. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  22889. var lightTheme = {
  22890. color: colorAll,
  22891. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  22892. };
  22893. /*
  22894. * Licensed to the Apache Software Foundation (ASF) under one
  22895. * or more contributor license agreements. See the NOTICE file
  22896. * distributed with this work for additional information
  22897. * regarding copyright ownership. The ASF licenses this file
  22898. * to you under the Apache License, Version 2.0 (the
  22899. * "License"); you may not use this file except in compliance
  22900. * with the License. You may obtain a copy of the License at
  22901. *
  22902. * http://www.apache.org/licenses/LICENSE-2.0
  22903. *
  22904. * Unless required by applicable law or agreed to in writing,
  22905. * software distributed under the License is distributed on an
  22906. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22907. * KIND, either express or implied. See the License for the
  22908. * specific language governing permissions and limitations
  22909. * under the License.
  22910. */
  22911. /**
  22912. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22913. */
  22914. /*
  22915. * Licensed to the Apache Software Foundation (ASF) under one
  22916. * or more contributor license agreements. See the NOTICE file
  22917. * distributed with this work for additional information
  22918. * regarding copyright ownership. The ASF licenses this file
  22919. * to you under the Apache License, Version 2.0 (the
  22920. * "License"); you may not use this file except in compliance
  22921. * with the License. You may obtain a copy of the License at
  22922. *
  22923. * http://www.apache.org/licenses/LICENSE-2.0
  22924. *
  22925. * Unless required by applicable law or agreed to in writing,
  22926. * software distributed under the License is distributed on an
  22927. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22928. * KIND, either express or implied. See the License for the
  22929. * specific language governing permissions and limitations
  22930. * under the License.
  22931. */
  22932. var contrastColor = '#B9B8CE';
  22933. var backgroundColor = '#100C2A';
  22934. var axisCommon = function () {
  22935. return {
  22936. axisLine: {
  22937. lineStyle: {
  22938. color: contrastColor
  22939. }
  22940. },
  22941. splitLine: {
  22942. lineStyle: {
  22943. color: '#484753'
  22944. }
  22945. },
  22946. splitArea: {
  22947. areaStyle: {
  22948. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  22949. }
  22950. },
  22951. minorSplitLine: {
  22952. lineStyle: {
  22953. color: '#20203B'
  22954. }
  22955. }
  22956. };
  22957. };
  22958. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  22959. var theme = {
  22960. darkMode: true,
  22961. color: colorPalette,
  22962. backgroundColor: backgroundColor,
  22963. axisPointer: {
  22964. lineStyle: {
  22965. color: '#817f91'
  22966. },
  22967. crossStyle: {
  22968. color: '#817f91'
  22969. },
  22970. label: {
  22971. // TODO Contrast of label backgorundColor
  22972. color: '#fff'
  22973. }
  22974. },
  22975. legend: {
  22976. textStyle: {
  22977. color: contrastColor
  22978. }
  22979. },
  22980. textStyle: {
  22981. color: contrastColor
  22982. },
  22983. title: {
  22984. textStyle: {
  22985. color: '#EEF1FA'
  22986. },
  22987. subtextStyle: {
  22988. color: '#B9B8CE'
  22989. }
  22990. },
  22991. toolbox: {
  22992. iconStyle: {
  22993. borderColor: contrastColor
  22994. }
  22995. },
  22996. dataZoom: {
  22997. borderColor: '#71708A',
  22998. textStyle: {
  22999. color: contrastColor
  23000. },
  23001. brushStyle: {
  23002. color: 'rgba(135,163,206,0.3)'
  23003. },
  23004. handleStyle: {
  23005. color: '#353450',
  23006. borderColor: '#C5CBE3'
  23007. },
  23008. moveHandleStyle: {
  23009. color: '#B0B6C3',
  23010. opacity: 0.3
  23011. },
  23012. fillerColor: 'rgba(135,163,206,0.2)',
  23013. emphasis: {
  23014. handleStyle: {
  23015. borderColor: '#91B7F2',
  23016. color: '#4D587D'
  23017. },
  23018. moveHandleStyle: {
  23019. color: '#636D9A',
  23020. opacity: 0.7
  23021. }
  23022. },
  23023. dataBackground: {
  23024. lineStyle: {
  23025. color: '#71708A',
  23026. width: 1
  23027. },
  23028. areaStyle: {
  23029. color: '#71708A'
  23030. }
  23031. },
  23032. selectedDataBackground: {
  23033. lineStyle: {
  23034. color: '#87A3CE'
  23035. },
  23036. areaStyle: {
  23037. color: '#87A3CE'
  23038. }
  23039. }
  23040. },
  23041. visualMap: {
  23042. textStyle: {
  23043. color: contrastColor
  23044. }
  23045. },
  23046. timeline: {
  23047. lineStyle: {
  23048. color: contrastColor
  23049. },
  23050. label: {
  23051. color: contrastColor
  23052. },
  23053. controlStyle: {
  23054. color: contrastColor,
  23055. borderColor: contrastColor
  23056. }
  23057. },
  23058. calendar: {
  23059. itemStyle: {
  23060. color: backgroundColor
  23061. },
  23062. dayLabel: {
  23063. color: contrastColor
  23064. },
  23065. monthLabel: {
  23066. color: contrastColor
  23067. },
  23068. yearLabel: {
  23069. color: contrastColor
  23070. }
  23071. },
  23072. timeAxis: axisCommon(),
  23073. logAxis: axisCommon(),
  23074. valueAxis: axisCommon(),
  23075. categoryAxis: axisCommon(),
  23076. line: {
  23077. symbol: 'circle'
  23078. },
  23079. graph: {
  23080. color: colorPalette
  23081. },
  23082. gauge: {
  23083. title: {
  23084. color: contrastColor
  23085. },
  23086. axisLine: {
  23087. lineStyle: {
  23088. color: [[1, 'rgba(207,212,219,0.2)']]
  23089. }
  23090. },
  23091. axisLabel: {
  23092. color: contrastColor
  23093. },
  23094. detail: {
  23095. color: '#EEF1FA'
  23096. }
  23097. },
  23098. candlestick: {
  23099. itemStyle: {
  23100. color: '#f64e56',
  23101. color0: '#54ea92',
  23102. borderColor: '#f64e56',
  23103. borderColor0: '#54ea92'
  23104. // borderColor: '#ca2824',
  23105. // borderColor0: '#09a443'
  23106. }
  23107. }
  23108. };
  23109. theme.categoryAxis.splitLine.show = false;
  23110. /**
  23111. * Usage of query:
  23112. * `chart.on('click', query, handler);`
  23113. * The `query` can be:
  23114. * + The component type query string, only `mainType` or `mainType.subType`,
  23115. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23116. * + The component query object, like:
  23117. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23118. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23119. * + The data query object, like:
  23120. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23121. * + The other query object (cmponent customized query), like:
  23122. * `{element: 'some'}` (only available in custom series).
  23123. *
  23124. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23125. * same as there is no such prop in the `query` object.
  23126. */
  23127. var ECEventProcessor = /** @class */function () {
  23128. function ECEventProcessor() {}
  23129. ECEventProcessor.prototype.normalizeQuery = function (query) {
  23130. var cptQuery = {};
  23131. var dataQuery = {};
  23132. var otherQuery = {};
  23133. // `query` is `mainType` or `mainType.subType` of component.
  23134. if (isString(query)) {
  23135. var condCptType = parseClassType(query);
  23136. // `.main` and `.sub` may be ''.
  23137. cptQuery.mainType = condCptType.main || null;
  23138. cptQuery.subType = condCptType.sub || null;
  23139. }
  23140. // `query` is an object, convert to {mainType, index, name, id}.
  23141. else {
  23142. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23143. // can not be used in `compomentModel.filterForExposedEvent`.
  23144. var suffixes_1 = ['Index', 'Name', 'Id'];
  23145. var dataKeys_1 = {
  23146. name: 1,
  23147. dataIndex: 1,
  23148. dataType: 1
  23149. };
  23150. each(query, function (val, key) {
  23151. var reserved = false;
  23152. for (var i = 0; i < suffixes_1.length; i++) {
  23153. var propSuffix = suffixes_1[i];
  23154. var suffixPos = key.lastIndexOf(propSuffix);
  23155. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23156. var mainType = key.slice(0, suffixPos);
  23157. // Consider `dataIndex`.
  23158. if (mainType !== 'data') {
  23159. cptQuery.mainType = mainType;
  23160. cptQuery[propSuffix.toLowerCase()] = val;
  23161. reserved = true;
  23162. }
  23163. }
  23164. }
  23165. if (dataKeys_1.hasOwnProperty(key)) {
  23166. dataQuery[key] = val;
  23167. reserved = true;
  23168. }
  23169. if (!reserved) {
  23170. otherQuery[key] = val;
  23171. }
  23172. });
  23173. }
  23174. return {
  23175. cptQuery: cptQuery,
  23176. dataQuery: dataQuery,
  23177. otherQuery: otherQuery
  23178. };
  23179. };
  23180. ECEventProcessor.prototype.filter = function (eventType, query) {
  23181. // They should be assigned before each trigger call.
  23182. var eventInfo = this.eventInfo;
  23183. if (!eventInfo) {
  23184. return true;
  23185. }
  23186. var targetEl = eventInfo.targetEl;
  23187. var packedEvent = eventInfo.packedEvent;
  23188. var model = eventInfo.model;
  23189. var view = eventInfo.view;
  23190. // For event like 'globalout'.
  23191. if (!model || !view) {
  23192. return true;
  23193. }
  23194. var cptQuery = query.cptQuery;
  23195. var dataQuery = query.dataQuery;
  23196. 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));
  23197. function check(query, host, prop, propOnHost) {
  23198. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23199. }
  23200. };
  23201. ECEventProcessor.prototype.afterTrigger = function () {
  23202. // Make sure the eventInfo won't be used in next trigger.
  23203. this.eventInfo = null;
  23204. };
  23205. return ECEventProcessor;
  23206. }();
  23207. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  23208. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']);
  23209. // Encoding visual for all series include which is filtered for legend drawing
  23210. var seriesSymbolTask = {
  23211. createOnAllSeries: true,
  23212. // For legend.
  23213. performRawSeries: true,
  23214. reset: function (seriesModel, ecModel) {
  23215. var data = seriesModel.getData();
  23216. if (seriesModel.legendIcon) {
  23217. data.setVisual('legendIcon', seriesModel.legendIcon);
  23218. }
  23219. if (!seriesModel.hasSymbolVisual) {
  23220. return;
  23221. }
  23222. var symbolOptions = {};
  23223. var symbolOptionsCb = {};
  23224. var hasCallback = false;
  23225. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  23226. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  23227. var val = seriesModel.get(symbolPropName);
  23228. if (isFunction(val)) {
  23229. hasCallback = true;
  23230. symbolOptionsCb[symbolPropName] = val;
  23231. } else {
  23232. symbolOptions[symbolPropName] = val;
  23233. }
  23234. }
  23235. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  23236. data.setVisual(extend({
  23237. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  23238. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  23239. }, symbolOptions));
  23240. // Only visible series has each data be visual encoded
  23241. if (ecModel.isSeriesFiltered(seriesModel)) {
  23242. return;
  23243. }
  23244. var symbolPropsCb = keys(symbolOptionsCb);
  23245. function dataEach(data, idx) {
  23246. var rawValue = seriesModel.getRawValue(idx);
  23247. var params = seriesModel.getDataParams(idx);
  23248. for (var i = 0; i < symbolPropsCb.length; i++) {
  23249. var symbolPropName = symbolPropsCb[i];
  23250. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  23251. }
  23252. }
  23253. return {
  23254. dataEach: hasCallback ? dataEach : null
  23255. };
  23256. }
  23257. };
  23258. var dataSymbolTask = {
  23259. createOnAllSeries: true,
  23260. // For legend.
  23261. performRawSeries: true,
  23262. reset: function (seriesModel, ecModel) {
  23263. if (!seriesModel.hasSymbolVisual) {
  23264. return;
  23265. }
  23266. // Only visible series has each data be visual encoded
  23267. if (ecModel.isSeriesFiltered(seriesModel)) {
  23268. return;
  23269. }
  23270. var data = seriesModel.getData();
  23271. function dataEach(data, idx) {
  23272. var itemModel = data.getItemModel(idx);
  23273. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  23274. var symbolPropName = SYMBOL_PROPS[i];
  23275. var val = itemModel.getShallow(symbolPropName, true);
  23276. if (val != null) {
  23277. data.setItemVisual(idx, symbolPropName, val);
  23278. }
  23279. }
  23280. }
  23281. return {
  23282. dataEach: data.hasItemOption ? dataEach : null
  23283. };
  23284. }
  23285. };
  23286. /*
  23287. * Licensed to the Apache Software Foundation (ASF) under one
  23288. * or more contributor license agreements. See the NOTICE file
  23289. * distributed with this work for additional information
  23290. * regarding copyright ownership. The ASF licenses this file
  23291. * to you under the Apache License, Version 2.0 (the
  23292. * "License"); you may not use this file except in compliance
  23293. * with the License. You may obtain a copy of the License at
  23294. *
  23295. * http://www.apache.org/licenses/LICENSE-2.0
  23296. *
  23297. * Unless required by applicable law or agreed to in writing,
  23298. * software distributed under the License is distributed on an
  23299. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23300. * KIND, either express or implied. See the License for the
  23301. * specific language governing permissions and limitations
  23302. * under the License.
  23303. */
  23304. /**
  23305. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23306. */
  23307. /*
  23308. * Licensed to the Apache Software Foundation (ASF) under one
  23309. * or more contributor license agreements. See the NOTICE file
  23310. * distributed with this work for additional information
  23311. * regarding copyright ownership. The ASF licenses this file
  23312. * to you under the Apache License, Version 2.0 (the
  23313. * "License"); you may not use this file except in compliance
  23314. * with the License. You may obtain a copy of the License at
  23315. *
  23316. * http://www.apache.org/licenses/LICENSE-2.0
  23317. *
  23318. * Unless required by applicable law or agreed to in writing,
  23319. * software distributed under the License is distributed on an
  23320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23321. * KIND, either express or implied. See the License for the
  23322. * specific language governing permissions and limitations
  23323. * under the License.
  23324. */
  23325. function getItemVisualFromData(data, dataIndex, key) {
  23326. switch (key) {
  23327. case 'color':
  23328. var style = data.getItemVisual(dataIndex, 'style');
  23329. return style[data.getVisual('drawType')];
  23330. case 'opacity':
  23331. return data.getItemVisual(dataIndex, 'style').opacity;
  23332. case 'symbol':
  23333. case 'symbolSize':
  23334. case 'liftZ':
  23335. return data.getItemVisual(dataIndex, key);
  23336. default:
  23337. if ("development" !== 'production') {
  23338. console.warn("Unknown visual type " + key);
  23339. }
  23340. }
  23341. }
  23342. function getVisualFromData(data, key) {
  23343. switch (key) {
  23344. case 'color':
  23345. var style = data.getVisual('style');
  23346. return style[data.getVisual('drawType')];
  23347. case 'opacity':
  23348. return data.getVisual('style').opacity;
  23349. case 'symbol':
  23350. case 'symbolSize':
  23351. case 'liftZ':
  23352. return data.getVisual(key);
  23353. default:
  23354. if ("development" !== 'production') {
  23355. console.warn("Unknown visual type " + key);
  23356. }
  23357. }
  23358. }
  23359. // Legacy data selection action.
  23360. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  23361. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  23362. function getSeriesIndices(ecModel, payload) {
  23363. var seriesIndices = [];
  23364. ecModel.eachComponent({
  23365. mainType: 'series',
  23366. subType: seriesType,
  23367. query: payload
  23368. }, function (seriesModel) {
  23369. seriesIndices.push(seriesModel.seriesIndex);
  23370. });
  23371. return seriesIndices;
  23372. }
  23373. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  23374. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  23375. payload = extend({}, payload);
  23376. if ("development" !== 'production') {
  23377. deprecateReplaceLog(payload.type, eventsMap[1]);
  23378. }
  23379. api.dispatchAction(extend(payload, {
  23380. type: eventsMap[1],
  23381. seriesIndex: getSeriesIndices(ecModel, payload)
  23382. }));
  23383. });
  23384. });
  23385. }
  23386. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  23387. var legacyEventName = type + eventPostfix;
  23388. if (!ecIns.isSilent(legacyEventName)) {
  23389. if ("development" !== 'production') {
  23390. deprecateLog("event " + legacyEventName + " is deprecated.");
  23391. }
  23392. ecModel.eachComponent({
  23393. mainType: 'series',
  23394. subType: 'pie'
  23395. }, function (seriesModel) {
  23396. var seriesIndex = seriesModel.seriesIndex;
  23397. var selectedMap = seriesModel.option.selectedMap;
  23398. var selected = payload.selected;
  23399. for (var i = 0; i < selected.length; i++) {
  23400. if (selected[i].seriesIndex === seriesIndex) {
  23401. var data = seriesModel.getData();
  23402. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  23403. ecIns.trigger(legacyEventName, {
  23404. type: legacyEventName,
  23405. seriesId: seriesModel.id,
  23406. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  23407. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  23408. });
  23409. }
  23410. }
  23411. });
  23412. }
  23413. }
  23414. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  23415. messageCenter.on('selectchanged', function (params) {
  23416. var ecModel = api.getModel();
  23417. if (params.isFromClick) {
  23418. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  23419. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  23420. } else if (params.fromAction === 'select') {
  23421. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  23422. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  23423. } else if (params.fromAction === 'unselect') {
  23424. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  23425. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  23426. }
  23427. });
  23428. }
  23429. /*
  23430. * Licensed to the Apache Software Foundation (ASF) under one
  23431. * or more contributor license agreements. See the NOTICE file
  23432. * distributed with this work for additional information
  23433. * regarding copyright ownership. The ASF licenses this file
  23434. * to you under the Apache License, Version 2.0 (the
  23435. * "License"); you may not use this file except in compliance
  23436. * with the License. You may obtain a copy of the License at
  23437. *
  23438. * http://www.apache.org/licenses/LICENSE-2.0
  23439. *
  23440. * Unless required by applicable law or agreed to in writing,
  23441. * software distributed under the License is distributed on an
  23442. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23443. * KIND, either express or implied. See the License for the
  23444. * specific language governing permissions and limitations
  23445. * under the License.
  23446. */
  23447. /**
  23448. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23449. */
  23450. /*
  23451. * Licensed to the Apache Software Foundation (ASF) under one
  23452. * or more contributor license agreements. See the NOTICE file
  23453. * distributed with this work for additional information
  23454. * regarding copyright ownership. The ASF licenses this file
  23455. * to you under the Apache License, Version 2.0 (the
  23456. * "License"); you may not use this file except in compliance
  23457. * with the License. You may obtain a copy of the License at
  23458. *
  23459. * http://www.apache.org/licenses/LICENSE-2.0
  23460. *
  23461. * Unless required by applicable law or agreed to in writing,
  23462. * software distributed under the License is distributed on an
  23463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23464. * KIND, either express or implied. See the License for the
  23465. * specific language governing permissions and limitations
  23466. * under the License.
  23467. */
  23468. function findEventDispatcher(target, det, returnFirstMatch) {
  23469. var found;
  23470. while (target) {
  23471. if (det(target)) {
  23472. found = target;
  23473. if (returnFirstMatch) {
  23474. break;
  23475. }
  23476. }
  23477. target = target.__hostTarget || target.parent;
  23478. }
  23479. return found;
  23480. }
  23481. var wmUniqueIndex = Math.round(Math.random() * 9);
  23482. var supportDefineProperty = typeof Object.defineProperty === 'function';
  23483. var WeakMap = (function () {
  23484. function WeakMap() {
  23485. this._id = '__ec_inner_' + wmUniqueIndex++;
  23486. }
  23487. WeakMap.prototype.get = function (key) {
  23488. return this._guard(key)[this._id];
  23489. };
  23490. WeakMap.prototype.set = function (key, value) {
  23491. var target = this._guard(key);
  23492. if (supportDefineProperty) {
  23493. Object.defineProperty(target, this._id, {
  23494. value: value,
  23495. enumerable: false,
  23496. configurable: true
  23497. });
  23498. }
  23499. else {
  23500. target[this._id] = value;
  23501. }
  23502. return this;
  23503. };
  23504. WeakMap.prototype["delete"] = function (key) {
  23505. if (this.has(key)) {
  23506. delete this._guard(key)[this._id];
  23507. return true;
  23508. }
  23509. return false;
  23510. };
  23511. WeakMap.prototype.has = function (key) {
  23512. return !!this._guard(key)[this._id];
  23513. };
  23514. WeakMap.prototype._guard = function (key) {
  23515. if (key !== Object(key)) {
  23516. throw TypeError('Value of WeakMap is not a non-null object.');
  23517. }
  23518. return key;
  23519. };
  23520. return WeakMap;
  23521. }());
  23522. /**
  23523. * Triangle shape
  23524. * @inner
  23525. */
  23526. var Triangle = Path.extend({
  23527. type: 'triangle',
  23528. shape: {
  23529. cx: 0,
  23530. cy: 0,
  23531. width: 0,
  23532. height: 0
  23533. },
  23534. buildPath: function (path, shape) {
  23535. var cx = shape.cx;
  23536. var cy = shape.cy;
  23537. var width = shape.width / 2;
  23538. var height = shape.height / 2;
  23539. path.moveTo(cx, cy - height);
  23540. path.lineTo(cx + width, cy + height);
  23541. path.lineTo(cx - width, cy + height);
  23542. path.closePath();
  23543. }
  23544. });
  23545. /**
  23546. * Diamond shape
  23547. * @inner
  23548. */
  23549. var Diamond = Path.extend({
  23550. type: 'diamond',
  23551. shape: {
  23552. cx: 0,
  23553. cy: 0,
  23554. width: 0,
  23555. height: 0
  23556. },
  23557. buildPath: function (path, shape) {
  23558. var cx = shape.cx;
  23559. var cy = shape.cy;
  23560. var width = shape.width / 2;
  23561. var height = shape.height / 2;
  23562. path.moveTo(cx, cy - height);
  23563. path.lineTo(cx + width, cy);
  23564. path.lineTo(cx, cy + height);
  23565. path.lineTo(cx - width, cy);
  23566. path.closePath();
  23567. }
  23568. });
  23569. /**
  23570. * Pin shape
  23571. * @inner
  23572. */
  23573. var Pin = Path.extend({
  23574. type: 'pin',
  23575. shape: {
  23576. // x, y on the cusp
  23577. x: 0,
  23578. y: 0,
  23579. width: 0,
  23580. height: 0
  23581. },
  23582. buildPath: function (path, shape) {
  23583. var x = shape.x;
  23584. var y = shape.y;
  23585. var w = shape.width / 5 * 3;
  23586. // Height must be larger than width
  23587. var h = Math.max(w, shape.height);
  23588. var r = w / 2;
  23589. // Dist on y with tangent point and circle center
  23590. var dy = r * r / (h - r);
  23591. var cy = y - h + r + dy;
  23592. var angle = Math.asin(dy / r);
  23593. // Dist on x with tangent point and circle center
  23594. var dx = Math.cos(angle) * r;
  23595. var tanX = Math.sin(angle);
  23596. var tanY = Math.cos(angle);
  23597. var cpLen = r * 0.6;
  23598. var cpLen2 = r * 0.7;
  23599. path.moveTo(x - dx, cy + dy);
  23600. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  23601. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  23602. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  23603. path.closePath();
  23604. }
  23605. });
  23606. /**
  23607. * Arrow shape
  23608. * @inner
  23609. */
  23610. var Arrow = Path.extend({
  23611. type: 'arrow',
  23612. shape: {
  23613. x: 0,
  23614. y: 0,
  23615. width: 0,
  23616. height: 0
  23617. },
  23618. buildPath: function (ctx, shape) {
  23619. var height = shape.height;
  23620. var width = shape.width;
  23621. var x = shape.x;
  23622. var y = shape.y;
  23623. var dx = width / 3 * 2;
  23624. ctx.moveTo(x, y);
  23625. ctx.lineTo(x + dx, y + height);
  23626. ctx.lineTo(x, y + height / 4 * 3);
  23627. ctx.lineTo(x - dx, y + height);
  23628. ctx.lineTo(x, y);
  23629. ctx.closePath();
  23630. }
  23631. });
  23632. /**
  23633. * Map of path constructors
  23634. */
  23635. // TODO Use function to build symbol path.
  23636. var symbolCtors = {
  23637. line: Line,
  23638. rect: Rect,
  23639. roundRect: Rect,
  23640. square: Rect,
  23641. circle: Circle,
  23642. diamond: Diamond,
  23643. pin: Pin,
  23644. arrow: Arrow,
  23645. triangle: Triangle
  23646. };
  23647. var symbolShapeMakers = {
  23648. line: function (x, y, w, h, shape) {
  23649. shape.x1 = x;
  23650. shape.y1 = y + h / 2;
  23651. shape.x2 = x + w;
  23652. shape.y2 = y + h / 2;
  23653. },
  23654. rect: function (x, y, w, h, shape) {
  23655. shape.x = x;
  23656. shape.y = y;
  23657. shape.width = w;
  23658. shape.height = h;
  23659. },
  23660. roundRect: function (x, y, w, h, shape) {
  23661. shape.x = x;
  23662. shape.y = y;
  23663. shape.width = w;
  23664. shape.height = h;
  23665. shape.r = Math.min(w, h) / 4;
  23666. },
  23667. square: function (x, y, w, h, shape) {
  23668. var size = Math.min(w, h);
  23669. shape.x = x;
  23670. shape.y = y;
  23671. shape.width = size;
  23672. shape.height = size;
  23673. },
  23674. circle: function (x, y, w, h, shape) {
  23675. // Put circle in the center of square
  23676. shape.cx = x + w / 2;
  23677. shape.cy = y + h / 2;
  23678. shape.r = Math.min(w, h) / 2;
  23679. },
  23680. diamond: function (x, y, w, h, shape) {
  23681. shape.cx = x + w / 2;
  23682. shape.cy = y + h / 2;
  23683. shape.width = w;
  23684. shape.height = h;
  23685. },
  23686. pin: function (x, y, w, h, shape) {
  23687. shape.x = x + w / 2;
  23688. shape.y = y + h / 2;
  23689. shape.width = w;
  23690. shape.height = h;
  23691. },
  23692. arrow: function (x, y, w, h, shape) {
  23693. shape.x = x + w / 2;
  23694. shape.y = y + h / 2;
  23695. shape.width = w;
  23696. shape.height = h;
  23697. },
  23698. triangle: function (x, y, w, h, shape) {
  23699. shape.cx = x + w / 2;
  23700. shape.cy = y + h / 2;
  23701. shape.width = w;
  23702. shape.height = h;
  23703. }
  23704. };
  23705. var symbolBuildProxies = {};
  23706. each(symbolCtors, function (Ctor, name) {
  23707. symbolBuildProxies[name] = new Ctor();
  23708. });
  23709. var SymbolClz = Path.extend({
  23710. type: 'symbol',
  23711. shape: {
  23712. symbolType: '',
  23713. x: 0,
  23714. y: 0,
  23715. width: 0,
  23716. height: 0
  23717. },
  23718. calculateTextPosition: function (out, config, rect) {
  23719. var res = calculateTextPosition(out, config, rect);
  23720. var shape = this.shape;
  23721. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  23722. res.y = rect.y + rect.height * 0.4;
  23723. }
  23724. return res;
  23725. },
  23726. buildPath: function (ctx, shape, inBundle) {
  23727. var symbolType = shape.symbolType;
  23728. if (symbolType !== 'none') {
  23729. var proxySymbol = symbolBuildProxies[symbolType];
  23730. if (!proxySymbol) {
  23731. // Default rect
  23732. symbolType = 'rect';
  23733. proxySymbol = symbolBuildProxies[symbolType];
  23734. }
  23735. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  23736. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  23737. }
  23738. }
  23739. });
  23740. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  23741. function symbolPathSetColor(color, innerColor) {
  23742. if (this.type !== 'image') {
  23743. var symbolStyle = this.style;
  23744. if (this.__isEmptyBrush) {
  23745. symbolStyle.stroke = color;
  23746. symbolStyle.fill = innerColor || '#fff';
  23747. // TODO Same width with lineStyle in LineView
  23748. symbolStyle.lineWidth = 2;
  23749. } else if (this.shape.symbolType === 'line') {
  23750. symbolStyle.stroke = color;
  23751. } else {
  23752. symbolStyle.fill = color;
  23753. }
  23754. this.markRedraw();
  23755. }
  23756. }
  23757. /**
  23758. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  23759. */
  23760. function createSymbol(symbolType, x, y, w, h, color,
  23761. // whether to keep the ratio of w/h,
  23762. keepAspect) {
  23763. // TODO Support image object, DynamicImage.
  23764. var isEmpty = symbolType.indexOf('empty') === 0;
  23765. if (isEmpty) {
  23766. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  23767. }
  23768. var symbolPath;
  23769. if (symbolType.indexOf('image://') === 0) {
  23770. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23771. } else if (symbolType.indexOf('path://') === 0) {
  23772. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23773. } else {
  23774. symbolPath = new SymbolClz({
  23775. shape: {
  23776. symbolType: symbolType,
  23777. x: x,
  23778. y: y,
  23779. width: w,
  23780. height: h
  23781. }
  23782. });
  23783. }
  23784. symbolPath.__isEmptyBrush = isEmpty;
  23785. // TODO Should deprecate setColor
  23786. symbolPath.setColor = symbolPathSetColor;
  23787. if (color) {
  23788. symbolPath.setColor(color);
  23789. }
  23790. return symbolPath;
  23791. }
  23792. function normalizeSymbolSize(symbolSize) {
  23793. if (!isArray(symbolSize)) {
  23794. symbolSize = [+symbolSize, +symbolSize];
  23795. }
  23796. return [symbolSize[0] || 0, symbolSize[1] || 0];
  23797. }
  23798. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  23799. if (symbolOffset == null) {
  23800. return;
  23801. }
  23802. if (!isArray(symbolOffset)) {
  23803. symbolOffset = [symbolOffset, symbolOffset];
  23804. }
  23805. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  23806. }
  23807. function isSafeNum(num) {
  23808. return isFinite(num);
  23809. }
  23810. function createLinearGradient(ctx, obj, rect) {
  23811. var x = obj.x == null ? 0 : obj.x;
  23812. var x2 = obj.x2 == null ? 1 : obj.x2;
  23813. var y = obj.y == null ? 0 : obj.y;
  23814. var y2 = obj.y2 == null ? 0 : obj.y2;
  23815. if (!obj.global) {
  23816. x = x * rect.width + rect.x;
  23817. x2 = x2 * rect.width + rect.x;
  23818. y = y * rect.height + rect.y;
  23819. y2 = y2 * rect.height + rect.y;
  23820. }
  23821. x = isSafeNum(x) ? x : 0;
  23822. x2 = isSafeNum(x2) ? x2 : 1;
  23823. y = isSafeNum(y) ? y : 0;
  23824. y2 = isSafeNum(y2) ? y2 : 0;
  23825. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  23826. return canvasGradient;
  23827. }
  23828. function createRadialGradient(ctx, obj, rect) {
  23829. var width = rect.width;
  23830. var height = rect.height;
  23831. var min = Math.min(width, height);
  23832. var x = obj.x == null ? 0.5 : obj.x;
  23833. var y = obj.y == null ? 0.5 : obj.y;
  23834. var r = obj.r == null ? 0.5 : obj.r;
  23835. if (!obj.global) {
  23836. x = x * width + rect.x;
  23837. y = y * height + rect.y;
  23838. r = r * min;
  23839. }
  23840. x = isSafeNum(x) ? x : 0.5;
  23841. y = isSafeNum(y) ? y : 0.5;
  23842. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  23843. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  23844. return canvasGradient;
  23845. }
  23846. function getCanvasGradient(ctx, obj, rect) {
  23847. var canvasGradient = obj.type === 'radial'
  23848. ? createRadialGradient(ctx, obj, rect)
  23849. : createLinearGradient(ctx, obj, rect);
  23850. var colorStops = obj.colorStops;
  23851. for (var i = 0; i < colorStops.length; i++) {
  23852. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  23853. }
  23854. return canvasGradient;
  23855. }
  23856. function isClipPathChanged(clipPaths, prevClipPaths) {
  23857. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  23858. return false;
  23859. }
  23860. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  23861. return true;
  23862. }
  23863. for (var i = 0; i < clipPaths.length; i++) {
  23864. if (clipPaths[i] !== prevClipPaths[i]) {
  23865. return true;
  23866. }
  23867. }
  23868. return false;
  23869. }
  23870. function parseInt10(val) {
  23871. return parseInt(val, 10);
  23872. }
  23873. function getSize(root, whIdx, opts) {
  23874. var wh = ['width', 'height'][whIdx];
  23875. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  23876. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  23877. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  23878. if (opts[wh] != null && opts[wh] !== 'auto') {
  23879. return parseFloat(opts[wh]);
  23880. }
  23881. var stl = document.defaultView.getComputedStyle(root);
  23882. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  23883. - (parseInt10(stl[plt]) || 0)
  23884. - (parseInt10(stl[prb]) || 0)) | 0;
  23885. }
  23886. function normalizeLineDash(lineType, lineWidth) {
  23887. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  23888. return null;
  23889. }
  23890. return lineType === 'dashed'
  23891. ? [4 * lineWidth, 2 * lineWidth]
  23892. : lineType === 'dotted'
  23893. ? [lineWidth]
  23894. : isNumber(lineType)
  23895. ? [lineType] : isArray(lineType) ? lineType : null;
  23896. }
  23897. function getLineDash(el) {
  23898. var style = el.style;
  23899. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  23900. var lineDashOffset = style.lineDashOffset;
  23901. if (lineDash) {
  23902. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  23903. if (lineScale_1 && lineScale_1 !== 1) {
  23904. lineDash = map(lineDash, function (rawVal) {
  23905. return rawVal / lineScale_1;
  23906. });
  23907. lineDashOffset /= lineScale_1;
  23908. }
  23909. }
  23910. return [lineDash, lineDashOffset];
  23911. }
  23912. var pathProxyForDraw = new PathProxy(true);
  23913. function styleHasStroke(style) {
  23914. var stroke = style.stroke;
  23915. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  23916. }
  23917. function isValidStrokeFillStyle(strokeOrFill) {
  23918. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  23919. }
  23920. function styleHasFill(style) {
  23921. var fill = style.fill;
  23922. return fill != null && fill !== 'none';
  23923. }
  23924. function doFillPath(ctx, style) {
  23925. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  23926. var originalGlobalAlpha = ctx.globalAlpha;
  23927. ctx.globalAlpha = style.fillOpacity * style.opacity;
  23928. ctx.fill();
  23929. ctx.globalAlpha = originalGlobalAlpha;
  23930. }
  23931. else {
  23932. ctx.fill();
  23933. }
  23934. }
  23935. function doStrokePath(ctx, style) {
  23936. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  23937. var originalGlobalAlpha = ctx.globalAlpha;
  23938. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  23939. ctx.stroke();
  23940. ctx.globalAlpha = originalGlobalAlpha;
  23941. }
  23942. else {
  23943. ctx.stroke();
  23944. }
  23945. }
  23946. function createCanvasPattern(ctx, pattern, el) {
  23947. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  23948. if (isImageReady(image)) {
  23949. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  23950. if (typeof DOMMatrix === 'function'
  23951. && canvasPattern
  23952. && canvasPattern.setTransform) {
  23953. var matrix = new DOMMatrix();
  23954. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  23955. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  23956. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  23957. canvasPattern.setTransform(matrix);
  23958. }
  23959. return canvasPattern;
  23960. }
  23961. }
  23962. function brushPath(ctx, el, style, inBatch) {
  23963. var _a;
  23964. var hasStroke = styleHasStroke(style);
  23965. var hasFill = styleHasFill(style);
  23966. var strokePercent = style.strokePercent;
  23967. var strokePart = strokePercent < 1;
  23968. var firstDraw = !el.path;
  23969. if ((!el.silent || strokePart) && firstDraw) {
  23970. el.createPathProxy();
  23971. }
  23972. var path = el.path || pathProxyForDraw;
  23973. var dirtyFlag = el.__dirty;
  23974. if (!inBatch) {
  23975. var fill = style.fill;
  23976. var stroke = style.stroke;
  23977. var hasFillGradient = hasFill && !!fill.colorStops;
  23978. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  23979. var hasFillPattern = hasFill && !!fill.image;
  23980. var hasStrokePattern = hasStroke && !!stroke.image;
  23981. var fillGradient = void 0;
  23982. var strokeGradient = void 0;
  23983. var fillPattern = void 0;
  23984. var strokePattern = void 0;
  23985. var rect = void 0;
  23986. if (hasFillGradient || hasStrokeGradient) {
  23987. rect = el.getBoundingRect();
  23988. }
  23989. if (hasFillGradient) {
  23990. fillGradient = dirtyFlag
  23991. ? getCanvasGradient(ctx, fill, rect)
  23992. : el.__canvasFillGradient;
  23993. el.__canvasFillGradient = fillGradient;
  23994. }
  23995. if (hasStrokeGradient) {
  23996. strokeGradient = dirtyFlag
  23997. ? getCanvasGradient(ctx, stroke, rect)
  23998. : el.__canvasStrokeGradient;
  23999. el.__canvasStrokeGradient = strokeGradient;
  24000. }
  24001. if (hasFillPattern) {
  24002. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  24003. ? createCanvasPattern(ctx, fill, el)
  24004. : el.__canvasFillPattern;
  24005. el.__canvasFillPattern = fillPattern;
  24006. }
  24007. if (hasStrokePattern) {
  24008. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  24009. ? createCanvasPattern(ctx, stroke, el)
  24010. : el.__canvasStrokePattern;
  24011. el.__canvasStrokePattern = fillPattern;
  24012. }
  24013. if (hasFillGradient) {
  24014. ctx.fillStyle = fillGradient;
  24015. }
  24016. else if (hasFillPattern) {
  24017. if (fillPattern) {
  24018. ctx.fillStyle = fillPattern;
  24019. }
  24020. else {
  24021. hasFill = false;
  24022. }
  24023. }
  24024. if (hasStrokeGradient) {
  24025. ctx.strokeStyle = strokeGradient;
  24026. }
  24027. else if (hasStrokePattern) {
  24028. if (strokePattern) {
  24029. ctx.strokeStyle = strokePattern;
  24030. }
  24031. else {
  24032. hasStroke = false;
  24033. }
  24034. }
  24035. }
  24036. var scale = el.getGlobalScale();
  24037. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24038. var lineDash;
  24039. var lineDashOffset;
  24040. if (ctx.setLineDash && style.lineDash) {
  24041. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24042. }
  24043. var needsRebuild = true;
  24044. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  24045. path.setDPR(ctx.dpr);
  24046. if (strokePart) {
  24047. path.setContext(null);
  24048. }
  24049. else {
  24050. path.setContext(ctx);
  24051. needsRebuild = false;
  24052. }
  24053. path.reset();
  24054. el.buildPath(path, el.shape, inBatch);
  24055. path.toStatic();
  24056. el.pathUpdated();
  24057. }
  24058. if (needsRebuild) {
  24059. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24060. }
  24061. if (lineDash) {
  24062. ctx.setLineDash(lineDash);
  24063. ctx.lineDashOffset = lineDashOffset;
  24064. }
  24065. if (!inBatch) {
  24066. if (style.strokeFirst) {
  24067. if (hasStroke) {
  24068. doStrokePath(ctx, style);
  24069. }
  24070. if (hasFill) {
  24071. doFillPath(ctx, style);
  24072. }
  24073. }
  24074. else {
  24075. if (hasFill) {
  24076. doFillPath(ctx, style);
  24077. }
  24078. if (hasStroke) {
  24079. doStrokePath(ctx, style);
  24080. }
  24081. }
  24082. }
  24083. if (lineDash) {
  24084. ctx.setLineDash([]);
  24085. }
  24086. }
  24087. function brushImage(ctx, el, style) {
  24088. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24089. if (!image || !isImageReady(image)) {
  24090. return;
  24091. }
  24092. var x = style.x || 0;
  24093. var y = style.y || 0;
  24094. var width = el.getWidth();
  24095. var height = el.getHeight();
  24096. var aspect = image.width / image.height;
  24097. if (width == null && height != null) {
  24098. width = height * aspect;
  24099. }
  24100. else if (height == null && width != null) {
  24101. height = width / aspect;
  24102. }
  24103. else if (width == null && height == null) {
  24104. width = image.width;
  24105. height = image.height;
  24106. }
  24107. if (style.sWidth && style.sHeight) {
  24108. var sx = style.sx || 0;
  24109. var sy = style.sy || 0;
  24110. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24111. }
  24112. else if (style.sx && style.sy) {
  24113. var sx = style.sx;
  24114. var sy = style.sy;
  24115. var sWidth = width - sx;
  24116. var sHeight = height - sy;
  24117. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24118. }
  24119. else {
  24120. ctx.drawImage(image, x, y, width, height);
  24121. }
  24122. }
  24123. function brushText(ctx, el, style) {
  24124. var _a;
  24125. var text = style.text;
  24126. text != null && (text += '');
  24127. if (text) {
  24128. ctx.font = style.font || DEFAULT_FONT;
  24129. ctx.textAlign = style.textAlign;
  24130. ctx.textBaseline = style.textBaseline;
  24131. var lineDash = void 0;
  24132. var lineDashOffset = void 0;
  24133. if (ctx.setLineDash && style.lineDash) {
  24134. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24135. }
  24136. if (lineDash) {
  24137. ctx.setLineDash(lineDash);
  24138. ctx.lineDashOffset = lineDashOffset;
  24139. }
  24140. if (style.strokeFirst) {
  24141. if (styleHasStroke(style)) {
  24142. ctx.strokeText(text, style.x, style.y);
  24143. }
  24144. if (styleHasFill(style)) {
  24145. ctx.fillText(text, style.x, style.y);
  24146. }
  24147. }
  24148. else {
  24149. if (styleHasFill(style)) {
  24150. ctx.fillText(text, style.x, style.y);
  24151. }
  24152. if (styleHasStroke(style)) {
  24153. ctx.strokeText(text, style.x, style.y);
  24154. }
  24155. }
  24156. if (lineDash) {
  24157. ctx.setLineDash([]);
  24158. }
  24159. }
  24160. }
  24161. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24162. var STROKE_PROPS = [
  24163. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24164. ];
  24165. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24166. var styleChanged = false;
  24167. if (!forceSetAll) {
  24168. prevStyle = prevStyle || {};
  24169. if (style === prevStyle) {
  24170. return false;
  24171. }
  24172. }
  24173. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24174. flushPathDrawn(ctx, scope);
  24175. styleChanged = true;
  24176. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  24177. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  24178. }
  24179. if (forceSetAll || style.blend !== prevStyle.blend) {
  24180. if (!styleChanged) {
  24181. flushPathDrawn(ctx, scope);
  24182. styleChanged = true;
  24183. }
  24184. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24185. }
  24186. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24187. var propName = SHADOW_NUMBER_PROPS[i];
  24188. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24189. if (!styleChanged) {
  24190. flushPathDrawn(ctx, scope);
  24191. styleChanged = true;
  24192. }
  24193. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24194. }
  24195. }
  24196. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24197. if (!styleChanged) {
  24198. flushPathDrawn(ctx, scope);
  24199. styleChanged = true;
  24200. }
  24201. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24202. }
  24203. return styleChanged;
  24204. }
  24205. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24206. var style = getStyle(el, scope.inHover);
  24207. var prevStyle = forceSetAll
  24208. ? null
  24209. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24210. if (style === prevStyle) {
  24211. return false;
  24212. }
  24213. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24214. if (forceSetAll || style.fill !== prevStyle.fill) {
  24215. if (!styleChanged) {
  24216. flushPathDrawn(ctx, scope);
  24217. styleChanged = true;
  24218. }
  24219. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  24220. }
  24221. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24222. if (!styleChanged) {
  24223. flushPathDrawn(ctx, scope);
  24224. styleChanged = true;
  24225. }
  24226. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  24227. }
  24228. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24229. if (!styleChanged) {
  24230. flushPathDrawn(ctx, scope);
  24231. styleChanged = true;
  24232. }
  24233. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24234. }
  24235. if (el.hasStroke()) {
  24236. var lineWidth = style.lineWidth;
  24237. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  24238. if (ctx.lineWidth !== newLineWidth) {
  24239. if (!styleChanged) {
  24240. flushPathDrawn(ctx, scope);
  24241. styleChanged = true;
  24242. }
  24243. ctx.lineWidth = newLineWidth;
  24244. }
  24245. }
  24246. for (var i = 0; i < STROKE_PROPS.length; i++) {
  24247. var prop = STROKE_PROPS[i];
  24248. var propName = prop[0];
  24249. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24250. if (!styleChanged) {
  24251. flushPathDrawn(ctx, scope);
  24252. styleChanged = true;
  24253. }
  24254. ctx[propName] = style[propName] || prop[1];
  24255. }
  24256. }
  24257. return styleChanged;
  24258. }
  24259. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  24260. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  24261. }
  24262. function setContextTransform(ctx, el) {
  24263. var m = el.transform;
  24264. var dpr = ctx.dpr || 1;
  24265. if (m) {
  24266. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  24267. }
  24268. else {
  24269. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  24270. }
  24271. }
  24272. function updateClipStatus(clipPaths, ctx, scope) {
  24273. var allClipped = false;
  24274. for (var i = 0; i < clipPaths.length; i++) {
  24275. var clipPath = clipPaths[i];
  24276. allClipped = allClipped || clipPath.isZeroArea();
  24277. setContextTransform(ctx, clipPath);
  24278. ctx.beginPath();
  24279. clipPath.buildPath(ctx, clipPath.shape);
  24280. ctx.clip();
  24281. }
  24282. scope.allClipped = allClipped;
  24283. }
  24284. function isTransformChanged(m0, m1) {
  24285. if (m0 && m1) {
  24286. return m0[0] !== m1[0]
  24287. || m0[1] !== m1[1]
  24288. || m0[2] !== m1[2]
  24289. || m0[3] !== m1[3]
  24290. || m0[4] !== m1[4]
  24291. || m0[5] !== m1[5];
  24292. }
  24293. else if (!m0 && !m1) {
  24294. return false;
  24295. }
  24296. return true;
  24297. }
  24298. var DRAW_TYPE_PATH = 1;
  24299. var DRAW_TYPE_IMAGE = 2;
  24300. var DRAW_TYPE_TEXT = 3;
  24301. var DRAW_TYPE_INCREMENTAL = 4;
  24302. function canPathBatch(style) {
  24303. var hasFill = styleHasFill(style);
  24304. var hasStroke = styleHasStroke(style);
  24305. return !(style.lineDash
  24306. || !(+hasFill ^ +hasStroke)
  24307. || (hasFill && typeof style.fill !== 'string')
  24308. || (hasStroke && typeof style.stroke !== 'string')
  24309. || style.strokePercent < 1
  24310. || style.strokeOpacity < 1
  24311. || style.fillOpacity < 1);
  24312. }
  24313. function flushPathDrawn(ctx, scope) {
  24314. scope.batchFill && ctx.fill();
  24315. scope.batchStroke && ctx.stroke();
  24316. scope.batchFill = '';
  24317. scope.batchStroke = '';
  24318. }
  24319. function getStyle(el, inHover) {
  24320. return inHover ? (el.__hoverStyle || el.style) : el.style;
  24321. }
  24322. function brushSingle(ctx, el) {
  24323. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  24324. }
  24325. function brush(ctx, el, scope, isLast) {
  24326. var m = el.transform;
  24327. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  24328. el.__dirty &= ~REDRAW_BIT;
  24329. el.__isRendered = false;
  24330. return;
  24331. }
  24332. var clipPaths = el.__clipPaths;
  24333. var prevElClipPaths = scope.prevElClipPaths;
  24334. var forceSetTransform = false;
  24335. var forceSetStyle = false;
  24336. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  24337. if (prevElClipPaths && prevElClipPaths.length) {
  24338. flushPathDrawn(ctx, scope);
  24339. ctx.restore();
  24340. forceSetStyle = forceSetTransform = true;
  24341. scope.prevElClipPaths = null;
  24342. scope.allClipped = false;
  24343. scope.prevEl = null;
  24344. }
  24345. if (clipPaths && clipPaths.length) {
  24346. flushPathDrawn(ctx, scope);
  24347. ctx.save();
  24348. updateClipStatus(clipPaths, ctx, scope);
  24349. forceSetTransform = true;
  24350. }
  24351. scope.prevElClipPaths = clipPaths;
  24352. }
  24353. if (scope.allClipped) {
  24354. el.__isRendered = false;
  24355. return;
  24356. }
  24357. el.beforeBrush && el.beforeBrush();
  24358. el.innerBeforeBrush();
  24359. var prevEl = scope.prevEl;
  24360. if (!prevEl) {
  24361. forceSetStyle = forceSetTransform = true;
  24362. }
  24363. var canBatchPath = el instanceof Path
  24364. && el.autoBatch
  24365. && canPathBatch(el.style);
  24366. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  24367. flushPathDrawn(ctx, scope);
  24368. setContextTransform(ctx, el);
  24369. }
  24370. else if (!canBatchPath) {
  24371. flushPathDrawn(ctx, scope);
  24372. }
  24373. var style = getStyle(el, scope.inHover);
  24374. if (el instanceof Path) {
  24375. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  24376. forceSetStyle = true;
  24377. scope.lastDrawType = DRAW_TYPE_PATH;
  24378. }
  24379. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24380. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  24381. ctx.beginPath();
  24382. }
  24383. brushPath(ctx, el, style, canBatchPath);
  24384. if (canBatchPath) {
  24385. scope.batchFill = style.fill || '';
  24386. scope.batchStroke = style.stroke || '';
  24387. }
  24388. }
  24389. else {
  24390. if (el instanceof TSpan) {
  24391. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  24392. forceSetStyle = true;
  24393. scope.lastDrawType = DRAW_TYPE_TEXT;
  24394. }
  24395. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24396. brushText(ctx, el, style);
  24397. }
  24398. else if (el instanceof ZRImage) {
  24399. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  24400. forceSetStyle = true;
  24401. scope.lastDrawType = DRAW_TYPE_IMAGE;
  24402. }
  24403. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  24404. brushImage(ctx, el, style);
  24405. }
  24406. else if (el.getTemporalDisplayables) {
  24407. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  24408. forceSetStyle = true;
  24409. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  24410. }
  24411. brushIncremental(ctx, el, scope);
  24412. }
  24413. }
  24414. if (canBatchPath && isLast) {
  24415. flushPathDrawn(ctx, scope);
  24416. }
  24417. el.innerAfterBrush();
  24418. el.afterBrush && el.afterBrush();
  24419. scope.prevEl = el;
  24420. el.__dirty = 0;
  24421. el.__isRendered = true;
  24422. }
  24423. function brushIncremental(ctx, el, scope) {
  24424. var displayables = el.getDisplayables();
  24425. var temporalDisplayables = el.getTemporalDisplayables();
  24426. ctx.save();
  24427. var innerScope = {
  24428. prevElClipPaths: null,
  24429. prevEl: null,
  24430. allClipped: false,
  24431. viewWidth: scope.viewWidth,
  24432. viewHeight: scope.viewHeight,
  24433. inHover: scope.inHover
  24434. };
  24435. var i;
  24436. var len;
  24437. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  24438. var displayable = displayables[i];
  24439. displayable.beforeBrush && displayable.beforeBrush();
  24440. displayable.innerBeforeBrush();
  24441. brush(ctx, displayable, innerScope, i === len - 1);
  24442. displayable.innerAfterBrush();
  24443. displayable.afterBrush && displayable.afterBrush();
  24444. innerScope.prevEl = displayable;
  24445. }
  24446. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  24447. var displayable = temporalDisplayables[i_1];
  24448. displayable.beforeBrush && displayable.beforeBrush();
  24449. displayable.innerBeforeBrush();
  24450. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  24451. displayable.innerAfterBrush();
  24452. displayable.afterBrush && displayable.afterBrush();
  24453. innerScope.prevEl = displayable;
  24454. }
  24455. el.clearTemporalDisplayables();
  24456. el.notClear = true;
  24457. ctx.restore();
  24458. }
  24459. var decalMap = new WeakMap();
  24460. var decalCache = new LRU(100);
  24461. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  24462. /**
  24463. * Create or update pattern image from decal options
  24464. *
  24465. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  24466. * @return {Pattern} pattern with generated image, null if no decal
  24467. */
  24468. function createOrUpdatePatternFromDecal(decalObject, api) {
  24469. if (decalObject === 'none') {
  24470. return null;
  24471. }
  24472. var dpr = api.getDevicePixelRatio();
  24473. var zr = api.getZr();
  24474. var isSVG = zr.painter.type === 'svg';
  24475. if (decalObject.dirty) {
  24476. decalMap["delete"](decalObject);
  24477. }
  24478. var oldPattern = decalMap.get(decalObject);
  24479. if (oldPattern) {
  24480. return oldPattern;
  24481. }
  24482. var decalOpt = defaults(decalObject, {
  24483. symbol: 'rect',
  24484. symbolSize: 1,
  24485. symbolKeepAspect: true,
  24486. color: 'rgba(0, 0, 0, 0.2)',
  24487. backgroundColor: null,
  24488. dashArrayX: 5,
  24489. dashArrayY: 5,
  24490. rotation: 0,
  24491. maxTileWidth: 512,
  24492. maxTileHeight: 512
  24493. });
  24494. if (decalOpt.backgroundColor === 'none') {
  24495. decalOpt.backgroundColor = null;
  24496. }
  24497. var pattern = {
  24498. repeat: 'repeat'
  24499. };
  24500. setPatternnSource(pattern);
  24501. pattern.rotation = decalOpt.rotation;
  24502. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  24503. decalMap.set(decalObject, pattern);
  24504. decalObject.dirty = false;
  24505. return pattern;
  24506. function setPatternnSource(pattern) {
  24507. var keys = [dpr];
  24508. var isValidKey = true;
  24509. for (var i = 0; i < decalKeys.length; ++i) {
  24510. var value = decalOpt[decalKeys[i]];
  24511. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  24512. isValidKey = false;
  24513. break;
  24514. }
  24515. keys.push(value);
  24516. }
  24517. var cacheKey;
  24518. if (isValidKey) {
  24519. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  24520. var cache = decalCache.get(cacheKey);
  24521. if (cache) {
  24522. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  24523. }
  24524. }
  24525. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  24526. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  24527. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  24528. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  24529. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  24530. var canvas = !isSVG && platformApi.createCanvas();
  24531. var svgRoot = isSVG && {
  24532. tag: 'g',
  24533. attrs: {},
  24534. key: 'dcl',
  24535. children: []
  24536. };
  24537. var pSize = getPatternSize();
  24538. var ctx;
  24539. if (canvas) {
  24540. canvas.width = pSize.width * dpr;
  24541. canvas.height = pSize.height * dpr;
  24542. ctx = canvas.getContext('2d');
  24543. }
  24544. brushDecal();
  24545. if (isValidKey) {
  24546. decalCache.put(cacheKey, canvas || svgRoot);
  24547. }
  24548. pattern.image = canvas;
  24549. pattern.svgElement = svgRoot;
  24550. pattern.svgWidth = pSize.width;
  24551. pattern.svgHeight = pSize.height;
  24552. /**
  24553. * Get minimum length that can make a repeatable pattern.
  24554. *
  24555. * @return {Object} pattern width and height
  24556. */
  24557. function getPatternSize() {
  24558. /**
  24559. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  24560. * |--- --- --- --- --- ...
  24561. * |-- -- -- -- -- -- -- -- ...
  24562. * |--- --- --- --- --- ...
  24563. * |-- -- -- -- -- -- -- -- ...
  24564. * So the minimum length of X is 15,
  24565. * which is the least common multiple of `3 + 2` and `2 + 1`
  24566. * |--- --- --- |--- --- ...
  24567. * |-- -- -- -- -- |-- -- -- ...
  24568. */
  24569. var width = 1;
  24570. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  24571. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  24572. }
  24573. var symbolRepeats = 1;
  24574. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  24575. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  24576. }
  24577. width *= symbolRepeats;
  24578. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  24579. if ("development" !== 'production') {
  24580. var warn = function (attrName) {
  24581. /* eslint-disable-next-line */
  24582. 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.");
  24583. };
  24584. if (width > decalOpt.maxTileWidth) {
  24585. warn('maxTileWidth');
  24586. }
  24587. if (height > decalOpt.maxTileHeight) {
  24588. warn('maxTileHeight');
  24589. }
  24590. }
  24591. return {
  24592. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  24593. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  24594. };
  24595. }
  24596. function brushDecal() {
  24597. if (ctx) {
  24598. ctx.clearRect(0, 0, canvas.width, canvas.height);
  24599. if (decalOpt.backgroundColor) {
  24600. ctx.fillStyle = decalOpt.backgroundColor;
  24601. ctx.fillRect(0, 0, canvas.width, canvas.height);
  24602. }
  24603. }
  24604. var ySum = 0;
  24605. for (var i = 0; i < dashArrayY.length; ++i) {
  24606. ySum += dashArrayY[i];
  24607. }
  24608. if (ySum <= 0) {
  24609. // dashArrayY is 0, draw nothing
  24610. return;
  24611. }
  24612. var y = -lineBlockLengthY;
  24613. var yId = 0;
  24614. var yIdTotal = 0;
  24615. var xId0 = 0;
  24616. while (y < pSize.height) {
  24617. if (yId % 2 === 0) {
  24618. var symbolYId = yIdTotal / 2 % symbolArray.length;
  24619. var x = 0;
  24620. var xId1 = 0;
  24621. var xId1Total = 0;
  24622. while (x < pSize.width * 2) {
  24623. var xSum = 0;
  24624. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  24625. xSum += dashArrayX[xId0][i];
  24626. }
  24627. if (xSum <= 0) {
  24628. // Skip empty line
  24629. break;
  24630. }
  24631. // E.g., [15, 5, 20, 5] draws only for 15 and 20
  24632. if (xId1 % 2 === 0) {
  24633. var size = (1 - decalOpt.symbolSize) * 0.5;
  24634. var left = x + dashArrayX[xId0][xId1] * size;
  24635. var top_1 = y + dashArrayY[yId] * size;
  24636. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  24637. var height = dashArrayY[yId] * decalOpt.symbolSize;
  24638. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  24639. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  24640. }
  24641. x += dashArrayX[xId0][xId1];
  24642. ++xId1Total;
  24643. ++xId1;
  24644. if (xId1 === dashArrayX[xId0].length) {
  24645. xId1 = 0;
  24646. }
  24647. }
  24648. ++xId0;
  24649. if (xId0 === dashArrayX.length) {
  24650. xId0 = 0;
  24651. }
  24652. }
  24653. y += dashArrayY[yId];
  24654. ++yIdTotal;
  24655. ++yId;
  24656. if (yId === dashArrayY.length) {
  24657. yId = 0;
  24658. }
  24659. }
  24660. function brushSymbol(x, y, width, height, symbolType) {
  24661. var scale = isSVG ? 1 : dpr;
  24662. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  24663. if (isSVG) {
  24664. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  24665. if (symbolVNode) {
  24666. svgRoot.children.push(symbolVNode);
  24667. }
  24668. } else {
  24669. // Paint to canvas for all other renderers.
  24670. brushSingle(ctx, symbol);
  24671. }
  24672. }
  24673. }
  24674. }
  24675. }
  24676. /**
  24677. * Convert symbol array into normalized array
  24678. *
  24679. * @param {string | (string | string[])[]} symbol symbol input
  24680. * @return {string[][]} normolized symbol array
  24681. */
  24682. function normalizeSymbolArray(symbol) {
  24683. if (!symbol || symbol.length === 0) {
  24684. return [['rect']];
  24685. }
  24686. if (isString(symbol)) {
  24687. return [[symbol]];
  24688. }
  24689. var isAllString = true;
  24690. for (var i = 0; i < symbol.length; ++i) {
  24691. if (!isString(symbol[i])) {
  24692. isAllString = false;
  24693. break;
  24694. }
  24695. }
  24696. if (isAllString) {
  24697. return normalizeSymbolArray([symbol]);
  24698. }
  24699. var result = [];
  24700. for (var i = 0; i < symbol.length; ++i) {
  24701. if (isString(symbol[i])) {
  24702. result.push([symbol[i]]);
  24703. } else {
  24704. result.push(symbol[i]);
  24705. }
  24706. }
  24707. return result;
  24708. }
  24709. /**
  24710. * Convert dash input into dashArray
  24711. *
  24712. * @param {DecalDashArrayX} dash dash input
  24713. * @return {number[][]} normolized dash array
  24714. */
  24715. function normalizeDashArrayX(dash) {
  24716. if (!dash || dash.length === 0) {
  24717. return [[0, 0]];
  24718. }
  24719. if (isNumber(dash)) {
  24720. var dashValue = Math.ceil(dash);
  24721. return [[dashValue, dashValue]];
  24722. }
  24723. /**
  24724. * [20, 5] should be normalized into [[20, 5]],
  24725. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  24726. */
  24727. var isAllNumber = true;
  24728. for (var i = 0; i < dash.length; ++i) {
  24729. if (!isNumber(dash[i])) {
  24730. isAllNumber = false;
  24731. break;
  24732. }
  24733. }
  24734. if (isAllNumber) {
  24735. return normalizeDashArrayX([dash]);
  24736. }
  24737. var result = [];
  24738. for (var i = 0; i < dash.length; ++i) {
  24739. if (isNumber(dash[i])) {
  24740. var dashValue = Math.ceil(dash[i]);
  24741. result.push([dashValue, dashValue]);
  24742. } else {
  24743. var dashValue = map(dash[i], function (n) {
  24744. return Math.ceil(n);
  24745. });
  24746. if (dashValue.length % 2 === 1) {
  24747. // [4, 2, 1] means |---- - -- |---- - -- |
  24748. // so normalize it to be [4, 2, 1, 4, 2, 1]
  24749. result.push(dashValue.concat(dashValue));
  24750. } else {
  24751. result.push(dashValue);
  24752. }
  24753. }
  24754. }
  24755. return result;
  24756. }
  24757. /**
  24758. * Convert dash input into dashArray
  24759. *
  24760. * @param {DecalDashArrayY} dash dash input
  24761. * @return {number[]} normolized dash array
  24762. */
  24763. function normalizeDashArrayY(dash) {
  24764. if (!dash || typeof dash === 'object' && dash.length === 0) {
  24765. return [0, 0];
  24766. }
  24767. if (isNumber(dash)) {
  24768. var dashValue_1 = Math.ceil(dash);
  24769. return [dashValue_1, dashValue_1];
  24770. }
  24771. var dashValue = map(dash, function (n) {
  24772. return Math.ceil(n);
  24773. });
  24774. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  24775. }
  24776. /**
  24777. * Get block length of each line. A block is the length of dash line and space.
  24778. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  24779. * that, so the block length of this line is 5.
  24780. *
  24781. * @param {number[][]} dash dash array of X or Y
  24782. * @return {number[]} block length of each line
  24783. */
  24784. function getLineBlockLengthX(dash) {
  24785. return map(dash, function (line) {
  24786. return getLineBlockLengthY(line);
  24787. });
  24788. }
  24789. function getLineBlockLengthY(dash) {
  24790. var blockLength = 0;
  24791. for (var i = 0; i < dash.length; ++i) {
  24792. blockLength += dash[i];
  24793. }
  24794. if (dash.length % 2 === 1) {
  24795. // [4, 2, 1] means |---- - -- |---- - -- |
  24796. // So total length is (4 + 2 + 1) * 2
  24797. return blockLength * 2;
  24798. }
  24799. return blockLength;
  24800. }
  24801. function decalVisual(ecModel, api) {
  24802. ecModel.eachRawSeries(function (seriesModel) {
  24803. if (ecModel.isSeriesFiltered(seriesModel)) {
  24804. return;
  24805. }
  24806. var data = seriesModel.getData();
  24807. if (data.hasItemVisual()) {
  24808. data.each(function (idx) {
  24809. var decal = data.getItemVisual(idx, 'decal');
  24810. if (decal) {
  24811. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  24812. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  24813. }
  24814. });
  24815. }
  24816. var decal = data.getVisual('decal');
  24817. if (decal) {
  24818. var style = data.getVisual('style');
  24819. style.decal = createOrUpdatePatternFromDecal(decal, api);
  24820. }
  24821. });
  24822. }
  24823. var lifecycle = new Eventful();
  24824. // Implementation of exported APIs. For example registerMap, getMap.
  24825. // The implementations will be registered when installing the component.
  24826. // Avoid these code being bundled to the core module.
  24827. var implsStore = {};
  24828. // TODO Type
  24829. function registerImpl(name, impl) {
  24830. if ("development" !== 'production') {
  24831. if (implsStore[name]) {
  24832. error("Already has an implementation of " + name + ".");
  24833. }
  24834. }
  24835. implsStore[name] = impl;
  24836. }
  24837. function getImpl(name) {
  24838. if ("development" !== 'production') {
  24839. if (!implsStore[name]) {
  24840. error("Implementation of " + name + " doesn't exists.");
  24841. }
  24842. }
  24843. return implsStore[name];
  24844. }
  24845. var version$1 = '5.5.1';
  24846. var dependencies = {
  24847. zrender: '5.6.0'
  24848. };
  24849. var TEST_FRAME_REMAIN_TIME = 1;
  24850. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24851. // Some data processors depends on the stack result dimension (to calculate data extent).
  24852. // So data stack stage should be in front of data processing stage.
  24853. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24854. // "Data filter" will block the stream, so it should be
  24855. // put at the beginning of data processing.
  24856. var PRIORITY_PROCESSOR_FILTER = 1000;
  24857. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  24858. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24859. var PRIORITY_VISUAL_LAYOUT = 1000;
  24860. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24861. var PRIORITY_VISUAL_GLOBAL = 2000;
  24862. var PRIORITY_VISUAL_CHART = 3000;
  24863. var PRIORITY_VISUAL_COMPONENT = 4000;
  24864. // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  24865. // overwrite the viusal result of component (like `visualMap`)
  24866. // using data item specific setting (like itemStyle.xxx on data item)
  24867. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500;
  24868. // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  24869. // visual result like `symbolSize`.
  24870. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  24871. var PRIORITY_VISUAL_BRUSH = 5000;
  24872. var PRIORITY_VISUAL_ARIA = 6000;
  24873. var PRIORITY_VISUAL_DECAL = 7000;
  24874. var PRIORITY = {
  24875. PROCESSOR: {
  24876. FILTER: PRIORITY_PROCESSOR_FILTER,
  24877. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24878. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24879. },
  24880. VISUAL: {
  24881. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24882. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24883. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24884. CHART: PRIORITY_VISUAL_CHART,
  24885. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24886. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24887. BRUSH: PRIORITY_VISUAL_BRUSH,
  24888. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  24889. ARIA: PRIORITY_VISUAL_ARIA,
  24890. DECAL: PRIORITY_VISUAL_DECAL
  24891. }
  24892. };
  24893. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24894. // where they must not be invoked nestedly, except the only case: invoke
  24895. // dispatchAction with updateMethod "none" in main process.
  24896. // This flag is used to carry out this rule.
  24897. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24898. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  24899. var PENDING_UPDATE = '__pendingUpdate';
  24900. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  24901. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24902. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  24903. var CONNECT_STATUS_PENDING = 0;
  24904. var CONNECT_STATUS_UPDATING = 1;
  24905. var CONNECT_STATUS_UPDATED = 2;
  24906. function createRegisterEventWithLowercaseECharts(method) {
  24907. return function () {
  24908. var args = [];
  24909. for (var _i = 0; _i < arguments.length; _i++) {
  24910. args[_i] = arguments[_i];
  24911. }
  24912. if (this.isDisposed()) {
  24913. disposedWarning(this.id);
  24914. return;
  24915. }
  24916. return toLowercaseNameAndCallEventful(this, method, args);
  24917. };
  24918. }
  24919. function createRegisterEventWithLowercaseMessageCenter(method) {
  24920. return function () {
  24921. var args = [];
  24922. for (var _i = 0; _i < arguments.length; _i++) {
  24923. args[_i] = arguments[_i];
  24924. }
  24925. return toLowercaseNameAndCallEventful(this, method, args);
  24926. };
  24927. }
  24928. function toLowercaseNameAndCallEventful(host, method, args) {
  24929. // `args[0]` is event name. Event name is all lowercase.
  24930. args[0] = args[0] && args[0].toLowerCase();
  24931. return Eventful.prototype[method].apply(host, args);
  24932. }
  24933. var MessageCenter = /** @class */function (_super) {
  24934. __extends(MessageCenter, _super);
  24935. function MessageCenter() {
  24936. return _super !== null && _super.apply(this, arguments) || this;
  24937. }
  24938. return MessageCenter;
  24939. }(Eventful);
  24940. var messageCenterProto = MessageCenter.prototype;
  24941. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  24942. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off');
  24943. // ---------------------------------------
  24944. // Internal method names for class ECharts
  24945. // ---------------------------------------
  24946. var prepare;
  24947. var prepareView;
  24948. var updateDirectly;
  24949. var updateMethods;
  24950. var doConvertPixel;
  24951. var updateStreamModes;
  24952. var doDispatchAction;
  24953. var flushPendingActions;
  24954. var triggerUpdatedEvent;
  24955. var bindRenderedEvent;
  24956. var bindMouseEvent;
  24957. var render;
  24958. var renderComponents;
  24959. var renderSeries;
  24960. var createExtensionAPI;
  24961. var enableConnect;
  24962. var markStatusToUpdate;
  24963. var applyChangedStates;
  24964. var ECharts = /** @class */function (_super) {
  24965. __extends(ECharts, _super);
  24966. function ECharts(dom,
  24967. // Theme name or themeOption.
  24968. theme, opts) {
  24969. var _this = _super.call(this, new ECEventProcessor()) || this;
  24970. _this._chartsViews = [];
  24971. _this._chartsMap = {};
  24972. _this._componentsViews = [];
  24973. _this._componentsMap = {};
  24974. // Can't dispatch action during rendering procedure
  24975. _this._pendingActions = [];
  24976. opts = opts || {};
  24977. // Get theme by name
  24978. if (isString(theme)) {
  24979. theme = themeStorage[theme];
  24980. }
  24981. _this._dom = dom;
  24982. var defaultRenderer = 'canvas';
  24983. var defaultCoarsePointer = 'auto';
  24984. var defaultUseDirtyRect = false;
  24985. if ("development" !== 'production') {
  24986. var root = /* eslint-disable-next-line */
  24987. env.hasGlobalWindow ? window : global;
  24988. if (root) {
  24989. defaultRenderer = retrieve2(root.__ECHARTS__DEFAULT__RENDERER__, defaultRenderer);
  24990. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  24991. defaultUseDirtyRect = retrieve2(root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__, defaultUseDirtyRect);
  24992. }
  24993. }
  24994. if (opts.ssr) {
  24995. registerSSRDataGetter(function (el) {
  24996. var ecData = getECData(el);
  24997. var dataIndex = ecData.dataIndex;
  24998. if (dataIndex == null) {
  24999. return;
  25000. }
  25001. var hashMap = createHashMap();
  25002. hashMap.set('series_index', ecData.seriesIndex);
  25003. hashMap.set('data_index', dataIndex);
  25004. ecData.ssrType && hashMap.set('ssr_type', ecData.ssrType);
  25005. return hashMap;
  25006. });
  25007. }
  25008. var zr = _this._zr = init(dom, {
  25009. renderer: opts.renderer || defaultRenderer,
  25010. devicePixelRatio: opts.devicePixelRatio,
  25011. width: opts.width,
  25012. height: opts.height,
  25013. ssr: opts.ssr,
  25014. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  25015. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  25016. pointerSize: opts.pointerSize
  25017. });
  25018. _this._ssr = opts.ssr;
  25019. // Expect 60 fps.
  25020. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25021. theme = clone(theme);
  25022. theme && globalBackwardCompat(theme, true);
  25023. _this._theme = theme;
  25024. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25025. _this._coordSysMgr = new CoordinateSystemManager();
  25026. var api = _this._api = createExtensionAPI(_this);
  25027. // Sort on demand
  25028. function prioritySortFunc(a, b) {
  25029. return a.__prio - b.__prio;
  25030. }
  25031. sort(visualFuncs, prioritySortFunc);
  25032. sort(dataProcessorFuncs, prioritySortFunc);
  25033. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25034. _this._messageCenter = new MessageCenter();
  25035. // Init mouse events
  25036. _this._initEvents();
  25037. // In case some people write `window.onresize = chart.resize`
  25038. _this.resize = bind(_this.resize, _this);
  25039. zr.animation.on('frame', _this._onframe, _this);
  25040. bindRenderedEvent(zr, _this);
  25041. bindMouseEvent(zr, _this);
  25042. // ECharts instance can be used as value.
  25043. setAsPrimitive(_this);
  25044. return _this;
  25045. }
  25046. ECharts.prototype._onframe = function () {
  25047. if (this._disposed) {
  25048. return;
  25049. }
  25050. applyChangedStates(this);
  25051. var scheduler = this._scheduler;
  25052. // Lazy update
  25053. if (this[PENDING_UPDATE]) {
  25054. var silent = this[PENDING_UPDATE].silent;
  25055. this[IN_MAIN_PROCESS_KEY] = true;
  25056. try {
  25057. prepare(this);
  25058. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  25059. } catch (e) {
  25060. this[IN_MAIN_PROCESS_KEY] = false;
  25061. this[PENDING_UPDATE] = null;
  25062. throw e;
  25063. }
  25064. // At present, in each frame, zrender performs:
  25065. // (1) animation step forward.
  25066. // (2) trigger('frame') (where this `_onframe` is called)
  25067. // (3) zrender flush (render).
  25068. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25069. // will render the final state of the elements before the real animation started.
  25070. this._zr.flush();
  25071. this[IN_MAIN_PROCESS_KEY] = false;
  25072. this[PENDING_UPDATE] = null;
  25073. flushPendingActions.call(this, silent);
  25074. triggerUpdatedEvent.call(this, silent);
  25075. }
  25076. // Avoid do both lazy update and progress in one frame.
  25077. else if (scheduler.unfinished) {
  25078. // Stream progress.
  25079. var remainTime = TEST_FRAME_REMAIN_TIME;
  25080. var ecModel = this._model;
  25081. var api = this._api;
  25082. scheduler.unfinished = false;
  25083. do {
  25084. var startTime = +new Date();
  25085. scheduler.performSeriesTasks(ecModel);
  25086. // Currently dataProcessorFuncs do not check threshold.
  25087. scheduler.performDataProcessorTasks(ecModel);
  25088. updateStreamModes(this, ecModel);
  25089. // Do not update coordinate system here. Because that coord system update in
  25090. // each frame is not a good user experience. So we follow the rule that
  25091. // the extent of the coordinate system is determined in the first frame (the
  25092. // frame is executed immediately after task reset.
  25093. // this._coordSysMgr.update(ecModel, api);
  25094. // console.log('--- ec frame visual ---', remainTime);
  25095. scheduler.performVisualTasks(ecModel);
  25096. renderSeries(this, this._model, api, 'remain', {});
  25097. remainTime -= +new Date() - startTime;
  25098. } while (remainTime > 0 && scheduler.unfinished);
  25099. // Call flush explicitly for trigger finished event.
  25100. if (!scheduler.unfinished) {
  25101. this._zr.flush();
  25102. }
  25103. // Else, zr flushing be ensue within the same frame,
  25104. // because zr flushing is after onframe event.
  25105. }
  25106. };
  25107. ECharts.prototype.getDom = function () {
  25108. return this._dom;
  25109. };
  25110. ECharts.prototype.getId = function () {
  25111. return this.id;
  25112. };
  25113. ECharts.prototype.getZr = function () {
  25114. return this._zr;
  25115. };
  25116. ECharts.prototype.isSSR = function () {
  25117. return this._ssr;
  25118. };
  25119. /* eslint-disable-next-line */
  25120. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  25121. if (this[IN_MAIN_PROCESS_KEY]) {
  25122. if ("development" !== 'production') {
  25123. error('`setOption` should not be called during main process.');
  25124. }
  25125. return;
  25126. }
  25127. if (this._disposed) {
  25128. disposedWarning(this.id);
  25129. return;
  25130. }
  25131. var silent;
  25132. var replaceMerge;
  25133. var transitionOpt;
  25134. if (isObject(notMerge)) {
  25135. lazyUpdate = notMerge.lazyUpdate;
  25136. silent = notMerge.silent;
  25137. replaceMerge = notMerge.replaceMerge;
  25138. transitionOpt = notMerge.transition;
  25139. notMerge = notMerge.notMerge;
  25140. }
  25141. this[IN_MAIN_PROCESS_KEY] = true;
  25142. if (!this._model || notMerge) {
  25143. var optionManager = new OptionManager(this._api);
  25144. var theme = this._theme;
  25145. var ecModel = this._model = new GlobalModel();
  25146. ecModel.scheduler = this._scheduler;
  25147. ecModel.ssr = this._ssr;
  25148. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25149. }
  25150. this._model.setOption(option, {
  25151. replaceMerge: replaceMerge
  25152. }, optionPreprocessorFuncs);
  25153. var updateParams = {
  25154. seriesTransition: transitionOpt,
  25155. optionChanged: true
  25156. };
  25157. if (lazyUpdate) {
  25158. this[PENDING_UPDATE] = {
  25159. silent: silent,
  25160. updateParams: updateParams
  25161. };
  25162. this[IN_MAIN_PROCESS_KEY] = false;
  25163. // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25164. // It should wake it up to make sure zrender start to render at the next frame.
  25165. this.getZr().wakeUp();
  25166. } else {
  25167. try {
  25168. prepare(this);
  25169. updateMethods.update.call(this, null, updateParams);
  25170. } catch (e) {
  25171. this[PENDING_UPDATE] = null;
  25172. this[IN_MAIN_PROCESS_KEY] = false;
  25173. throw e;
  25174. }
  25175. // Ensure zr refresh sychronously, and then pixel in canvas can be
  25176. // fetched after `setOption`.
  25177. if (!this._ssr) {
  25178. // not use flush when using ssr mode.
  25179. this._zr.flush();
  25180. }
  25181. this[PENDING_UPDATE] = null;
  25182. this[IN_MAIN_PROCESS_KEY] = false;
  25183. flushPendingActions.call(this, silent);
  25184. triggerUpdatedEvent.call(this, silent);
  25185. }
  25186. };
  25187. /**
  25188. * @deprecated
  25189. */
  25190. ECharts.prototype.setTheme = function () {
  25191. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25192. };
  25193. // We don't want developers to use getModel directly.
  25194. ECharts.prototype.getModel = function () {
  25195. return this._model;
  25196. };
  25197. ECharts.prototype.getOption = function () {
  25198. return this._model && this._model.getOption();
  25199. };
  25200. ECharts.prototype.getWidth = function () {
  25201. return this._zr.getWidth();
  25202. };
  25203. ECharts.prototype.getHeight = function () {
  25204. return this._zr.getHeight();
  25205. };
  25206. ECharts.prototype.getDevicePixelRatio = function () {
  25207. return this._zr.painter.dpr
  25208. /* eslint-disable-next-line */ || env.hasGlobalWindow && window.devicePixelRatio || 1;
  25209. };
  25210. /**
  25211. * Get canvas which has all thing rendered
  25212. * @deprecated Use renderToCanvas instead.
  25213. */
  25214. ECharts.prototype.getRenderedCanvas = function (opts) {
  25215. if ("development" !== 'production') {
  25216. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  25217. }
  25218. return this.renderToCanvas(opts);
  25219. };
  25220. ECharts.prototype.renderToCanvas = function (opts) {
  25221. opts = opts || {};
  25222. var painter = this._zr.painter;
  25223. if ("development" !== 'production') {
  25224. if (painter.type !== 'canvas') {
  25225. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  25226. }
  25227. }
  25228. return painter.getRenderedCanvas({
  25229. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  25230. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  25231. });
  25232. };
  25233. ECharts.prototype.renderToSVGString = function (opts) {
  25234. opts = opts || {};
  25235. var painter = this._zr.painter;
  25236. if ("development" !== 'production') {
  25237. if (painter.type !== 'svg') {
  25238. throw new Error('renderToSVGString can only be used in the svg renderer.');
  25239. }
  25240. }
  25241. return painter.renderToString({
  25242. useViewBox: opts.useViewBox
  25243. });
  25244. };
  25245. /**
  25246. * Get svg data url
  25247. */
  25248. ECharts.prototype.getSvgDataURL = function () {
  25249. if (!env.svgSupported) {
  25250. return;
  25251. }
  25252. var zr = this._zr;
  25253. var list = zr.storage.getDisplayList();
  25254. // Stop animations
  25255. each(list, function (el) {
  25256. el.stopAnimation(null, true);
  25257. });
  25258. return zr.painter.toDataURL();
  25259. };
  25260. ECharts.prototype.getDataURL = function (opts) {
  25261. if (this._disposed) {
  25262. disposedWarning(this.id);
  25263. return;
  25264. }
  25265. opts = opts || {};
  25266. var excludeComponents = opts.excludeComponents;
  25267. var ecModel = this._model;
  25268. var excludesComponentViews = [];
  25269. var self = this;
  25270. each(excludeComponents, function (componentType) {
  25271. ecModel.eachComponent({
  25272. mainType: componentType
  25273. }, function (component) {
  25274. var view = self._componentsMap[component.__viewId];
  25275. if (!view.group.ignore) {
  25276. excludesComponentViews.push(view);
  25277. view.group.ignore = true;
  25278. }
  25279. });
  25280. });
  25281. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  25282. each(excludesComponentViews, function (view) {
  25283. view.group.ignore = false;
  25284. });
  25285. return url;
  25286. };
  25287. ECharts.prototype.getConnectedDataURL = function (opts) {
  25288. if (this._disposed) {
  25289. disposedWarning(this.id);
  25290. return;
  25291. }
  25292. var isSvg = opts.type === 'svg';
  25293. var groupId = this.group;
  25294. var mathMin = Math.min;
  25295. var mathMax = Math.max;
  25296. var MAX_NUMBER = Infinity;
  25297. if (connectedGroups[groupId]) {
  25298. var left_1 = MAX_NUMBER;
  25299. var top_1 = MAX_NUMBER;
  25300. var right_1 = -MAX_NUMBER;
  25301. var bottom_1 = -MAX_NUMBER;
  25302. var canvasList_1 = [];
  25303. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  25304. each(instances$1, function (chart, id) {
  25305. if (chart.group === groupId) {
  25306. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  25307. var boundingRect = chart.getDom().getBoundingClientRect();
  25308. left_1 = mathMin(boundingRect.left, left_1);
  25309. top_1 = mathMin(boundingRect.top, top_1);
  25310. right_1 = mathMax(boundingRect.right, right_1);
  25311. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  25312. canvasList_1.push({
  25313. dom: canvas,
  25314. left: boundingRect.left,
  25315. top: boundingRect.top
  25316. });
  25317. }
  25318. });
  25319. left_1 *= dpr_1;
  25320. top_1 *= dpr_1;
  25321. right_1 *= dpr_1;
  25322. bottom_1 *= dpr_1;
  25323. var width = right_1 - left_1;
  25324. var height = bottom_1 - top_1;
  25325. var targetCanvas = platformApi.createCanvas();
  25326. var zr_1 = init(targetCanvas, {
  25327. renderer: isSvg ? 'svg' : 'canvas'
  25328. });
  25329. zr_1.resize({
  25330. width: width,
  25331. height: height
  25332. });
  25333. if (isSvg) {
  25334. var content_1 = '';
  25335. each(canvasList_1, function (item) {
  25336. var x = item.left - left_1;
  25337. var y = item.top - top_1;
  25338. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  25339. });
  25340. zr_1.painter.getSvgRoot().innerHTML = content_1;
  25341. if (opts.connectedBackgroundColor) {
  25342. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  25343. }
  25344. zr_1.refreshImmediately();
  25345. return zr_1.painter.toDataURL();
  25346. } else {
  25347. // Background between the charts
  25348. if (opts.connectedBackgroundColor) {
  25349. zr_1.add(new Rect({
  25350. shape: {
  25351. x: 0,
  25352. y: 0,
  25353. width: width,
  25354. height: height
  25355. },
  25356. style: {
  25357. fill: opts.connectedBackgroundColor
  25358. }
  25359. }));
  25360. }
  25361. each(canvasList_1, function (item) {
  25362. var img = new ZRImage({
  25363. style: {
  25364. x: item.left * dpr_1 - left_1,
  25365. y: item.top * dpr_1 - top_1,
  25366. image: item.dom
  25367. }
  25368. });
  25369. zr_1.add(img);
  25370. });
  25371. zr_1.refreshImmediately();
  25372. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  25373. }
  25374. } else {
  25375. return this.getDataURL(opts);
  25376. }
  25377. };
  25378. ECharts.prototype.convertToPixel = function (finder, value) {
  25379. return doConvertPixel(this, 'convertToPixel', finder, value);
  25380. };
  25381. ECharts.prototype.convertFromPixel = function (finder, value) {
  25382. return doConvertPixel(this, 'convertFromPixel', finder, value);
  25383. };
  25384. /**
  25385. * Is the specified coordinate systems or components contain the given pixel point.
  25386. * @param {Array|number} value
  25387. * @return {boolean} result
  25388. */
  25389. ECharts.prototype.containPixel = function (finder, value) {
  25390. if (this._disposed) {
  25391. disposedWarning(this.id);
  25392. return;
  25393. }
  25394. var ecModel = this._model;
  25395. var result;
  25396. var findResult = parseFinder(ecModel, finder);
  25397. each(findResult, function (models, key) {
  25398. key.indexOf('Models') >= 0 && each(models, function (model) {
  25399. var coordSys = model.coordinateSystem;
  25400. if (coordSys && coordSys.containPoint) {
  25401. result = result || !!coordSys.containPoint(value);
  25402. } else if (key === 'seriesModels') {
  25403. var view = this._chartsMap[model.__viewId];
  25404. if (view && view.containPoint) {
  25405. result = result || view.containPoint(value, model);
  25406. } else {
  25407. if ("development" !== 'production') {
  25408. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  25409. }
  25410. }
  25411. } else {
  25412. if ("development" !== 'production') {
  25413. warn(key + ': containPoint is not supported');
  25414. }
  25415. }
  25416. }, this);
  25417. }, this);
  25418. return !!result;
  25419. };
  25420. /**
  25421. * Get visual from series or data.
  25422. * @param finder
  25423. * If string, e.g., 'series', means {seriesIndex: 0}.
  25424. * If Object, could contain some of these properties below:
  25425. * {
  25426. * seriesIndex / seriesId / seriesName,
  25427. * dataIndex / dataIndexInside
  25428. * }
  25429. * If dataIndex is not specified, series visual will be fetched,
  25430. * but not data item visual.
  25431. * If all of seriesIndex, seriesId, seriesName are not specified,
  25432. * visual will be fetched from first series.
  25433. * @param visualType 'color', 'symbol', 'symbolSize'
  25434. */
  25435. ECharts.prototype.getVisual = function (finder, visualType) {
  25436. var ecModel = this._model;
  25437. var parsedFinder = parseFinder(ecModel, finder, {
  25438. defaultMainType: 'series'
  25439. });
  25440. var seriesModel = parsedFinder.seriesModel;
  25441. if ("development" !== 'production') {
  25442. if (!seriesModel) {
  25443. warn('There is no specified series model');
  25444. }
  25445. }
  25446. var data = seriesModel.getData();
  25447. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  25448. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  25449. };
  25450. /**
  25451. * Get view of corresponding component model
  25452. */
  25453. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  25454. return this._componentsMap[componentModel.__viewId];
  25455. };
  25456. /**
  25457. * Get view of corresponding series model
  25458. */
  25459. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  25460. return this._chartsMap[seriesModel.__viewId];
  25461. };
  25462. ECharts.prototype._initEvents = function () {
  25463. var _this = this;
  25464. each(MOUSE_EVENT_NAMES, function (eveName) {
  25465. var handler = function (e) {
  25466. var ecModel = _this.getModel();
  25467. var el = e.target;
  25468. var params;
  25469. var isGlobalOut = eveName === 'globalout';
  25470. // no e.target when 'globalout'.
  25471. if (isGlobalOut) {
  25472. params = {};
  25473. } else {
  25474. el && findEventDispatcher(el, function (parent) {
  25475. var ecData = getECData(parent);
  25476. if (ecData && ecData.dataIndex != null) {
  25477. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  25478. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType, el) || {};
  25479. return true;
  25480. }
  25481. // If element has custom eventData of components
  25482. else if (ecData.eventData) {
  25483. params = extend({}, ecData.eventData);
  25484. return true;
  25485. }
  25486. }, true);
  25487. }
  25488. // Contract: if params prepared in mouse event,
  25489. // these properties must be specified:
  25490. // {
  25491. // componentType: string (component main type)
  25492. // componentIndex: number
  25493. // }
  25494. // Otherwise event query can not work.
  25495. if (params) {
  25496. var componentType = params.componentType;
  25497. var componentIndex = params.componentIndex;
  25498. // Special handling for historic reason: when trigger by
  25499. // markLine/markPoint/markArea, the componentType is
  25500. // 'markLine'/'markPoint'/'markArea', but we should better
  25501. // enable them to be queried by seriesIndex, since their
  25502. // option is set in each series.
  25503. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  25504. componentType = 'series';
  25505. componentIndex = params.seriesIndex;
  25506. }
  25507. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  25508. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  25509. if ("development" !== 'production') {
  25510. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25511. // be missed, otherwise there is no way to distinguish source component.
  25512. // See `dataFormat.getDataParams`.
  25513. if (!isGlobalOut && !(model && view)) {
  25514. warn('model or view can not be found by params');
  25515. }
  25516. }
  25517. params.event = e;
  25518. params.type = eveName;
  25519. _this._$eventProcessor.eventInfo = {
  25520. targetEl: el,
  25521. packedEvent: params,
  25522. model: model,
  25523. view: view
  25524. };
  25525. _this.trigger(eveName, params);
  25526. }
  25527. };
  25528. // Consider that some component (like tooltip, brush, ...)
  25529. // register zr event handler, but user event handler might
  25530. // do anything, such as call `setOption` or `dispatchAction`,
  25531. // which probably update any of the content and probably
  25532. // cause problem if it is called previous other inner handlers.
  25533. handler.zrEventfulCallAtLast = true;
  25534. _this._zr.on(eveName, handler, _this);
  25535. });
  25536. each(eventActionMap, function (actionType, eventType) {
  25537. _this._messageCenter.on(eventType, function (event) {
  25538. this.trigger(eventType, event);
  25539. }, _this);
  25540. });
  25541. // Extra events
  25542. // TODO register?
  25543. each(['selectchanged'], function (eventType) {
  25544. _this._messageCenter.on(eventType, function (event) {
  25545. this.trigger(eventType, event);
  25546. }, _this);
  25547. });
  25548. handleLegacySelectEvents(this._messageCenter, this, this._api);
  25549. };
  25550. ECharts.prototype.isDisposed = function () {
  25551. return this._disposed;
  25552. };
  25553. ECharts.prototype.clear = function () {
  25554. if (this._disposed) {
  25555. disposedWarning(this.id);
  25556. return;
  25557. }
  25558. this.setOption({
  25559. series: []
  25560. }, true);
  25561. };
  25562. ECharts.prototype.dispose = function () {
  25563. if (this._disposed) {
  25564. disposedWarning(this.id);
  25565. return;
  25566. }
  25567. this._disposed = true;
  25568. var dom = this.getDom();
  25569. if (dom) {
  25570. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25571. }
  25572. var chart = this;
  25573. var api = chart._api;
  25574. var ecModel = chart._model;
  25575. each(chart._componentsViews, function (component) {
  25576. component.dispose(ecModel, api);
  25577. });
  25578. each(chart._chartsViews, function (chart) {
  25579. chart.dispose(ecModel, api);
  25580. });
  25581. // Dispose after all views disposed
  25582. chart._zr.dispose();
  25583. // Set properties to null.
  25584. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  25585. chart._dom = chart._model = chart._chartsMap = chart._componentsMap = chart._chartsViews = chart._componentsViews = chart._scheduler = chart._api = chart._zr = chart._throttledZrFlush = chart._theme = chart._coordSysMgr = chart._messageCenter = null;
  25586. delete instances$1[chart.id];
  25587. };
  25588. /**
  25589. * Resize the chart
  25590. */
  25591. ECharts.prototype.resize = function (opts) {
  25592. if (this[IN_MAIN_PROCESS_KEY]) {
  25593. if ("development" !== 'production') {
  25594. error('`resize` should not be called during main process.');
  25595. }
  25596. return;
  25597. }
  25598. if (this._disposed) {
  25599. disposedWarning(this.id);
  25600. return;
  25601. }
  25602. this._zr.resize(opts);
  25603. var ecModel = this._model;
  25604. // Resize loading effect
  25605. this._loadingFX && this._loadingFX.resize();
  25606. if (!ecModel) {
  25607. return;
  25608. }
  25609. var needPrepare = ecModel.resetOption('media');
  25610. var silent = opts && opts.silent;
  25611. // There is some real cases that:
  25612. // chart.setOption(option, { lazyUpdate: true });
  25613. // chart.resize();
  25614. if (this[PENDING_UPDATE]) {
  25615. if (silent == null) {
  25616. silent = this[PENDING_UPDATE].silent;
  25617. }
  25618. needPrepare = true;
  25619. this[PENDING_UPDATE] = null;
  25620. }
  25621. this[IN_MAIN_PROCESS_KEY] = true;
  25622. try {
  25623. needPrepare && prepare(this);
  25624. updateMethods.update.call(this, {
  25625. type: 'resize',
  25626. animation: extend({
  25627. // Disable animation
  25628. duration: 0
  25629. }, opts && opts.animation)
  25630. });
  25631. } catch (e) {
  25632. this[IN_MAIN_PROCESS_KEY] = false;
  25633. throw e;
  25634. }
  25635. this[IN_MAIN_PROCESS_KEY] = false;
  25636. flushPendingActions.call(this, silent);
  25637. triggerUpdatedEvent.call(this, silent);
  25638. };
  25639. ECharts.prototype.showLoading = function (name, cfg) {
  25640. if (this._disposed) {
  25641. disposedWarning(this.id);
  25642. return;
  25643. }
  25644. if (isObject(name)) {
  25645. cfg = name;
  25646. name = '';
  25647. }
  25648. name = name || 'default';
  25649. this.hideLoading();
  25650. if (!loadingEffects[name]) {
  25651. if ("development" !== 'production') {
  25652. warn('Loading effects ' + name + ' not exists.');
  25653. }
  25654. return;
  25655. }
  25656. var el = loadingEffects[name](this._api, cfg);
  25657. var zr = this._zr;
  25658. this._loadingFX = el;
  25659. zr.add(el);
  25660. };
  25661. /**
  25662. * Hide loading effect
  25663. */
  25664. ECharts.prototype.hideLoading = function () {
  25665. if (this._disposed) {
  25666. disposedWarning(this.id);
  25667. return;
  25668. }
  25669. this._loadingFX && this._zr.remove(this._loadingFX);
  25670. this._loadingFX = null;
  25671. };
  25672. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  25673. var payload = extend({}, eventObj);
  25674. payload.type = eventActionMap[eventObj.type];
  25675. return payload;
  25676. };
  25677. /**
  25678. * @param opt If pass boolean, means opt.silent
  25679. * @param opt.silent Default `false`. Whether trigger events.
  25680. * @param opt.flush Default `undefined`.
  25681. * true: Flush immediately, and then pixel in canvas can be fetched
  25682. * immediately. Caution: it might affect performance.
  25683. * false: Not flush.
  25684. * undefined: Auto decide whether perform flush.
  25685. */
  25686. ECharts.prototype.dispatchAction = function (payload, opt) {
  25687. if (this._disposed) {
  25688. disposedWarning(this.id);
  25689. return;
  25690. }
  25691. if (!isObject(opt)) {
  25692. opt = {
  25693. silent: !!opt
  25694. };
  25695. }
  25696. if (!actions[payload.type]) {
  25697. return;
  25698. }
  25699. // Avoid dispatch action before setOption. Especially in `connect`.
  25700. if (!this._model) {
  25701. return;
  25702. }
  25703. // May dispatchAction in rendering procedure
  25704. if (this[IN_MAIN_PROCESS_KEY]) {
  25705. this._pendingActions.push(payload);
  25706. return;
  25707. }
  25708. var silent = opt.silent;
  25709. doDispatchAction.call(this, payload, silent);
  25710. var flush = opt.flush;
  25711. if (flush) {
  25712. this._zr.flush();
  25713. } else if (flush !== false && env.browser.weChat) {
  25714. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  25715. // hang when sliding page (on touch event), which cause that zr does not
  25716. // refresh until user interaction finished, which is not expected.
  25717. // But `dispatchAction` may be called too frequently when pan on touch
  25718. // screen, which impacts performance if do not throttle them.
  25719. this._throttledZrFlush();
  25720. }
  25721. flushPendingActions.call(this, silent);
  25722. triggerUpdatedEvent.call(this, silent);
  25723. };
  25724. ECharts.prototype.updateLabelLayout = function () {
  25725. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  25726. // Not adding series labels.
  25727. // TODO
  25728. updatedSeries: []
  25729. });
  25730. };
  25731. ECharts.prototype.appendData = function (params) {
  25732. if (this._disposed) {
  25733. disposedWarning(this.id);
  25734. return;
  25735. }
  25736. var seriesIndex = params.seriesIndex;
  25737. var ecModel = this.getModel();
  25738. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25739. if ("development" !== 'production') {
  25740. assert(params.data && seriesModel);
  25741. }
  25742. seriesModel.appendData(params);
  25743. // Note: `appendData` does not support that update extent of coordinate
  25744. // system, util some scenario require that. In the expected usage of
  25745. // `appendData`, the initial extent of coordinate system should better
  25746. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25747. // the extent changed while `appendData`, the location of the painted
  25748. // graphic elements have to be changed, which make the usage of
  25749. // `appendData` meaningless.
  25750. this._scheduler.unfinished = true;
  25751. this.getZr().wakeUp();
  25752. };
  25753. // A work around for no `internal` modifier in ts yet but
  25754. // need to strictly hide private methods to JS users.
  25755. ECharts.internalField = function () {
  25756. prepare = function (ecIns) {
  25757. var scheduler = ecIns._scheduler;
  25758. scheduler.restorePipelines(ecIns._model);
  25759. scheduler.prepareStageTasks();
  25760. prepareView(ecIns, true);
  25761. prepareView(ecIns, false);
  25762. scheduler.plan();
  25763. };
  25764. /**
  25765. * Prepare view instances of charts and components
  25766. */
  25767. prepareView = function (ecIns, isComponent) {
  25768. var ecModel = ecIns._model;
  25769. var scheduler = ecIns._scheduler;
  25770. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25771. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25772. var zr = ecIns._zr;
  25773. var api = ecIns._api;
  25774. for (var i = 0; i < viewList.length; i++) {
  25775. viewList[i].__alive = false;
  25776. }
  25777. isComponent ? ecModel.eachComponent(function (componentType, model) {
  25778. componentType !== 'series' && doPrepare(model);
  25779. }) : ecModel.eachSeries(doPrepare);
  25780. function doPrepare(model) {
  25781. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  25782. // mode and need to enable transition animation. (Usually, when they have the same id, or
  25783. // especially no id but have the same type & name & index. See the `model.id` generation
  25784. // rule in `makeIdAndName` and `viewId` generation rule here).
  25785. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  25786. // the new model has nothing to do with the old model.
  25787. var requireNewView = model.__requireNewView;
  25788. // This command should not work twice.
  25789. model.__requireNewView = false;
  25790. // Consider: id same and type changed.
  25791. var viewId = '_ec_' + model.id + '_' + model.type;
  25792. var view = !requireNewView && viewMap[viewId];
  25793. if (!view) {
  25794. var classType = parseClassType(model.type);
  25795. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) :
  25796. // FIXME:TS
  25797. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  25798. // For backward compat, still support a chart type declared as only subType
  25799. // like "liquidfill", but recommend "series.liquidfill"
  25800. // But need a base class to make a type series.
  25801. ChartView.getClass(classType.sub);
  25802. if ("development" !== 'production') {
  25803. assert(Clazz, classType.sub + ' does not exist.');
  25804. }
  25805. view = new Clazz();
  25806. view.init(ecModel, api);
  25807. viewMap[viewId] = view;
  25808. viewList.push(view);
  25809. zr.add(view.group);
  25810. }
  25811. model.__viewId = view.__id = viewId;
  25812. view.__alive = true;
  25813. view.__model = model;
  25814. view.group.__ecComponentInfo = {
  25815. mainType: model.mainType,
  25816. index: model.componentIndex
  25817. };
  25818. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25819. }
  25820. for (var i = 0; i < viewList.length;) {
  25821. var view = viewList[i];
  25822. if (!view.__alive) {
  25823. !isComponent && view.renderTask.dispose();
  25824. zr.remove(view.group);
  25825. view.dispose(ecModel, api);
  25826. viewList.splice(i, 1);
  25827. if (viewMap[view.__id] === view) {
  25828. delete viewMap[view.__id];
  25829. }
  25830. view.__id = view.group.__ecComponentInfo = null;
  25831. } else {
  25832. i++;
  25833. }
  25834. }
  25835. };
  25836. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  25837. var ecModel = ecIns._model;
  25838. ecModel.setUpdatePayload(payload);
  25839. // broadcast
  25840. if (!mainType) {
  25841. // FIXME
  25842. // Chart will not be update directly here, except set dirty.
  25843. // But there is no such scenario now.
  25844. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  25845. return;
  25846. }
  25847. var query = {};
  25848. query[mainType + 'Id'] = payload[mainType + 'Id'];
  25849. query[mainType + 'Index'] = payload[mainType + 'Index'];
  25850. query[mainType + 'Name'] = payload[mainType + 'Name'];
  25851. var condition = {
  25852. mainType: mainType,
  25853. query: query
  25854. };
  25855. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  25856. var excludeSeriesId = payload.excludeSeriesId;
  25857. var excludeSeriesIdMap;
  25858. if (excludeSeriesId != null) {
  25859. excludeSeriesIdMap = createHashMap();
  25860. each(normalizeToArray(excludeSeriesId), function (id) {
  25861. var modelId = convertOptionIdName(id, null);
  25862. if (modelId != null) {
  25863. excludeSeriesIdMap.set(modelId, true);
  25864. }
  25865. });
  25866. }
  25867. // If dispatchAction before setOption, do nothing.
  25868. ecModel && ecModel.eachComponent(condition, function (model) {
  25869. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  25870. if (isExcluded) {
  25871. return;
  25872. }
  25873. if (isHighDownPayload(payload)) {
  25874. if (model instanceof SeriesModel) {
  25875. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  25876. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  25877. }
  25878. } else {
  25879. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  25880. focusSelf = _a.focusSelf,
  25881. dispatchers = _a.dispatchers;
  25882. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  25883. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  25884. }
  25885. // PENDING:
  25886. // Whether to put this "enter emphasis" code in `ComponentView`,
  25887. // which will be the same as `ChartView` but might be not necessary
  25888. // and will be far from this logic.
  25889. if (dispatchers) {
  25890. each(dispatchers, function (dispatcher) {
  25891. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  25892. });
  25893. }
  25894. }
  25895. } else if (isSelectChangePayload(payload)) {
  25896. // TODO geo
  25897. if (model instanceof SeriesModel) {
  25898. toggleSelectionFromPayload(model, payload, ecIns._api);
  25899. updateSeriesElementSelection(model);
  25900. markStatusToUpdate(ecIns);
  25901. }
  25902. }
  25903. }, ecIns);
  25904. ecModel && ecModel.eachComponent(condition, function (model) {
  25905. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  25906. if (isExcluded) {
  25907. return;
  25908. }
  25909. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  25910. }, ecIns);
  25911. function callView(view) {
  25912. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  25913. }
  25914. };
  25915. updateMethods = {
  25916. prepareAndUpdate: function (payload) {
  25917. prepare(this);
  25918. updateMethods.update.call(this, payload, {
  25919. // Needs to mark option changed if newOption is given.
  25920. // It's from MagicType.
  25921. // TODO If use a separate flag optionChanged in payload?
  25922. optionChanged: payload.newOption != null
  25923. });
  25924. },
  25925. update: function (payload, updateParams) {
  25926. var ecModel = this._model;
  25927. var api = this._api;
  25928. var zr = this._zr;
  25929. var coordSysMgr = this._coordSysMgr;
  25930. var scheduler = this._scheduler;
  25931. // update before setOption
  25932. if (!ecModel) {
  25933. return;
  25934. }
  25935. ecModel.setUpdatePayload(payload);
  25936. scheduler.restoreData(ecModel, payload);
  25937. scheduler.performSeriesTasks(ecModel);
  25938. // TODO
  25939. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  25940. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  25941. // Create new coordinate system each update
  25942. // In LineView may save the old coordinate system and use it to get the original point.
  25943. coordSysMgr.create(ecModel, api);
  25944. scheduler.performDataProcessorTasks(ecModel, payload);
  25945. // Current stream render is not supported in data process. So we can update
  25946. // stream modes after data processing, where the filtered data is used to
  25947. // determine whether to use progressive rendering.
  25948. updateStreamModes(this, ecModel);
  25949. // We update stream modes before coordinate system updated, then the modes info
  25950. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  25951. // the drawback is the full coord info can not be fetched. Fortunately this full
  25952. // coord is not required in stream mode updater currently.
  25953. coordSysMgr.update(ecModel, api);
  25954. clearColorPalette(ecModel);
  25955. scheduler.performVisualTasks(ecModel, payload);
  25956. render(this, ecModel, api, payload, updateParams);
  25957. // Set background
  25958. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  25959. var darkMode = ecModel.get('darkMode');
  25960. zr.setBackgroundColor(backgroundColor);
  25961. // Force set dark mode.
  25962. if (darkMode != null && darkMode !== 'auto') {
  25963. zr.setDarkMode(darkMode);
  25964. }
  25965. lifecycle.trigger('afterupdate', ecModel, api);
  25966. },
  25967. updateTransform: function (payload) {
  25968. var _this = this;
  25969. var ecModel = this._model;
  25970. var api = this._api;
  25971. // update before setOption
  25972. if (!ecModel) {
  25973. return;
  25974. }
  25975. ecModel.setUpdatePayload(payload);
  25976. // ChartView.markUpdateMethod(payload, 'updateTransform');
  25977. var componentDirtyList = [];
  25978. ecModel.eachComponent(function (componentType, componentModel) {
  25979. if (componentType === 'series') {
  25980. return;
  25981. }
  25982. var componentView = _this.getViewOfComponentModel(componentModel);
  25983. if (componentView && componentView.__alive) {
  25984. if (componentView.updateTransform) {
  25985. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  25986. result && result.update && componentDirtyList.push(componentView);
  25987. } else {
  25988. componentDirtyList.push(componentView);
  25989. }
  25990. }
  25991. });
  25992. var seriesDirtyMap = createHashMap();
  25993. ecModel.eachSeries(function (seriesModel) {
  25994. var chartView = _this._chartsMap[seriesModel.__viewId];
  25995. if (chartView.updateTransform) {
  25996. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  25997. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  25998. } else {
  25999. seriesDirtyMap.set(seriesModel.uid, 1);
  26000. }
  26001. });
  26002. clearColorPalette(ecModel);
  26003. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26004. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  26005. this._scheduler.performVisualTasks(ecModel, payload, {
  26006. setDirty: true,
  26007. dirtyMap: seriesDirtyMap
  26008. });
  26009. // Currently, not call render of components. Geo render cost a lot.
  26010. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  26011. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  26012. lifecycle.trigger('afterupdate', ecModel, api);
  26013. },
  26014. updateView: function (payload) {
  26015. var ecModel = this._model;
  26016. // update before setOption
  26017. if (!ecModel) {
  26018. return;
  26019. }
  26020. ecModel.setUpdatePayload(payload);
  26021. ChartView.markUpdateMethod(payload, 'updateView');
  26022. clearColorPalette(ecModel);
  26023. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26024. this._scheduler.performVisualTasks(ecModel, payload, {
  26025. setDirty: true
  26026. });
  26027. render(this, ecModel, this._api, payload, {});
  26028. lifecycle.trigger('afterupdate', ecModel, this._api);
  26029. },
  26030. updateVisual: function (payload) {
  26031. // updateMethods.update.call(this, payload);
  26032. var _this = this;
  26033. var ecModel = this._model;
  26034. // update before setOption
  26035. if (!ecModel) {
  26036. return;
  26037. }
  26038. ecModel.setUpdatePayload(payload);
  26039. // clear all visual
  26040. ecModel.eachSeries(function (seriesModel) {
  26041. seriesModel.getData().clearAllVisual();
  26042. });
  26043. // Perform visual
  26044. ChartView.markUpdateMethod(payload, 'updateVisual');
  26045. clearColorPalette(ecModel);
  26046. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26047. this._scheduler.performVisualTasks(ecModel, payload, {
  26048. visualType: 'visual',
  26049. setDirty: true
  26050. });
  26051. ecModel.eachComponent(function (componentType, componentModel) {
  26052. if (componentType !== 'series') {
  26053. var componentView = _this.getViewOfComponentModel(componentModel);
  26054. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26055. }
  26056. });
  26057. ecModel.eachSeries(function (seriesModel) {
  26058. var chartView = _this._chartsMap[seriesModel.__viewId];
  26059. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26060. });
  26061. lifecycle.trigger('afterupdate', ecModel, this._api);
  26062. },
  26063. updateLayout: function (payload) {
  26064. updateMethods.update.call(this, payload);
  26065. }
  26066. };
  26067. doConvertPixel = function (ecIns, methodName, finder, value) {
  26068. if (ecIns._disposed) {
  26069. disposedWarning(ecIns.id);
  26070. return;
  26071. }
  26072. var ecModel = ecIns._model;
  26073. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26074. var result;
  26075. var parsedFinder = parseFinder(ecModel, finder);
  26076. for (var i = 0; i < coordSysList.length; i++) {
  26077. var coordSys = coordSysList[i];
  26078. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26079. return result;
  26080. }
  26081. }
  26082. if ("development" !== 'production') {
  26083. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26084. }
  26085. };
  26086. updateStreamModes = function (ecIns, ecModel) {
  26087. var chartsMap = ecIns._chartsMap;
  26088. var scheduler = ecIns._scheduler;
  26089. ecModel.eachSeries(function (seriesModel) {
  26090. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26091. });
  26092. };
  26093. doDispatchAction = function (payload, silent) {
  26094. var _this = this;
  26095. var ecModel = this.getModel();
  26096. var payloadType = payload.type;
  26097. var escapeConnect = payload.escapeConnect;
  26098. var actionWrap = actions[payloadType];
  26099. var actionInfo = actionWrap.actionInfo;
  26100. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  26101. var updateMethod = cptTypeTmp.pop();
  26102. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  26103. this[IN_MAIN_PROCESS_KEY] = true;
  26104. var payloads = [payload];
  26105. var batched = false;
  26106. // Batch action
  26107. if (payload.batch) {
  26108. batched = true;
  26109. payloads = map(payload.batch, function (item) {
  26110. item = defaults(extend({}, item), payload);
  26111. item.batch = null;
  26112. return item;
  26113. });
  26114. }
  26115. var eventObjBatch = [];
  26116. var eventObj;
  26117. var isSelectChange = isSelectChangePayload(payload);
  26118. var isHighDown = isHighDownPayload(payload);
  26119. // Only leave blur once if there are multiple batches.
  26120. if (isHighDown) {
  26121. allLeaveBlur(this._api);
  26122. }
  26123. each(payloads, function (batchItem) {
  26124. // Action can specify the event by return it.
  26125. eventObj = actionWrap.action(batchItem, _this._model, _this._api);
  26126. // Emit event outside
  26127. eventObj = eventObj || extend({}, batchItem);
  26128. // Convert type to eventType
  26129. eventObj.type = actionInfo.event || eventObj.type;
  26130. eventObjBatch.push(eventObj);
  26131. // light update does not perform data process, layout and visual.
  26132. if (isHighDown) {
  26133. var _a = preParseFinder(payload),
  26134. queryOptionMap = _a.queryOptionMap,
  26135. mainTypeSpecified = _a.mainTypeSpecified;
  26136. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  26137. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  26138. markStatusToUpdate(_this);
  26139. } else if (isSelectChange) {
  26140. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  26141. // geo still use 'geoselect'.
  26142. updateDirectly(_this, updateMethod, batchItem, 'series');
  26143. markStatusToUpdate(_this);
  26144. } else if (cptType) {
  26145. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  26146. }
  26147. });
  26148. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  26149. try {
  26150. // Still dirty
  26151. if (this[PENDING_UPDATE]) {
  26152. prepare(this);
  26153. updateMethods.update.call(this, payload);
  26154. this[PENDING_UPDATE] = null;
  26155. } else {
  26156. updateMethods[updateMethod].call(this, payload);
  26157. }
  26158. } catch (e) {
  26159. this[IN_MAIN_PROCESS_KEY] = false;
  26160. throw e;
  26161. }
  26162. }
  26163. // Follow the rule of action batch
  26164. if (batched) {
  26165. eventObj = {
  26166. type: actionInfo.event || payloadType,
  26167. escapeConnect: escapeConnect,
  26168. batch: eventObjBatch
  26169. };
  26170. } else {
  26171. eventObj = eventObjBatch[0];
  26172. }
  26173. this[IN_MAIN_PROCESS_KEY] = false;
  26174. if (!silent) {
  26175. var messageCenter = this._messageCenter;
  26176. messageCenter.trigger(eventObj.type, eventObj);
  26177. // Extra triggered 'selectchanged' event
  26178. if (isSelectChange) {
  26179. var newObj = {
  26180. type: 'selectchanged',
  26181. escapeConnect: escapeConnect,
  26182. selected: getAllSelectedIndices(ecModel),
  26183. isFromClick: payload.isFromClick || false,
  26184. fromAction: payload.type,
  26185. fromActionPayload: payload
  26186. };
  26187. messageCenter.trigger(newObj.type, newObj);
  26188. }
  26189. }
  26190. };
  26191. flushPendingActions = function (silent) {
  26192. var pendingActions = this._pendingActions;
  26193. while (pendingActions.length) {
  26194. var payload = pendingActions.shift();
  26195. doDispatchAction.call(this, payload, silent);
  26196. }
  26197. };
  26198. triggerUpdatedEvent = function (silent) {
  26199. !silent && this.trigger('updated');
  26200. };
  26201. /**
  26202. * Event `rendered` is triggered when zr
  26203. * rendered. It is useful for realtime
  26204. * snapshot (reflect animation).
  26205. *
  26206. * Event `finished` is triggered when:
  26207. * (1) zrender rendering finished.
  26208. * (2) initial animation finished.
  26209. * (3) progressive rendering finished.
  26210. * (4) no pending action.
  26211. * (5) no delayed setOption needs to be processed.
  26212. */
  26213. bindRenderedEvent = function (zr, ecIns) {
  26214. zr.on('rendered', function (params) {
  26215. ecIns.trigger('rendered', params);
  26216. // The `finished` event should not be triggered repeatedly,
  26217. // so it should only be triggered when rendering indeed happens
  26218. // in zrender. (Consider the case that dipatchAction is keep
  26219. // triggering when mouse move).
  26220. if (
  26221. // Although zr is dirty if initial animation is not finished
  26222. // and this checking is called on frame, we also check
  26223. // animation finished for robustness.
  26224. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  26225. ecIns.trigger('finished');
  26226. }
  26227. });
  26228. };
  26229. bindMouseEvent = function (zr, ecIns) {
  26230. zr.on('mouseover', function (e) {
  26231. var el = e.target;
  26232. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26233. if (dispatcher) {
  26234. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  26235. markStatusToUpdate(ecIns);
  26236. }
  26237. }).on('mouseout', function (e) {
  26238. var el = e.target;
  26239. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26240. if (dispatcher) {
  26241. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  26242. markStatusToUpdate(ecIns);
  26243. }
  26244. }).on('click', function (e) {
  26245. var el = e.target;
  26246. var dispatcher = findEventDispatcher(el, function (target) {
  26247. return getECData(target).dataIndex != null;
  26248. }, true);
  26249. if (dispatcher) {
  26250. var actionType = dispatcher.selected ? 'unselect' : 'select';
  26251. var ecData = getECData(dispatcher);
  26252. ecIns._api.dispatchAction({
  26253. type: actionType,
  26254. dataType: ecData.dataType,
  26255. dataIndexInside: ecData.dataIndex,
  26256. seriesIndex: ecData.seriesIndex,
  26257. isFromClick: true
  26258. });
  26259. }
  26260. });
  26261. };
  26262. function clearColorPalette(ecModel) {
  26263. ecModel.clearColorPalette();
  26264. ecModel.eachSeries(function (seriesModel) {
  26265. seriesModel.clearColorPalette();
  26266. });
  26267. }
  26268. // Allocate zlevels for series and components
  26269. function allocateZlevels(ecModel) {
  26270. var componentZLevels = [];
  26271. var seriesZLevels = [];
  26272. var hasSeparateZLevel = false;
  26273. ecModel.eachComponent(function (componentType, componentModel) {
  26274. var zlevel = componentModel.get('zlevel') || 0;
  26275. var z = componentModel.get('z') || 0;
  26276. var zlevelKey = componentModel.getZLevelKey();
  26277. hasSeparateZLevel = hasSeparateZLevel || !!zlevelKey;
  26278. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  26279. zlevel: zlevel,
  26280. z: z,
  26281. idx: componentModel.componentIndex,
  26282. type: componentType,
  26283. key: zlevelKey
  26284. });
  26285. });
  26286. if (hasSeparateZLevel) {
  26287. // Series after component
  26288. var zLevels = componentZLevels.concat(seriesZLevels);
  26289. var lastSeriesZLevel_1;
  26290. var lastSeriesKey_1;
  26291. sort(zLevels, function (a, b) {
  26292. if (a.zlevel === b.zlevel) {
  26293. return a.z - b.z;
  26294. }
  26295. return a.zlevel - b.zlevel;
  26296. });
  26297. each(zLevels, function (item) {
  26298. var componentModel = ecModel.getComponent(item.type, item.idx);
  26299. var zlevel = item.zlevel;
  26300. var key = item.key;
  26301. if (lastSeriesZLevel_1 != null) {
  26302. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  26303. }
  26304. if (key) {
  26305. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  26306. zlevel++;
  26307. }
  26308. lastSeriesKey_1 = key;
  26309. } else if (lastSeriesKey_1) {
  26310. if (zlevel === lastSeriesZLevel_1) {
  26311. zlevel++;
  26312. }
  26313. lastSeriesKey_1 = '';
  26314. }
  26315. lastSeriesZLevel_1 = zlevel;
  26316. componentModel.setZLevel(zlevel);
  26317. });
  26318. }
  26319. }
  26320. render = function (ecIns, ecModel, api, payload, updateParams) {
  26321. allocateZlevels(ecModel);
  26322. renderComponents(ecIns, ecModel, api, payload, updateParams);
  26323. each(ecIns._chartsViews, function (chart) {
  26324. chart.__alive = false;
  26325. });
  26326. renderSeries(ecIns, ecModel, api, payload, updateParams);
  26327. // Remove groups of unrendered charts
  26328. each(ecIns._chartsViews, function (chart) {
  26329. if (!chart.__alive) {
  26330. chart.remove(ecModel, api);
  26331. }
  26332. });
  26333. };
  26334. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  26335. each(dirtyList || ecIns._componentsViews, function (componentView) {
  26336. var componentModel = componentView.__model;
  26337. clearStates(componentModel, componentView);
  26338. componentView.render(componentModel, ecModel, api, payload);
  26339. updateZ(componentModel, componentView);
  26340. updateStates(componentModel, componentView);
  26341. });
  26342. };
  26343. /**
  26344. * Render each chart and component
  26345. */
  26346. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  26347. // Render all charts
  26348. var scheduler = ecIns._scheduler;
  26349. updateParams = extend(updateParams || {}, {
  26350. updatedSeries: ecModel.getSeries()
  26351. });
  26352. // TODO progressive?
  26353. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  26354. var unfinished = false;
  26355. ecModel.eachSeries(function (seriesModel) {
  26356. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26357. chartView.__alive = true;
  26358. var renderTask = chartView.renderTask;
  26359. scheduler.updatePayload(renderTask, payload);
  26360. // TODO states on marker.
  26361. clearStates(seriesModel, chartView);
  26362. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  26363. renderTask.dirty();
  26364. }
  26365. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  26366. unfinished = true;
  26367. }
  26368. chartView.group.silent = !!seriesModel.get('silent');
  26369. // Should not call markRedraw on group, because it will disable zrender
  26370. // incremental render (always render from the __startIndex each frame)
  26371. // chartView.group.markRedraw();
  26372. updateBlend(seriesModel, chartView);
  26373. updateSeriesElementSelection(seriesModel);
  26374. });
  26375. scheduler.unfinished = unfinished || scheduler.unfinished;
  26376. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams);
  26377. // transition after label is layouted.
  26378. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  26379. ecModel.eachSeries(function (seriesModel) {
  26380. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26381. // Update Z after labels updated. Before applying states.
  26382. updateZ(seriesModel, chartView);
  26383. // NOTE: Update states after label is updated.
  26384. // label should be in normal status when layouting.
  26385. updateStates(seriesModel, chartView);
  26386. });
  26387. // If use hover layer
  26388. updateHoverLayerStatus(ecIns, ecModel);
  26389. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  26390. };
  26391. markStatusToUpdate = function (ecIns) {
  26392. ecIns[STATUS_NEEDS_UPDATE_KEY] = true;
  26393. // Wake up zrender if it's sleep. Let it update states in the next frame.
  26394. ecIns.getZr().wakeUp();
  26395. };
  26396. applyChangedStates = function (ecIns) {
  26397. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  26398. return;
  26399. }
  26400. ecIns.getZr().storage.traverse(function (el) {
  26401. // Not applied on removed elements, it may still in fading.
  26402. if (isElementRemoved(el)) {
  26403. return;
  26404. }
  26405. applyElementStates(el);
  26406. });
  26407. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  26408. };
  26409. function applyElementStates(el) {
  26410. var newStates = [];
  26411. var oldStates = el.currentStates;
  26412. // Keep other states.
  26413. for (var i = 0; i < oldStates.length; i++) {
  26414. var stateName = oldStates[i];
  26415. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  26416. newStates.push(stateName);
  26417. }
  26418. }
  26419. // Only use states when it's exists.
  26420. if (el.selected && el.states.select) {
  26421. newStates.push('select');
  26422. }
  26423. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  26424. newStates.push('emphasis');
  26425. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  26426. newStates.push('blur');
  26427. }
  26428. el.useStates(newStates);
  26429. }
  26430. function updateHoverLayerStatus(ecIns, ecModel) {
  26431. var zr = ecIns._zr;
  26432. var storage = zr.storage;
  26433. var elCount = 0;
  26434. storage.traverse(function (el) {
  26435. if (!el.isGroup) {
  26436. elCount++;
  26437. }
  26438. });
  26439. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  26440. ecModel.eachSeries(function (seriesModel) {
  26441. if (seriesModel.preventUsingHoverLayer) {
  26442. return;
  26443. }
  26444. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26445. if (chartView.__alive) {
  26446. chartView.eachRendered(function (el) {
  26447. if (el.states.emphasis) {
  26448. el.states.emphasis.hoverLayer = true;
  26449. }
  26450. });
  26451. }
  26452. });
  26453. }
  26454. }
  26455. /**
  26456. * Update chart and blend.
  26457. */
  26458. function updateBlend(seriesModel, chartView) {
  26459. var blendMode = seriesModel.get('blendMode') || null;
  26460. chartView.eachRendered(function (el) {
  26461. // FIXME marker and other components
  26462. if (!el.isGroup) {
  26463. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  26464. el.style.blend = blendMode;
  26465. }
  26466. });
  26467. }
  26468. function updateZ(model, view) {
  26469. if (model.preventAutoZ) {
  26470. return;
  26471. }
  26472. var z = model.get('z') || 0;
  26473. var zlevel = model.get('zlevel') || 0;
  26474. // Set z and zlevel
  26475. view.eachRendered(function (el) {
  26476. doUpdateZ(el, z, zlevel, -Infinity);
  26477. // Don't traverse the children because it has been traversed in _updateZ.
  26478. return true;
  26479. });
  26480. }
  26481. function doUpdateZ(el, z, zlevel, maxZ2) {
  26482. // Group may also have textContent
  26483. var label = el.getTextContent();
  26484. var labelLine = el.getTextGuideLine();
  26485. var isGroup = el.isGroup;
  26486. if (isGroup) {
  26487. // set z & zlevel of children elements of Group
  26488. var children = el.childrenRef();
  26489. for (var i = 0; i < children.length; i++) {
  26490. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  26491. }
  26492. } else {
  26493. // not Group
  26494. el.z = z;
  26495. el.zlevel = zlevel;
  26496. maxZ2 = Math.max(el.z2, maxZ2);
  26497. }
  26498. // always set z and zlevel if label/labelLine exists
  26499. if (label) {
  26500. label.z = z;
  26501. label.zlevel = zlevel;
  26502. // lift z2 of text content
  26503. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  26504. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  26505. }
  26506. if (labelLine) {
  26507. var textGuideLineConfig = el.textGuideLineConfig;
  26508. labelLine.z = z;
  26509. labelLine.zlevel = zlevel;
  26510. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  26511. }
  26512. return maxZ2;
  26513. }
  26514. // Clear states without animation.
  26515. // TODO States on component.
  26516. function clearStates(model, view) {
  26517. view.eachRendered(function (el) {
  26518. // Not applied on removed elements, it may still in fading.
  26519. if (isElementRemoved(el)) {
  26520. return;
  26521. }
  26522. var textContent = el.getTextContent();
  26523. var textGuide = el.getTextGuideLine();
  26524. if (el.stateTransition) {
  26525. el.stateTransition = null;
  26526. }
  26527. if (textContent && textContent.stateTransition) {
  26528. textContent.stateTransition = null;
  26529. }
  26530. if (textGuide && textGuide.stateTransition) {
  26531. textGuide.stateTransition = null;
  26532. }
  26533. // TODO If el is incremental.
  26534. if (el.hasState()) {
  26535. el.prevStates = el.currentStates;
  26536. el.clearStates();
  26537. } else if (el.prevStates) {
  26538. el.prevStates = null;
  26539. }
  26540. });
  26541. }
  26542. function updateStates(model, view) {
  26543. var stateAnimationModel = model.getModel('stateAnimation');
  26544. var enableAnimation = model.isAnimationEnabled();
  26545. var duration = stateAnimationModel.get('duration');
  26546. var stateTransition = duration > 0 ? {
  26547. duration: duration,
  26548. delay: stateAnimationModel.get('delay'),
  26549. easing: stateAnimationModel.get('easing')
  26550. // additive: stateAnimationModel.get('additive')
  26551. } : null;
  26552. view.eachRendered(function (el) {
  26553. if (el.states && el.states.emphasis) {
  26554. // Not applied on removed elements, it may still in fading.
  26555. if (isElementRemoved(el)) {
  26556. return;
  26557. }
  26558. if (el instanceof Path) {
  26559. savePathStates(el);
  26560. }
  26561. // Only updated on changed element. In case element is incremental and don't want to rerender.
  26562. // TODO, a more proper way?
  26563. if (el.__dirty) {
  26564. var prevStates = el.prevStates;
  26565. // Restore states without animation
  26566. if (prevStates) {
  26567. el.useStates(prevStates);
  26568. }
  26569. }
  26570. // Update state transition and enable animation again.
  26571. if (enableAnimation) {
  26572. el.stateTransition = stateTransition;
  26573. var textContent = el.getTextContent();
  26574. var textGuide = el.getTextGuideLine();
  26575. // TODO Is it necessary to animate label?
  26576. if (textContent) {
  26577. textContent.stateTransition = stateTransition;
  26578. }
  26579. if (textGuide) {
  26580. textGuide.stateTransition = stateTransition;
  26581. }
  26582. }
  26583. // Use highlighted and selected flag to toggle states.
  26584. if (el.__dirty) {
  26585. applyElementStates(el);
  26586. }
  26587. }
  26588. });
  26589. }
  26590. createExtensionAPI = function (ecIns) {
  26591. return new ( /** @class */function (_super) {
  26592. __extends(class_1, _super);
  26593. function class_1() {
  26594. return _super !== null && _super.apply(this, arguments) || this;
  26595. }
  26596. class_1.prototype.getCoordinateSystems = function () {
  26597. return ecIns._coordSysMgr.getCoordinateSystems();
  26598. };
  26599. class_1.prototype.getComponentByElement = function (el) {
  26600. while (el) {
  26601. var modelInfo = el.__ecComponentInfo;
  26602. if (modelInfo != null) {
  26603. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  26604. }
  26605. el = el.parent;
  26606. }
  26607. };
  26608. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  26609. enterEmphasis(el, highlightDigit);
  26610. markStatusToUpdate(ecIns);
  26611. };
  26612. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  26613. leaveEmphasis(el, highlightDigit);
  26614. markStatusToUpdate(ecIns);
  26615. };
  26616. class_1.prototype.enterBlur = function (el) {
  26617. enterBlur(el);
  26618. markStatusToUpdate(ecIns);
  26619. };
  26620. class_1.prototype.leaveBlur = function (el) {
  26621. leaveBlur(el);
  26622. markStatusToUpdate(ecIns);
  26623. };
  26624. class_1.prototype.enterSelect = function (el) {
  26625. enterSelect(el);
  26626. markStatusToUpdate(ecIns);
  26627. };
  26628. class_1.prototype.leaveSelect = function (el) {
  26629. leaveSelect(el);
  26630. markStatusToUpdate(ecIns);
  26631. };
  26632. class_1.prototype.getModel = function () {
  26633. return ecIns.getModel();
  26634. };
  26635. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  26636. return ecIns.getViewOfComponentModel(componentModel);
  26637. };
  26638. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  26639. return ecIns.getViewOfSeriesModel(seriesModel);
  26640. };
  26641. return class_1;
  26642. }(ExtensionAPI))(ecIns);
  26643. };
  26644. enableConnect = function (chart) {
  26645. function updateConnectedChartsStatus(charts, status) {
  26646. for (var i = 0; i < charts.length; i++) {
  26647. var otherChart = charts[i];
  26648. otherChart[CONNECT_STATUS_KEY] = status;
  26649. }
  26650. }
  26651. each(eventActionMap, function (actionType, eventType) {
  26652. chart._messageCenter.on(eventType, function (event) {
  26653. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  26654. if (event && event.escapeConnect) {
  26655. return;
  26656. }
  26657. var action_1 = chart.makeActionFromEvent(event);
  26658. var otherCharts_1 = [];
  26659. each(instances$1, function (otherChart) {
  26660. if (otherChart !== chart && otherChart.group === chart.group) {
  26661. otherCharts_1.push(otherChart);
  26662. }
  26663. });
  26664. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  26665. each(otherCharts_1, function (otherChart) {
  26666. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  26667. otherChart.dispatchAction(action_1);
  26668. }
  26669. });
  26670. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  26671. }
  26672. });
  26673. });
  26674. };
  26675. }();
  26676. return ECharts;
  26677. }(Eventful);
  26678. var echartsProto = ECharts.prototype;
  26679. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  26680. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  26681. /**
  26682. * @deprecated
  26683. */
  26684. // @ts-ignore
  26685. echartsProto.one = function (eventName, cb, ctx) {
  26686. var self = this;
  26687. deprecateLog('ECharts#one is deprecated.');
  26688. function wrapped() {
  26689. var args2 = [];
  26690. for (var _i = 0; _i < arguments.length; _i++) {
  26691. args2[_i] = arguments[_i];
  26692. }
  26693. cb && cb.apply && cb.apply(this, args2);
  26694. // @ts-ignore
  26695. self.off(eventName, wrapped);
  26696. }
  26697. // @ts-ignore
  26698. this.on.call(this, eventName, wrapped, ctx);
  26699. };
  26700. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  26701. function disposedWarning(id) {
  26702. if ("development" !== 'production') {
  26703. warn('Instance ' + id + ' has been disposed');
  26704. }
  26705. }
  26706. var actions = {};
  26707. /**
  26708. * Map eventType to actionType
  26709. */
  26710. var eventActionMap = {};
  26711. var dataProcessorFuncs = [];
  26712. var optionPreprocessorFuncs = [];
  26713. var visualFuncs = [];
  26714. var themeStorage = {};
  26715. var loadingEffects = {};
  26716. var instances$1 = {};
  26717. var connectedGroups = {};
  26718. var idBase = +new Date() - 0;
  26719. var groupIdBase = +new Date() - 0;
  26720. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  26721. /**
  26722. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  26723. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  26724. * @param opts.width Use clientWidth of the input `dom` by default.
  26725. * Can be 'auto' (the same as null/undefined)
  26726. * @param opts.height Use clientHeight of the input `dom` by default.
  26727. * Can be 'auto' (the same as null/undefined)
  26728. * @param opts.locale Specify the locale.
  26729. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  26730. */
  26731. function init$1(dom, theme, opts) {
  26732. var isClient = !(opts && opts.ssr);
  26733. if (isClient) {
  26734. if ("development" !== 'production') {
  26735. if (!dom) {
  26736. throw new Error('Initialize failed: invalid dom.');
  26737. }
  26738. }
  26739. var existInstance = getInstanceByDom(dom);
  26740. if (existInstance) {
  26741. if ("development" !== 'production') {
  26742. warn('There is a chart instance already initialized on the dom.');
  26743. }
  26744. return existInstance;
  26745. }
  26746. if ("development" !== 'production') {
  26747. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  26748. 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.');
  26749. }
  26750. }
  26751. }
  26752. var chart = new ECharts(dom, theme, opts);
  26753. chart.id = 'ec_' + idBase++;
  26754. instances$1[chart.id] = chart;
  26755. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  26756. enableConnect(chart);
  26757. lifecycle.trigger('afterinit', chart);
  26758. return chart;
  26759. }
  26760. /**
  26761. * @usage
  26762. * (A)
  26763. * ```js
  26764. * let chart1 = echarts.init(dom1);
  26765. * let chart2 = echarts.init(dom2);
  26766. * chart1.group = 'xxx';
  26767. * chart2.group = 'xxx';
  26768. * echarts.connect('xxx');
  26769. * ```
  26770. * (B)
  26771. * ```js
  26772. * let chart1 = echarts.init(dom1);
  26773. * let chart2 = echarts.init(dom2);
  26774. * echarts.connect('xxx', [chart1, chart2]);
  26775. * ```
  26776. */
  26777. function connect(groupId) {
  26778. // Is array of charts
  26779. if (isArray(groupId)) {
  26780. var charts = groupId;
  26781. groupId = null;
  26782. // If any chart has group
  26783. each(charts, function (chart) {
  26784. if (chart.group != null) {
  26785. groupId = chart.group;
  26786. }
  26787. });
  26788. groupId = groupId || 'g_' + groupIdBase++;
  26789. each(charts, function (chart) {
  26790. chart.group = groupId;
  26791. });
  26792. }
  26793. connectedGroups[groupId] = true;
  26794. return groupId;
  26795. }
  26796. function disconnect(groupId) {
  26797. connectedGroups[groupId] = false;
  26798. }
  26799. /**
  26800. * Alias and backward compatibility
  26801. * @deprecated
  26802. */
  26803. var disConnect = disconnect;
  26804. /**
  26805. * Dispose a chart instance
  26806. */
  26807. function dispose$1(chart) {
  26808. if (isString(chart)) {
  26809. chart = instances$1[chart];
  26810. } else if (!(chart instanceof ECharts)) {
  26811. // Try to treat as dom
  26812. chart = getInstanceByDom(chart);
  26813. }
  26814. if (chart instanceof ECharts && !chart.isDisposed()) {
  26815. chart.dispose();
  26816. }
  26817. }
  26818. function getInstanceByDom(dom) {
  26819. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  26820. }
  26821. function getInstanceById(key) {
  26822. return instances$1[key];
  26823. }
  26824. /**
  26825. * Register theme
  26826. */
  26827. function registerTheme(name, theme) {
  26828. themeStorage[name] = theme;
  26829. }
  26830. /**
  26831. * Register option preprocessor
  26832. */
  26833. function registerPreprocessor(preprocessorFunc) {
  26834. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  26835. optionPreprocessorFuncs.push(preprocessorFunc);
  26836. }
  26837. }
  26838. function registerProcessor(priority, processor) {
  26839. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  26840. }
  26841. /**
  26842. * Register postIniter
  26843. * @param {Function} postInitFunc
  26844. */
  26845. function registerPostInit(postInitFunc) {
  26846. registerUpdateLifecycle('afterinit', postInitFunc);
  26847. }
  26848. /**
  26849. * Register postUpdater
  26850. * @param {Function} postUpdateFunc
  26851. */
  26852. function registerPostUpdate(postUpdateFunc) {
  26853. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  26854. }
  26855. function registerUpdateLifecycle(name, cb) {
  26856. lifecycle.on(name, cb);
  26857. }
  26858. function registerAction(actionInfo, eventName, action) {
  26859. if (isFunction(eventName)) {
  26860. action = eventName;
  26861. eventName = '';
  26862. }
  26863. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  26864. event: eventName
  26865. }][0];
  26866. // Event name is all lowercase
  26867. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  26868. eventName = actionInfo.event;
  26869. if (eventActionMap[eventName]) {
  26870. // Already registered.
  26871. return;
  26872. }
  26873. // Validate action type and event name.
  26874. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  26875. if (!actions[actionType]) {
  26876. actions[actionType] = {
  26877. action: action,
  26878. actionInfo: actionInfo
  26879. };
  26880. }
  26881. eventActionMap[eventName] = actionType;
  26882. }
  26883. function registerCoordinateSystem(type, coordSysCreator) {
  26884. CoordinateSystemManager.register(type, coordSysCreator);
  26885. }
  26886. /**
  26887. * Get dimensions of specified coordinate system.
  26888. * @param {string} type
  26889. * @return {Array.<string|Object>}
  26890. */
  26891. function getCoordinateSystemDimensions(type) {
  26892. var coordSysCreator = CoordinateSystemManager.get(type);
  26893. if (coordSysCreator) {
  26894. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  26895. }
  26896. }
  26897. function registerLayout(priority, layoutTask) {
  26898. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26899. }
  26900. function registerVisual(priority, visualTask) {
  26901. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26902. }
  26903. var registeredTasks = [];
  26904. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26905. if (isFunction(priority) || isObject(priority)) {
  26906. fn = priority;
  26907. priority = defaultPriority;
  26908. }
  26909. if ("development" !== 'production') {
  26910. if (isNaN(priority) || priority == null) {
  26911. throw new Error('Illegal priority');
  26912. }
  26913. // Check duplicate
  26914. each(targetList, function (wrap) {
  26915. assert(wrap.__raw !== fn);
  26916. });
  26917. }
  26918. // Already registered
  26919. if (indexOf(registeredTasks, fn) >= 0) {
  26920. return;
  26921. }
  26922. registeredTasks.push(fn);
  26923. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26924. stageHandler.__prio = priority;
  26925. stageHandler.__raw = fn;
  26926. targetList.push(stageHandler);
  26927. }
  26928. function registerLoading(name, loadingFx) {
  26929. loadingEffects[name] = loadingFx;
  26930. }
  26931. /**
  26932. * ZRender need a canvas context to do measureText.
  26933. * But in node environment canvas may be created by node-canvas.
  26934. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26935. *
  26936. *
  26937. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  26938. *
  26939. * @example
  26940. * let Canvas = require('canvas');
  26941. * let echarts = require('echarts');
  26942. * echarts.setCanvasCreator(function () {
  26943. * // Small size is enough.
  26944. * return new Canvas(32, 32);
  26945. * });
  26946. */
  26947. function setCanvasCreator(creator) {
  26948. if ("development" !== 'production') {
  26949. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  26950. }
  26951. setPlatformAPI({
  26952. createCanvas: creator
  26953. });
  26954. }
  26955. /**
  26956. * The parameters and usage: see `geoSourceManager.registerMap`.
  26957. * Compatible with previous `echarts.registerMap`.
  26958. */
  26959. function registerMap(mapName, geoJson, specialAreas) {
  26960. var registerMap = getImpl('registerMap');
  26961. registerMap && registerMap(mapName, geoJson, specialAreas);
  26962. }
  26963. function getMap(mapName) {
  26964. var getMap = getImpl('getMap');
  26965. return getMap && getMap(mapName);
  26966. }
  26967. var registerTransform = registerExternalTransform;
  26968. /**
  26969. * Globa dispatchAction to a specified chart instance.
  26970. */
  26971. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  26972. // if (!payload || !payload.chartId) {
  26973. // // Must have chartId to find chart
  26974. // return;
  26975. // }
  26976. // const chart = instances[payload.chartId];
  26977. // if (chart) {
  26978. // chart.dispatchAction(payload, opt);
  26979. // }
  26980. // }
  26981. // Builtin global visual
  26982. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  26983. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  26984. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  26985. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  26986. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  26987. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  26988. registerPreprocessor(globalBackwardCompat);
  26989. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26990. registerLoading('default', defaultLoading);
  26991. // Default actions
  26992. registerAction({
  26993. type: HIGHLIGHT_ACTION_TYPE,
  26994. event: HIGHLIGHT_ACTION_TYPE,
  26995. update: HIGHLIGHT_ACTION_TYPE
  26996. }, noop);
  26997. registerAction({
  26998. type: DOWNPLAY_ACTION_TYPE,
  26999. event: DOWNPLAY_ACTION_TYPE,
  27000. update: DOWNPLAY_ACTION_TYPE
  27001. }, noop);
  27002. registerAction({
  27003. type: SELECT_ACTION_TYPE,
  27004. event: SELECT_ACTION_TYPE,
  27005. update: SELECT_ACTION_TYPE
  27006. }, noop);
  27007. registerAction({
  27008. type: UNSELECT_ACTION_TYPE,
  27009. event: UNSELECT_ACTION_TYPE,
  27010. update: UNSELECT_ACTION_TYPE
  27011. }, noop);
  27012. registerAction({
  27013. type: TOGGLE_SELECT_ACTION_TYPE,
  27014. event: TOGGLE_SELECT_ACTION_TYPE,
  27015. update: TOGGLE_SELECT_ACTION_TYPE
  27016. }, noop);
  27017. // Default theme
  27018. registerTheme('light', lightTheme);
  27019. registerTheme('dark', theme);
  27020. // For backward compatibility, where the namespace `dataTool` will
  27021. // be mounted on `echarts` is the extension `dataTool` is imported.
  27022. var dataTool = {};
  27023. var extensions = [];
  27024. var extensionRegisters = {
  27025. registerPreprocessor: registerPreprocessor,
  27026. registerProcessor: registerProcessor,
  27027. registerPostInit: registerPostInit,
  27028. registerPostUpdate: registerPostUpdate,
  27029. registerUpdateLifecycle: registerUpdateLifecycle,
  27030. registerAction: registerAction,
  27031. registerCoordinateSystem: registerCoordinateSystem,
  27032. registerLayout: registerLayout,
  27033. registerVisual: registerVisual,
  27034. registerTransform: registerTransform,
  27035. registerLoading: registerLoading,
  27036. registerMap: registerMap,
  27037. registerImpl: registerImpl,
  27038. PRIORITY: PRIORITY,
  27039. ComponentModel: ComponentModel,
  27040. ComponentView: ComponentView,
  27041. SeriesModel: SeriesModel,
  27042. ChartView: ChartView,
  27043. // TODO Use ComponentModel and SeriesModel instead of Constructor
  27044. registerComponentModel: function (ComponentModelClass) {
  27045. ComponentModel.registerClass(ComponentModelClass);
  27046. },
  27047. registerComponentView: function (ComponentViewClass) {
  27048. ComponentView.registerClass(ComponentViewClass);
  27049. },
  27050. registerSeriesModel: function (SeriesModelClass) {
  27051. SeriesModel.registerClass(SeriesModelClass);
  27052. },
  27053. registerChartView: function (ChartViewClass) {
  27054. ChartView.registerClass(ChartViewClass);
  27055. },
  27056. registerSubTypeDefaulter: function (componentType, defaulter) {
  27057. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  27058. },
  27059. registerPainter: function (painterType, PainterCtor) {
  27060. registerPainter(painterType, PainterCtor);
  27061. }
  27062. };
  27063. function use(ext) {
  27064. if (isArray(ext)) {
  27065. // use([ChartLine, ChartBar]);
  27066. each(ext, function (singleExt) {
  27067. use(singleExt);
  27068. });
  27069. return;
  27070. }
  27071. if (indexOf(extensions, ext) >= 0) {
  27072. return;
  27073. }
  27074. extensions.push(ext);
  27075. if (isFunction(ext)) {
  27076. ext = {
  27077. install: ext
  27078. };
  27079. }
  27080. ext.install(extensionRegisters);
  27081. }
  27082. /*
  27083. * Licensed to the Apache Software Foundation (ASF) under one
  27084. * or more contributor license agreements. See the NOTICE file
  27085. * distributed with this work for additional information
  27086. * regarding copyright ownership. The ASF licenses this file
  27087. * to you under the Apache License, Version 2.0 (the
  27088. * "License"); you may not use this file except in compliance
  27089. * with the License. You may obtain a copy of the License at
  27090. *
  27091. * http://www.apache.org/licenses/LICENSE-2.0
  27092. *
  27093. * Unless required by applicable law or agreed to in writing,
  27094. * software distributed under the License is distributed on an
  27095. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27096. * KIND, either express or implied. See the License for the
  27097. * specific language governing permissions and limitations
  27098. * under the License.
  27099. */
  27100. /**
  27101. * AUTO-GENERATED FILE. DO NOT MODIFY.
  27102. */
  27103. /*
  27104. * Licensed to the Apache Software Foundation (ASF) under one
  27105. * or more contributor license agreements. See the NOTICE file
  27106. * distributed with this work for additional information
  27107. * regarding copyright ownership. The ASF licenses this file
  27108. * to you under the Apache License, Version 2.0 (the
  27109. * "License"); you may not use this file except in compliance
  27110. * with the License. You may obtain a copy of the License at
  27111. *
  27112. * http://www.apache.org/licenses/LICENSE-2.0
  27113. *
  27114. * Unless required by applicable law or agreed to in writing,
  27115. * software distributed under the License is distributed on an
  27116. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27117. * KIND, either express or implied. See the License for the
  27118. * specific language governing permissions and limitations
  27119. * under the License.
  27120. */
  27121. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  27122. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  27123. }
  27124. function defaultKeyGetter(item) {
  27125. return item;
  27126. }
  27127. var DataDiffer = /** @class */function () {
  27128. /**
  27129. * @param context Can be visited by this.context in callback.
  27130. */
  27131. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context,
  27132. // By default: 'oneToOne'.
  27133. diffMode) {
  27134. this._old = oldArr;
  27135. this._new = newArr;
  27136. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  27137. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  27138. // Visible in callback via `this.context`;
  27139. this.context = context;
  27140. this._diffModeMultiple = diffMode === 'multiple';
  27141. }
  27142. /**
  27143. * Callback function when add a data
  27144. */
  27145. DataDiffer.prototype.add = function (func) {
  27146. this._add = func;
  27147. return this;
  27148. };
  27149. /**
  27150. * Callback function when update a data
  27151. */
  27152. DataDiffer.prototype.update = function (func) {
  27153. this._update = func;
  27154. return this;
  27155. };
  27156. /**
  27157. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27158. */
  27159. DataDiffer.prototype.updateManyToOne = function (func) {
  27160. this._updateManyToOne = func;
  27161. return this;
  27162. };
  27163. /**
  27164. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27165. */
  27166. DataDiffer.prototype.updateOneToMany = function (func) {
  27167. this._updateOneToMany = func;
  27168. return this;
  27169. };
  27170. /**
  27171. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27172. */
  27173. DataDiffer.prototype.updateManyToMany = function (func) {
  27174. this._updateManyToMany = func;
  27175. return this;
  27176. };
  27177. /**
  27178. * Callback function when remove a data
  27179. */
  27180. DataDiffer.prototype.remove = function (func) {
  27181. this._remove = func;
  27182. return this;
  27183. };
  27184. DataDiffer.prototype.execute = function () {
  27185. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  27186. };
  27187. DataDiffer.prototype._executeOneToOne = function () {
  27188. var oldArr = this._old;
  27189. var newArr = this._new;
  27190. var newDataIndexMap = {};
  27191. var oldDataKeyArr = new Array(oldArr.length);
  27192. var newDataKeyArr = new Array(newArr.length);
  27193. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  27194. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27195. for (var i = 0; i < oldArr.length; i++) {
  27196. var oldKey = oldDataKeyArr[i];
  27197. var newIdxMapVal = newDataIndexMap[oldKey];
  27198. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27199. // idx can never be empty array here. see 'set null' logic below.
  27200. if (newIdxMapValLen > 1) {
  27201. // Consider there is duplicate key (for example, use dataItem.name as key).
  27202. // We should make sure every item in newArr and oldArr can be visited.
  27203. var newIdx = newIdxMapVal.shift();
  27204. if (newIdxMapVal.length === 1) {
  27205. newDataIndexMap[oldKey] = newIdxMapVal[0];
  27206. }
  27207. this._update && this._update(newIdx, i);
  27208. } else if (newIdxMapValLen === 1) {
  27209. newDataIndexMap[oldKey] = null;
  27210. this._update && this._update(newIdxMapVal, i);
  27211. } else {
  27212. this._remove && this._remove(i);
  27213. }
  27214. }
  27215. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27216. };
  27217. /**
  27218. * For example, consider the case:
  27219. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  27220. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  27221. * Where:
  27222. * o0, o1, n0 has key 'a' (many to one)
  27223. * o5, n4, n5, n6 has key 'b' (one to many)
  27224. * o2, n1 has key 'c' (one to one)
  27225. * n2, n3 has key 'd' (add)
  27226. * o3, o4 has key 'e' (remove)
  27227. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  27228. * Then:
  27229. * (The order of the following directives are not ensured.)
  27230. * this._updateManyToOne(n0, [o0, o1]);
  27231. * this._updateOneToMany([n4, n5, n6], o5);
  27232. * this._update(n1, o2);
  27233. * this._remove(o3);
  27234. * this._remove(o4);
  27235. * this._remove(o6);
  27236. * this._remove(o7);
  27237. * this._add(n2);
  27238. * this._add(n3);
  27239. * this._add(n7);
  27240. * this._add(n8);
  27241. */
  27242. DataDiffer.prototype._executeMultiple = function () {
  27243. var oldArr = this._old;
  27244. var newArr = this._new;
  27245. var oldDataIndexMap = {};
  27246. var newDataIndexMap = {};
  27247. var oldDataKeyArr = [];
  27248. var newDataKeyArr = [];
  27249. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  27250. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27251. for (var i = 0; i < oldDataKeyArr.length; i++) {
  27252. var oldKey = oldDataKeyArr[i];
  27253. var oldIdxMapVal = oldDataIndexMap[oldKey];
  27254. var newIdxMapVal = newDataIndexMap[oldKey];
  27255. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  27256. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27257. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  27258. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  27259. newDataIndexMap[oldKey] = null;
  27260. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  27261. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  27262. newDataIndexMap[oldKey] = null;
  27263. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  27264. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  27265. newDataIndexMap[oldKey] = null;
  27266. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  27267. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  27268. newDataIndexMap[oldKey] = null;
  27269. } else if (oldIdxMapValLen > 1) {
  27270. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  27271. this._remove && this._remove(oldIdxMapVal[i_1]);
  27272. }
  27273. } else {
  27274. this._remove && this._remove(oldIdxMapVal);
  27275. }
  27276. }
  27277. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27278. };
  27279. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  27280. for (var i = 0; i < newDataKeyArr.length; i++) {
  27281. var newKey = newDataKeyArr[i];
  27282. var newIdxMapVal = newDataIndexMap[newKey];
  27283. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27284. if (idxMapValLen > 1) {
  27285. for (var j = 0; j < idxMapValLen; j++) {
  27286. this._add && this._add(newIdxMapVal[j]);
  27287. }
  27288. } else if (idxMapValLen === 1) {
  27289. this._add && this._add(newIdxMapVal);
  27290. }
  27291. // Support both `newDataKeyArr` are duplication removed or not removed.
  27292. newDataIndexMap[newKey] = null;
  27293. }
  27294. };
  27295. DataDiffer.prototype._initIndexMap = function (arr,
  27296. // Can be null.
  27297. map,
  27298. // In 'byKey', the output `keyArr` is duplication removed.
  27299. // In 'byIndex', the output `keyArr` is not duplication removed and
  27300. // its indices are accurately corresponding to `arr`.
  27301. keyArr, keyGetterName) {
  27302. var cbModeMultiple = this._diffModeMultiple;
  27303. for (var i = 0; i < arr.length; i++) {
  27304. // Add prefix to avoid conflict with Object.prototype.
  27305. var key = '_ec_' + this[keyGetterName](arr[i], i);
  27306. if (!cbModeMultiple) {
  27307. keyArr[i] = key;
  27308. }
  27309. if (!map) {
  27310. continue;
  27311. }
  27312. var idxMapVal = map[key];
  27313. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27314. if (idxMapValLen === 0) {
  27315. // Simple optimize: in most cases, one index has one key,
  27316. // do not need array.
  27317. map[key] = i;
  27318. if (cbModeMultiple) {
  27319. keyArr.push(key);
  27320. }
  27321. } else if (idxMapValLen === 1) {
  27322. map[key] = [idxMapVal, i];
  27323. } else {
  27324. idxMapVal.push(i);
  27325. }
  27326. }
  27327. };
  27328. return DataDiffer;
  27329. }();
  27330. var DimensionUserOuput = /** @class */function () {
  27331. function DimensionUserOuput(encode, dimRequest) {
  27332. this._encode = encode;
  27333. this._schema = dimRequest;
  27334. }
  27335. DimensionUserOuput.prototype.get = function () {
  27336. return {
  27337. // Do not generate full dimension name until fist used.
  27338. fullDimensions: this._getFullDimensionNames(),
  27339. encode: this._encode
  27340. };
  27341. };
  27342. /**
  27343. * Get all data store dimension names.
  27344. * Theoretically a series data store is defined both by series and used dataset (if any).
  27345. * If some dimensions are omitted for performance reason in `this.dimensions`,
  27346. * the dimension name may not be auto-generated if user does not specify a dimension name.
  27347. * In this case, the dimension name is `null`/`undefined`.
  27348. */
  27349. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  27350. if (!this._cachedDimNames) {
  27351. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  27352. }
  27353. return this._cachedDimNames;
  27354. };
  27355. return DimensionUserOuput;
  27356. }();
  27357. function summarizeDimensions(data, schema) {
  27358. var summary = {};
  27359. var encode = summary.encode = {};
  27360. var notExtraCoordDimMap = createHashMap();
  27361. var defaultedLabel = [];
  27362. var defaultedTooltip = [];
  27363. var userOutputEncode = {};
  27364. each(data.dimensions, function (dimName) {
  27365. var dimItem = data.getDimensionInfo(dimName);
  27366. var coordDim = dimItem.coordDim;
  27367. if (coordDim) {
  27368. if ("development" !== 'production') {
  27369. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  27370. }
  27371. var coordDimIndex = dimItem.coordDimIndex;
  27372. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  27373. if (!dimItem.isExtraCoord) {
  27374. notExtraCoordDimMap.set(coordDim, 1);
  27375. // Use the last coord dim (and label friendly) as default label,
  27376. // because when dataset is used, it is hard to guess which dimension
  27377. // can be value dimension. If both show x, y on label is not look good,
  27378. // and conventionally y axis is focused more.
  27379. if (mayLabelDimType(dimItem.type)) {
  27380. defaultedLabel[0] = dimName;
  27381. }
  27382. // User output encode do not contain generated coords.
  27383. // And it only has index. User can use index to retrieve value from the raw item array.
  27384. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  27385. }
  27386. if (dimItem.defaultTooltip) {
  27387. defaultedTooltip.push(dimName);
  27388. }
  27389. }
  27390. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  27391. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  27392. var dimIndex = dimItem.otherDims[otherDim];
  27393. if (dimIndex != null && dimIndex !== false) {
  27394. encodeArr[dimIndex] = dimItem.name;
  27395. }
  27396. });
  27397. });
  27398. var dataDimsOnCoord = [];
  27399. var encodeFirstDimNotExtra = {};
  27400. notExtraCoordDimMap.each(function (v, coordDim) {
  27401. var dimArr = encode[coordDim];
  27402. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  27403. // Not necessary to remove duplicate, because a data
  27404. // dim canot on more than one coordDim.
  27405. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  27406. });
  27407. summary.dataDimsOnCoord = dataDimsOnCoord;
  27408. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  27409. return data.getDimensionInfo(dimName).storeDimIndex;
  27410. });
  27411. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  27412. var encodeLabel = encode.label;
  27413. // FIXME `encode.label` is not recommended, because formatter cannot be set
  27414. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  27415. if (encodeLabel && encodeLabel.length) {
  27416. defaultedLabel = encodeLabel.slice();
  27417. }
  27418. var encodeTooltip = encode.tooltip;
  27419. if (encodeTooltip && encodeTooltip.length) {
  27420. defaultedTooltip = encodeTooltip.slice();
  27421. } else if (!defaultedTooltip.length) {
  27422. defaultedTooltip = defaultedLabel.slice();
  27423. }
  27424. encode.defaultedLabel = defaultedLabel;
  27425. encode.defaultedTooltip = defaultedTooltip;
  27426. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  27427. return summary;
  27428. }
  27429. function getOrCreateEncodeArr(encode, dim) {
  27430. if (!encode.hasOwnProperty(dim)) {
  27431. encode[dim] = [];
  27432. }
  27433. return encode[dim];
  27434. }
  27435. // FIXME:TS should be type `AxisType`
  27436. function getDimensionTypeByAxis(axisType) {
  27437. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  27438. }
  27439. function mayLabelDimType(dimType) {
  27440. // In most cases, ordinal and time do not suitable for label.
  27441. // Ordinal info can be displayed on axis. Time is too long.
  27442. return !(dimType === 'ordinal' || dimType === 'time');
  27443. }
  27444. // function findTheLastDimMayLabel(data) {
  27445. // // Get last value dim
  27446. // let dimensions = data.dimensions.slice();
  27447. // let valueType;
  27448. // let valueDim;
  27449. // while (dimensions.length && (
  27450. // valueDim = dimensions.pop(),
  27451. // valueType = data.getDimensionInfo(valueDim).type,
  27452. // valueType === 'ordinal' || valueType === 'time'
  27453. // )) {} // jshint ignore:line
  27454. // return valueDim;
  27455. // }
  27456. var SeriesDimensionDefine = /** @class */function () {
  27457. /**
  27458. * @param opt All of the fields will be shallow copied.
  27459. */
  27460. function SeriesDimensionDefine(opt) {
  27461. /**
  27462. * The format of `otherDims` is:
  27463. * ```js
  27464. * {
  27465. * tooltip?: number
  27466. * label?: number
  27467. * itemName?: number
  27468. * seriesName?: number
  27469. * }
  27470. * ```
  27471. *
  27472. * A `series.encode` can specified these fields:
  27473. * ```js
  27474. * encode: {
  27475. * // "3, 1, 5" is the index of data dimension.
  27476. * tooltip: [3, 1, 5],
  27477. * label: [0, 3],
  27478. * ...
  27479. * }
  27480. * ```
  27481. * `otherDims` is the parse result of the `series.encode` above, like:
  27482. * ```js
  27483. * // Suppose the index of this data dimension is `3`.
  27484. * this.otherDims = {
  27485. * // `3` is at the index `0` of the `encode.tooltip`
  27486. * tooltip: 0,
  27487. * // `3` is at the index `1` of the `encode.label`
  27488. * label: 1
  27489. * };
  27490. * ```
  27491. *
  27492. * This prop should never be `null`/`undefined` after initialized.
  27493. */
  27494. this.otherDims = {};
  27495. if (opt != null) {
  27496. extend(this, opt);
  27497. }
  27498. }
  27499. return SeriesDimensionDefine;
  27500. }();
  27501. var inner$4 = makeInner();
  27502. var dimTypeShort = {
  27503. float: 'f',
  27504. int: 'i',
  27505. ordinal: 'o',
  27506. number: 'n',
  27507. time: 't'
  27508. };
  27509. /**
  27510. * Represents the dimension requirement of a series.
  27511. *
  27512. * NOTICE:
  27513. * When there are too many dimensions in dataset and many series, only the used dimensions
  27514. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  27515. * But users may query data by other unused dimension names.
  27516. * In this case, users can only query data if and only if they have defined dimension names
  27517. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  27518. * `source` dimensions.
  27519. */
  27520. var SeriesDataSchema = /** @class */function () {
  27521. function SeriesDataSchema(opt) {
  27522. this.dimensions = opt.dimensions;
  27523. this._dimOmitted = opt.dimensionOmitted;
  27524. this.source = opt.source;
  27525. this._fullDimCount = opt.fullDimensionCount;
  27526. this._updateDimOmitted(opt.dimensionOmitted);
  27527. }
  27528. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  27529. return this._dimOmitted;
  27530. };
  27531. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  27532. this._dimOmitted = dimensionOmitted;
  27533. if (!dimensionOmitted) {
  27534. return;
  27535. }
  27536. if (!this._dimNameMap) {
  27537. this._dimNameMap = ensureSourceDimNameMap(this.source);
  27538. }
  27539. };
  27540. /**
  27541. * @caution Can only be used when `dimensionOmitted: true`.
  27542. *
  27543. * Get index by user defined dimension name (i.e., not internal generate name).
  27544. * That is, get index from `dimensionsDefine`.
  27545. * If no `dimensionsDefine`, or no name get, return -1.
  27546. */
  27547. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  27548. return retrieve2(this._dimNameMap.get(dimName), -1);
  27549. };
  27550. /**
  27551. * @caution Can only be used when `dimensionOmitted: true`.
  27552. *
  27553. * Notice: may return `null`/`undefined` if user not specify dimension names.
  27554. */
  27555. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  27556. var dimensionsDefine = this.source.dimensionsDefine;
  27557. if (dimensionsDefine) {
  27558. return dimensionsDefine[dimIndex];
  27559. }
  27560. };
  27561. SeriesDataSchema.prototype.makeStoreSchema = function () {
  27562. var dimCount = this._fullDimCount;
  27563. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  27564. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount);
  27565. // If source don't have dimensions or series don't omit unsed dimensions.
  27566. // Generate from seriesDimList directly
  27567. var dimHash = '';
  27568. var dims = [];
  27569. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  27570. var property = void 0;
  27571. var type = void 0;
  27572. var ordinalMeta = void 0;
  27573. var seriesDimDef = this.dimensions[seriesDimIdx];
  27574. // The list has been sorted by `storeDimIndex` asc.
  27575. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  27576. property = willRetrieveDataByName ? seriesDimDef.name : null;
  27577. type = seriesDimDef.type;
  27578. ordinalMeta = seriesDimDef.ordinalMeta;
  27579. seriesDimIdx++;
  27580. } else {
  27581. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  27582. if (sourceDimDef) {
  27583. property = willRetrieveDataByName ? sourceDimDef.name : null;
  27584. type = sourceDimDef.type;
  27585. }
  27586. }
  27587. dims.push({
  27588. property: property,
  27589. type: type,
  27590. ordinalMeta: ordinalMeta
  27591. });
  27592. // If retrieving data by index,
  27593. // use <index, type, ordinalMeta> to determine whether data can be shared.
  27594. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  27595. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  27596. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  27597. // use <property, type, ordinalMeta> in hash.
  27598. if (willRetrieveDataByName && property != null
  27599. // For data stack, we have make sure each series has its own dim on this store.
  27600. // So we do not add property to hash to make sure they can share this store.
  27601. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  27602. dimHash += makeHashStrict
  27603. // Use escape character '`' in case that property name contains '$'.
  27604. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2')
  27605. // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  27606. : property;
  27607. }
  27608. dimHash += '$';
  27609. dimHash += dimTypeShort[type] || 'f';
  27610. if (ordinalMeta) {
  27611. dimHash += ordinalMeta.uid;
  27612. }
  27613. dimHash += '$';
  27614. }
  27615. // Source from endpoint(usually series) will be read differently
  27616. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  27617. // So we use this three props as key.
  27618. var source = this.source;
  27619. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  27620. return {
  27621. dimensions: dims,
  27622. hash: hash
  27623. };
  27624. };
  27625. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  27626. var result = [];
  27627. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  27628. var name_1 = void 0;
  27629. var seriesDimDef = this.dimensions[seriesDimIdx];
  27630. // The list has been sorted by `storeDimIndex` asc.
  27631. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  27632. if (!seriesDimDef.isCalculationCoord) {
  27633. name_1 = seriesDimDef.name;
  27634. }
  27635. seriesDimIdx++;
  27636. } else {
  27637. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  27638. if (sourceDimDef) {
  27639. name_1 = sourceDimDef.name;
  27640. }
  27641. }
  27642. result.push(name_1);
  27643. }
  27644. return result;
  27645. };
  27646. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  27647. this.dimensions.push(dimDef);
  27648. dimDef.isCalculationCoord = true;
  27649. this._fullDimCount++;
  27650. // If append dimension on a data store, consider the store
  27651. // might be shared by different series, series dimensions not
  27652. // really map to store dimensions.
  27653. this._updateDimOmitted(true);
  27654. };
  27655. return SeriesDataSchema;
  27656. }();
  27657. function isSeriesDataSchema(schema) {
  27658. return schema instanceof SeriesDataSchema;
  27659. }
  27660. function createDimNameMap(dimsDef) {
  27661. var dataDimNameMap = createHashMap();
  27662. for (var i = 0; i < (dimsDef || []).length; i++) {
  27663. var dimDefItemRaw = dimsDef[i];
  27664. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  27665. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27666. dataDimNameMap.set(userDimName, i);
  27667. }
  27668. }
  27669. return dataDimNameMap;
  27670. }
  27671. function ensureSourceDimNameMap(source) {
  27672. var innerSource = inner$4(source);
  27673. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  27674. }
  27675. function shouldOmitUnusedDimensions(dimCount) {
  27676. return dimCount > 30;
  27677. }
  27678. var isObject$2 = isObject;
  27679. var map$1 = map;
  27680. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array;
  27681. // Use prefix to avoid index to be the same as otherIdList[idx],
  27682. // which will cause weird update animation.
  27683. var ID_PREFIX = 'e\0\0';
  27684. var INDEX_NOT_FOUND = -1;
  27685. // type SeriesDimensionIndex = DimensionIndex;
  27686. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  27687. var CLONE_PROPERTIES = ['_approximateExtent'];
  27688. // -----------------------------
  27689. // Internal method declarations:
  27690. // -----------------------------
  27691. var prepareInvertedIndex;
  27692. var getId;
  27693. var getIdNameFromStore;
  27694. var normalizeDimensions;
  27695. var transferProperties;
  27696. var cloneListForMapAndSample;
  27697. var makeIdFromName;
  27698. var SeriesData = /** @class */function () {
  27699. /**
  27700. * @param dimensionsInput.dimensions
  27701. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  27702. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  27703. */
  27704. function SeriesData(dimensionsInput, hostModel) {
  27705. this.type = 'list';
  27706. this._dimOmitted = false;
  27707. this._nameList = [];
  27708. this._idList = [];
  27709. // Models of data option is stored sparse for optimizing memory cost
  27710. // Never used yet (not used yet).
  27711. // private _optionModels: Model[] = [];
  27712. // Global visual properties after visual coding
  27713. this._visual = {};
  27714. // Global layout properties.
  27715. this._layout = {};
  27716. // Item visual properties after visual coding
  27717. this._itemVisuals = [];
  27718. // Item layout properties after layout
  27719. this._itemLayouts = [];
  27720. // Graphic elements
  27721. this._graphicEls = [];
  27722. // key: dim, value: extent
  27723. this._approximateExtent = {};
  27724. this._calculationInfo = {};
  27725. // Having detected that there is data item is non primitive type
  27726. // (in type `OptionDataItemObject`).
  27727. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  27728. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  27729. this.hasItemOption = false;
  27730. // Methods that create a new list based on this list should be listed here.
  27731. // Notice that those method should `RETURN` the new list.
  27732. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map'];
  27733. // Methods that change indices of this list should be listed here.
  27734. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27735. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  27736. var dimensions;
  27737. var assignStoreDimIdx = false;
  27738. if (isSeriesDataSchema(dimensionsInput)) {
  27739. dimensions = dimensionsInput.dimensions;
  27740. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  27741. this._schema = dimensionsInput;
  27742. } else {
  27743. assignStoreDimIdx = true;
  27744. dimensions = dimensionsInput;
  27745. }
  27746. dimensions = dimensions || ['x', 'y'];
  27747. var dimensionInfos = {};
  27748. var dimensionNames = [];
  27749. var invertedIndicesMap = {};
  27750. var needsHasOwn = false;
  27751. var emptyObj = {};
  27752. for (var i = 0; i < dimensions.length; i++) {
  27753. // Use the original dimensions[i], where other flag props may exists.
  27754. var dimInfoInput = dimensions[i];
  27755. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  27756. name: dimInfoInput
  27757. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  27758. var dimensionName = dimensionInfo.name;
  27759. dimensionInfo.type = dimensionInfo.type || 'float';
  27760. if (!dimensionInfo.coordDim) {
  27761. dimensionInfo.coordDim = dimensionName;
  27762. dimensionInfo.coordDimIndex = 0;
  27763. }
  27764. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  27765. dimensionNames.push(dimensionName);
  27766. dimensionInfos[dimensionName] = dimensionInfo;
  27767. if (emptyObj[dimensionName] != null) {
  27768. needsHasOwn = true;
  27769. }
  27770. if (dimensionInfo.createInvertedIndices) {
  27771. invertedIndicesMap[dimensionName] = [];
  27772. }
  27773. if (otherDims.itemName === 0) {
  27774. this._nameDimIdx = i;
  27775. }
  27776. if (otherDims.itemId === 0) {
  27777. this._idDimIdx = i;
  27778. }
  27779. if ("development" !== 'production') {
  27780. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  27781. }
  27782. if (assignStoreDimIdx) {
  27783. dimensionInfo.storeDimIndex = i;
  27784. }
  27785. }
  27786. this.dimensions = dimensionNames;
  27787. this._dimInfos = dimensionInfos;
  27788. this._initGetDimensionInfo(needsHasOwn);
  27789. this.hostModel = hostModel;
  27790. this._invertedIndicesMap = invertedIndicesMap;
  27791. if (this._dimOmitted) {
  27792. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  27793. each(dimensionNames, function (dimName) {
  27794. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  27795. });
  27796. }
  27797. }
  27798. /**
  27799. *
  27800. * Get concrete dimension name by dimension name or dimension index.
  27801. * If input a dimension name, do not validate whether the dimension name exits.
  27802. *
  27803. * @caution
  27804. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  27805. * Because only those dimensions will have auto-generated dimension names if not
  27806. * have a user-specified name, and other dimensions will get a return of null/undefined.
  27807. *
  27808. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  27809. * ```js
  27810. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  27811. * ```
  27812. *
  27813. * @return Concrete dim name.
  27814. */
  27815. SeriesData.prototype.getDimension = function (dim) {
  27816. var dimIdx = this._recognizeDimIndex(dim);
  27817. if (dimIdx == null) {
  27818. return dim;
  27819. }
  27820. dimIdx = dim;
  27821. if (!this._dimOmitted) {
  27822. return this.dimensions[dimIdx];
  27823. }
  27824. // Retrieve from series dimension definition because it probably contains
  27825. // generated dimension name (like 'x', 'y').
  27826. var dimName = this._dimIdxToName.get(dimIdx);
  27827. if (dimName != null) {
  27828. return dimName;
  27829. }
  27830. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  27831. if (sourceDimDef) {
  27832. return sourceDimDef.name;
  27833. }
  27834. };
  27835. /**
  27836. * Get dimension index in data store. Return -1 if not found.
  27837. * Can be used to index value from getRawValue.
  27838. */
  27839. SeriesData.prototype.getDimensionIndex = function (dim) {
  27840. var dimIdx = this._recognizeDimIndex(dim);
  27841. if (dimIdx != null) {
  27842. return dimIdx;
  27843. }
  27844. if (dim == null) {
  27845. return -1;
  27846. }
  27847. var dimInfo = this._getDimInfo(dim);
  27848. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  27849. };
  27850. /**
  27851. * The meanings of the input parameter `dim`:
  27852. *
  27853. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  27854. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  27855. * + If dim is a number-like string (e.g., `"1"`):
  27856. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  27857. * it means that concrete name.
  27858. * + If not, it will be converted to a number, which means the index of the dimension.
  27859. * (why? because of the backward compatibility. We have been tolerating number-like string in
  27860. * dimension setting, although now it seems that it is not a good idea.)
  27861. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  27862. * if no dimension name is defined as `"1"`.
  27863. * + If dim is a not-number-like string, it means the concrete dim name.
  27864. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  27865. * or customized in `dimensions` property of option like `"age"`.
  27866. *
  27867. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  27868. */
  27869. SeriesData.prototype._recognizeDimIndex = function (dim) {
  27870. if (isNumber(dim)
  27871. // If being a number-like string but not being defined as a dimension name.
  27872. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  27873. return +dim;
  27874. }
  27875. };
  27876. SeriesData.prototype._getStoreDimIndex = function (dim) {
  27877. var dimIdx = this.getDimensionIndex(dim);
  27878. if ("development" !== 'production') {
  27879. if (dimIdx == null) {
  27880. throw new Error('Unknown dimension ' + dim);
  27881. }
  27882. }
  27883. return dimIdx;
  27884. };
  27885. /**
  27886. * Get type and calculation info of particular dimension
  27887. * @param dim
  27888. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  27889. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  27890. */
  27891. SeriesData.prototype.getDimensionInfo = function (dim) {
  27892. // Do not clone, because there may be categories in dimInfo.
  27893. return this._getDimInfo(this.getDimension(dim));
  27894. };
  27895. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  27896. var dimensionInfos = this._dimInfos;
  27897. this._getDimInfo = needsHasOwn ? function (dimName) {
  27898. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  27899. } : function (dimName) {
  27900. return dimensionInfos[dimName];
  27901. };
  27902. };
  27903. /**
  27904. * concrete dimension name list on coord.
  27905. */
  27906. SeriesData.prototype.getDimensionsOnCoord = function () {
  27907. return this._dimSummary.dataDimsOnCoord.slice();
  27908. };
  27909. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  27910. var dimensionsSummary = this._dimSummary;
  27911. if (idx == null) {
  27912. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  27913. }
  27914. var dims = dimensionsSummary.encode[coordDim];
  27915. return dims ? dims[idx] : null;
  27916. };
  27917. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  27918. var dimensionsSummary = this._dimSummary;
  27919. var dims = dimensionsSummary.encode[coordDim];
  27920. return (dims || []).slice();
  27921. };
  27922. SeriesData.prototype.getStore = function () {
  27923. return this._store;
  27924. };
  27925. /**
  27926. * Initialize from data
  27927. * @param data source or data or data store.
  27928. * @param nameList The name of a datum is used on data diff and
  27929. * default label/tooltip.
  27930. * A name can be specified in encode.itemName,
  27931. * or dataItem.name (only for series option data),
  27932. * or provided in nameList from outside.
  27933. */
  27934. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  27935. var _this = this;
  27936. var store;
  27937. if (data instanceof DataStore) {
  27938. store = data;
  27939. }
  27940. if (!store) {
  27941. var dimensions = this.dimensions;
  27942. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  27943. store = new DataStore();
  27944. var dimensionInfos = map$1(dimensions, function (dimName) {
  27945. return {
  27946. type: _this._dimInfos[dimName].type,
  27947. property: dimName
  27948. };
  27949. });
  27950. store.initData(provider, dimensionInfos, dimValueGetter);
  27951. }
  27952. this._store = store;
  27953. // Reset
  27954. this._nameList = (nameList || []).slice();
  27955. this._idList = [];
  27956. this._nameRepeatCount = {};
  27957. this._doInit(0, store.count());
  27958. // Cache summary info for fast visit. See "dimensionHelper".
  27959. // Needs to be initialized after store is prepared.
  27960. this._dimSummary = summarizeDimensions(this, this._schema);
  27961. this.userOutput = this._dimSummary.userOutput;
  27962. };
  27963. /**
  27964. * Caution: Can be only called on raw data (before `this._indices` created).
  27965. */
  27966. SeriesData.prototype.appendData = function (data) {
  27967. var range = this._store.appendData(data);
  27968. this._doInit(range[0], range[1]);
  27969. };
  27970. /**
  27971. * Caution: Can be only called on raw data (before `this._indices` created).
  27972. * This method does not modify `rawData` (`dataProvider`), but only
  27973. * add values to store.
  27974. *
  27975. * The final count will be increased by `Math.max(values.length, names.length)`.
  27976. *
  27977. * @param values That is the SourceType: 'arrayRows', like
  27978. * [
  27979. * [12, 33, 44],
  27980. * [NaN, 43, 1],
  27981. * ['-', 'asdf', 0]
  27982. * ]
  27983. * Each item is exactly corresponding to a dimension.
  27984. */
  27985. SeriesData.prototype.appendValues = function (values, names) {
  27986. var _a = this._store.appendValues(values, names.length),
  27987. start = _a.start,
  27988. end = _a.end;
  27989. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  27990. this._updateOrdinalMeta();
  27991. if (names) {
  27992. for (var idx = start; idx < end; idx++) {
  27993. var sourceIdx = idx - start;
  27994. this._nameList[idx] = names[sourceIdx];
  27995. if (shouldMakeIdFromName) {
  27996. makeIdFromName(this, idx);
  27997. }
  27998. }
  27999. }
  28000. };
  28001. SeriesData.prototype._updateOrdinalMeta = function () {
  28002. var store = this._store;
  28003. var dimensions = this.dimensions;
  28004. for (var i = 0; i < dimensions.length; i++) {
  28005. var dimInfo = this._dimInfos[dimensions[i]];
  28006. if (dimInfo.ordinalMeta) {
  28007. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  28008. }
  28009. }
  28010. };
  28011. SeriesData.prototype._shouldMakeIdFromName = function () {
  28012. var provider = this._store.getProvider();
  28013. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  28014. };
  28015. SeriesData.prototype._doInit = function (start, end) {
  28016. if (start >= end) {
  28017. return;
  28018. }
  28019. var store = this._store;
  28020. var provider = store.getProvider();
  28021. this._updateOrdinalMeta();
  28022. var nameList = this._nameList;
  28023. var idList = this._idList;
  28024. var sourceFormat = provider.getSource().sourceFormat;
  28025. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL;
  28026. // Each data item is value
  28027. // [1, 2]
  28028. // 2
  28029. // Bar chart, line chart which uses category axis
  28030. // only gives the 'y' value. 'x' value is the indices of category
  28031. // Use a tempValue to normalize the value to be a (x, y) value
  28032. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  28033. // This kind of ids and names are always stored `_nameList` and `_idList`.
  28034. if (isFormatOriginal && !provider.pure) {
  28035. var sharedDataItem = [];
  28036. for (var idx = start; idx < end; idx++) {
  28037. // NOTICE: Try not to write things into dataItem
  28038. var dataItem = provider.getItem(idx, sharedDataItem);
  28039. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  28040. this.hasItemOption = true;
  28041. }
  28042. if (dataItem) {
  28043. var itemName = dataItem.name;
  28044. if (nameList[idx] == null && itemName != null) {
  28045. nameList[idx] = convertOptionIdName(itemName, null);
  28046. }
  28047. var itemId = dataItem.id;
  28048. if (idList[idx] == null && itemId != null) {
  28049. idList[idx] = convertOptionIdName(itemId, null);
  28050. }
  28051. }
  28052. }
  28053. }
  28054. if (this._shouldMakeIdFromName()) {
  28055. for (var idx = start; idx < end; idx++) {
  28056. makeIdFromName(this, idx);
  28057. }
  28058. }
  28059. prepareInvertedIndex(this);
  28060. };
  28061. /**
  28062. * PENDING: In fact currently this function is only used to short-circuit
  28063. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  28064. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  28065. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  28066. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  28067. * But if we add "custom data filter" in future, which is not "axis related", this method may
  28068. * be still needed.
  28069. *
  28070. * Optimize for the scenario that data is filtered by a given extent.
  28071. * Consider that if data amount is more than hundreds of thousand,
  28072. * extent calculation will cost more than 10ms and the cache will
  28073. * be erased because of the filtering.
  28074. */
  28075. SeriesData.prototype.getApproximateExtent = function (dim) {
  28076. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  28077. };
  28078. /**
  28079. * Calculate extent on a filtered data might be time consuming.
  28080. * Approximate extent is only used for: calculate extent of filtered data outside.
  28081. */
  28082. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  28083. dim = this.getDimension(dim);
  28084. this._approximateExtent[dim] = extent.slice();
  28085. };
  28086. SeriesData.prototype.getCalculationInfo = function (key) {
  28087. return this._calculationInfo[key];
  28088. };
  28089. SeriesData.prototype.setCalculationInfo = function (key, value) {
  28090. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  28091. };
  28092. /**
  28093. * @return Never be null/undefined. `number` will be converted to string. Because:
  28094. * In most cases, name is used in display, where returning a string is more convenient.
  28095. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28096. * rule that name `2` equals to name `'2'`.
  28097. */
  28098. SeriesData.prototype.getName = function (idx) {
  28099. var rawIndex = this.getRawIndex(idx);
  28100. var name = this._nameList[rawIndex];
  28101. if (name == null && this._nameDimIdx != null) {
  28102. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  28103. }
  28104. if (name == null) {
  28105. name = '';
  28106. }
  28107. return name;
  28108. };
  28109. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  28110. var ordinal = this._store.get(dimIdx, idx);
  28111. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  28112. if (ordinalMeta) {
  28113. return ordinalMeta.categories[ordinal];
  28114. }
  28115. return ordinal;
  28116. };
  28117. /**
  28118. * @return Never null/undefined. `number` will be converted to string. Because:
  28119. * In all cases having encountered at present, id is used in making diff comparison, which
  28120. * are usually based on hash map. We can keep the rule that the internal id are always string
  28121. * (treat `2` is the same as `'2'`) to make the related logic simple.
  28122. */
  28123. SeriesData.prototype.getId = function (idx) {
  28124. return getId(this, this.getRawIndex(idx));
  28125. };
  28126. SeriesData.prototype.count = function () {
  28127. return this._store.count();
  28128. };
  28129. /**
  28130. * Get value. Return NaN if idx is out of range.
  28131. *
  28132. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  28133. */
  28134. SeriesData.prototype.get = function (dim, idx) {
  28135. var store = this._store;
  28136. var dimInfo = this._dimInfos[dim];
  28137. if (dimInfo) {
  28138. return store.get(dimInfo.storeDimIndex, idx);
  28139. }
  28140. };
  28141. /**
  28142. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  28143. */
  28144. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  28145. var store = this._store;
  28146. var dimInfo = this._dimInfos[dim];
  28147. if (dimInfo) {
  28148. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  28149. }
  28150. };
  28151. SeriesData.prototype.getIndices = function () {
  28152. return this._store.getIndices();
  28153. };
  28154. SeriesData.prototype.getDataExtent = function (dim) {
  28155. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  28156. };
  28157. SeriesData.prototype.getSum = function (dim) {
  28158. return this._store.getSum(this._getStoreDimIndex(dim));
  28159. };
  28160. SeriesData.prototype.getMedian = function (dim) {
  28161. return this._store.getMedian(this._getStoreDimIndex(dim));
  28162. };
  28163. SeriesData.prototype.getValues = function (dimensions, idx) {
  28164. var _this = this;
  28165. var store = this._store;
  28166. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  28167. return _this._getStoreDimIndex(dim);
  28168. }), idx) : store.getValues(dimensions);
  28169. };
  28170. /**
  28171. * If value is NaN. Including '-'
  28172. * Only check the coord dimensions.
  28173. */
  28174. SeriesData.prototype.hasValue = function (idx) {
  28175. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  28176. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  28177. // Ordinal type originally can be string or number.
  28178. // But when an ordinal type is used on coord, it can
  28179. // not be string but only number. So we can also use isNaN.
  28180. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  28181. return false;
  28182. }
  28183. }
  28184. return true;
  28185. };
  28186. /**
  28187. * Retrieve the index with given name
  28188. */
  28189. SeriesData.prototype.indexOfName = function (name) {
  28190. for (var i = 0, len = this._store.count(); i < len; i++) {
  28191. if (this.getName(i) === name) {
  28192. return i;
  28193. }
  28194. }
  28195. return -1;
  28196. };
  28197. SeriesData.prototype.getRawIndex = function (idx) {
  28198. return this._store.getRawIndex(idx);
  28199. };
  28200. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  28201. return this._store.indexOfRawIndex(rawIndex);
  28202. };
  28203. /**
  28204. * Only support the dimension which inverted index created.
  28205. * Do not support other cases until required.
  28206. * @param dim concrete dim
  28207. * @param value ordinal index
  28208. * @return rawIndex
  28209. */
  28210. SeriesData.prototype.rawIndexOf = function (dim, value) {
  28211. var invertedIndices = dim && this._invertedIndicesMap[dim];
  28212. if ("development" !== 'production') {
  28213. if (!invertedIndices) {
  28214. throw new Error('Do not supported yet');
  28215. }
  28216. }
  28217. var rawIndex = invertedIndices[value];
  28218. if (rawIndex == null || isNaN(rawIndex)) {
  28219. return INDEX_NOT_FOUND;
  28220. }
  28221. return rawIndex;
  28222. };
  28223. /**
  28224. * Retrieve the index of nearest value
  28225. * @param dim
  28226. * @param value
  28227. * @param [maxDistance=Infinity]
  28228. * @return If and only if multiple indices has
  28229. * the same value, they are put to the result.
  28230. */
  28231. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  28232. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  28233. };
  28234. SeriesData.prototype.each = function (dims, cb, ctx) {
  28235. if (isFunction(dims)) {
  28236. ctx = cb;
  28237. cb = dims;
  28238. dims = [];
  28239. }
  28240. // ctxCompat just for compat echarts3
  28241. var fCtx = ctx || this;
  28242. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28243. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28244. };
  28245. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  28246. if (isFunction(dims)) {
  28247. ctx = cb;
  28248. cb = dims;
  28249. dims = [];
  28250. }
  28251. // ctxCompat just for compat echarts3
  28252. var fCtx = ctx || this;
  28253. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28254. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28255. return this;
  28256. };
  28257. /**
  28258. * Select data in range. (For optimization of filter)
  28259. * (Manually inline code, support 5 million data filtering in data zoom.)
  28260. */
  28261. SeriesData.prototype.selectRange = function (range) {
  28262. var _this = this;
  28263. var innerRange = {};
  28264. var dims = keys(range);
  28265. each(dims, function (dim) {
  28266. var dimIdx = _this._getStoreDimIndex(dim);
  28267. innerRange[dimIdx] = range[dim];
  28268. });
  28269. this._store = this._store.selectRange(innerRange);
  28270. return this;
  28271. };
  28272. /* eslint-enable max-len */
  28273. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  28274. if (isFunction(dims)) {
  28275. ctx = cb;
  28276. cb = dims;
  28277. dims = [];
  28278. }
  28279. // ctxCompat just for compat echarts3
  28280. ctx = ctx || this;
  28281. var result = [];
  28282. this.each(dims, function () {
  28283. result.push(cb && cb.apply(this, arguments));
  28284. }, ctx);
  28285. return result;
  28286. };
  28287. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28288. // ctxCompat just for compat echarts3
  28289. var fCtx = ctx || ctxCompat || this;
  28290. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28291. var list = cloneListForMapAndSample(this);
  28292. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28293. return list;
  28294. };
  28295. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  28296. var _this = this;
  28297. // ctxCompat just for compat echarts3
  28298. var fCtx = ctx || ctxCompat || this;
  28299. if ("development" !== 'production') {
  28300. each(normalizeDimensions(dims), function (dim) {
  28301. var dimInfo = _this.getDimensionInfo(dim);
  28302. if (!dimInfo.isCalculationCoord) {
  28303. console.error('Danger: only stack dimension can be modified');
  28304. }
  28305. });
  28306. }
  28307. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28308. // If do shallow clone here, if there are too many stacked series,
  28309. // it still cost lots of memory, because `_store.dimensions` are not shared.
  28310. // We should consider there probably be shallow clone happen in each series
  28311. // in consequent filter/map.
  28312. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28313. };
  28314. /**
  28315. * Large data down sampling on given dimension
  28316. * @param sampleIndex Sample index for name and id
  28317. */
  28318. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28319. var list = cloneListForMapAndSample(this);
  28320. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  28321. return list;
  28322. };
  28323. /**
  28324. * Large data down sampling using largest-triangle-three-buckets
  28325. * @param {string} valueDimension
  28326. * @param {number} targetCount
  28327. */
  28328. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  28329. var list = cloneListForMapAndSample(this);
  28330. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  28331. return list;
  28332. };
  28333. SeriesData.prototype.getRawDataItem = function (idx) {
  28334. return this._store.getRawDataItem(idx);
  28335. };
  28336. /**
  28337. * Get model of one data item.
  28338. */
  28339. // TODO: Type of data item
  28340. SeriesData.prototype.getItemModel = function (idx) {
  28341. var hostModel = this.hostModel;
  28342. var dataItem = this.getRawDataItem(idx);
  28343. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28344. };
  28345. /**
  28346. * Create a data differ
  28347. */
  28348. SeriesData.prototype.diff = function (otherList) {
  28349. var thisList = this;
  28350. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  28351. return getId(otherList, idx);
  28352. }, function (idx) {
  28353. return getId(thisList, idx);
  28354. });
  28355. };
  28356. /**
  28357. * Get visual property.
  28358. */
  28359. SeriesData.prototype.getVisual = function (key) {
  28360. var visual = this._visual;
  28361. return visual && visual[key];
  28362. };
  28363. SeriesData.prototype.setVisual = function (kvObj, val) {
  28364. this._visual = this._visual || {};
  28365. if (isObject$2(kvObj)) {
  28366. extend(this._visual, kvObj);
  28367. } else {
  28368. this._visual[kvObj] = val;
  28369. }
  28370. };
  28371. /**
  28372. * Get visual property of single data item
  28373. */
  28374. // eslint-disable-next-line
  28375. SeriesData.prototype.getItemVisual = function (idx, key) {
  28376. var itemVisual = this._itemVisuals[idx];
  28377. var val = itemVisual && itemVisual[key];
  28378. if (val == null) {
  28379. // Use global visual property
  28380. return this.getVisual(key);
  28381. }
  28382. return val;
  28383. };
  28384. /**
  28385. * If exists visual property of single data item
  28386. */
  28387. SeriesData.prototype.hasItemVisual = function () {
  28388. return this._itemVisuals.length > 0;
  28389. };
  28390. /**
  28391. * Make sure itemVisual property is unique
  28392. */
  28393. // TODO: use key to save visual to reduce memory.
  28394. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  28395. var itemVisuals = this._itemVisuals;
  28396. var itemVisual = itemVisuals[idx];
  28397. if (!itemVisual) {
  28398. itemVisual = itemVisuals[idx] = {};
  28399. }
  28400. var val = itemVisual[key];
  28401. if (val == null) {
  28402. val = this.getVisual(key);
  28403. // TODO Performance?
  28404. if (isArray(val)) {
  28405. val = val.slice();
  28406. } else if (isObject$2(val)) {
  28407. val = extend({}, val);
  28408. }
  28409. itemVisual[key] = val;
  28410. }
  28411. return val;
  28412. };
  28413. // eslint-disable-next-line
  28414. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  28415. var itemVisual = this._itemVisuals[idx] || {};
  28416. this._itemVisuals[idx] = itemVisual;
  28417. if (isObject$2(key)) {
  28418. extend(itemVisual, key);
  28419. } else {
  28420. itemVisual[key] = value;
  28421. }
  28422. };
  28423. /**
  28424. * Clear itemVisuals and list visual.
  28425. */
  28426. SeriesData.prototype.clearAllVisual = function () {
  28427. this._visual = {};
  28428. this._itemVisuals = [];
  28429. };
  28430. SeriesData.prototype.setLayout = function (key, val) {
  28431. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  28432. };
  28433. /**
  28434. * Get layout property.
  28435. */
  28436. SeriesData.prototype.getLayout = function (key) {
  28437. return this._layout[key];
  28438. };
  28439. /**
  28440. * Get layout of single data item
  28441. */
  28442. SeriesData.prototype.getItemLayout = function (idx) {
  28443. return this._itemLayouts[idx];
  28444. };
  28445. /**
  28446. * Set layout of single data item
  28447. */
  28448. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  28449. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  28450. };
  28451. /**
  28452. * Clear all layout of single data item
  28453. */
  28454. SeriesData.prototype.clearItemLayouts = function () {
  28455. this._itemLayouts.length = 0;
  28456. };
  28457. /**
  28458. * Set graphic element relative to data. It can be set as null
  28459. */
  28460. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  28461. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  28462. setCommonECData(seriesIndex, this.dataType, idx, el);
  28463. this._graphicEls[idx] = el;
  28464. };
  28465. SeriesData.prototype.getItemGraphicEl = function (idx) {
  28466. return this._graphicEls[idx];
  28467. };
  28468. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  28469. each(this._graphicEls, function (el, idx) {
  28470. if (el) {
  28471. cb && cb.call(context, el, idx);
  28472. }
  28473. });
  28474. };
  28475. /**
  28476. * Shallow clone a new list except visual and layout properties, and graph elements.
  28477. * New list only change the indices.
  28478. */
  28479. SeriesData.prototype.cloneShallow = function (list) {
  28480. if (!list) {
  28481. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  28482. }
  28483. transferProperties(list, this);
  28484. list._store = this._store;
  28485. return list;
  28486. };
  28487. /**
  28488. * Wrap some method to add more feature
  28489. */
  28490. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  28491. var originalMethod = this[methodName];
  28492. if (!isFunction(originalMethod)) {
  28493. return;
  28494. }
  28495. this.__wrappedMethods = this.__wrappedMethods || [];
  28496. this.__wrappedMethods.push(methodName);
  28497. this[methodName] = function () {
  28498. var res = originalMethod.apply(this, arguments);
  28499. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28500. };
  28501. };
  28502. // ----------------------------------------------------------
  28503. // A work around for internal method visiting private member.
  28504. // ----------------------------------------------------------
  28505. SeriesData.internalField = function () {
  28506. prepareInvertedIndex = function (data) {
  28507. var invertedIndicesMap = data._invertedIndicesMap;
  28508. each(invertedIndicesMap, function (invertedIndices, dim) {
  28509. var dimInfo = data._dimInfos[dim];
  28510. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  28511. var ordinalMeta = dimInfo.ordinalMeta;
  28512. var store = data._store;
  28513. if (ordinalMeta) {
  28514. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length);
  28515. // The default value of TypedArray is 0. To avoid miss
  28516. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  28517. for (var i = 0; i < invertedIndices.length; i++) {
  28518. invertedIndices[i] = INDEX_NOT_FOUND;
  28519. }
  28520. for (var i = 0; i < store.count(); i++) {
  28521. // Only support the case that all values are distinct.
  28522. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  28523. }
  28524. }
  28525. });
  28526. };
  28527. getIdNameFromStore = function (data, dimIdx, idx) {
  28528. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  28529. };
  28530. /**
  28531. * @see the comment of `List['getId']`.
  28532. */
  28533. getId = function (data, rawIndex) {
  28534. var id = data._idList[rawIndex];
  28535. if (id == null && data._idDimIdx != null) {
  28536. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  28537. }
  28538. if (id == null) {
  28539. id = ID_PREFIX + rawIndex;
  28540. }
  28541. return id;
  28542. };
  28543. normalizeDimensions = function (dimensions) {
  28544. if (!isArray(dimensions)) {
  28545. dimensions = dimensions != null ? [dimensions] : [];
  28546. }
  28547. return dimensions;
  28548. };
  28549. /**
  28550. * Data in excludeDimensions is copied, otherwise transferred.
  28551. */
  28552. cloneListForMapAndSample = function (original) {
  28553. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel);
  28554. // FIXME If needs stackedOn, value may already been stacked
  28555. transferProperties(list, original);
  28556. return list;
  28557. };
  28558. transferProperties = function (target, source) {
  28559. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  28560. if (source.hasOwnProperty(propName)) {
  28561. target[propName] = source[propName];
  28562. }
  28563. });
  28564. target.__wrappedMethods = source.__wrappedMethods;
  28565. each(CLONE_PROPERTIES, function (propName) {
  28566. target[propName] = clone(source[propName]);
  28567. });
  28568. target._calculationInfo = extend({}, source._calculationInfo);
  28569. };
  28570. makeIdFromName = function (data, idx) {
  28571. var nameList = data._nameList;
  28572. var idList = data._idList;
  28573. var nameDimIdx = data._nameDimIdx;
  28574. var idDimIdx = data._idDimIdx;
  28575. var name = nameList[idx];
  28576. var id = idList[idx];
  28577. if (name == null && nameDimIdx != null) {
  28578. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  28579. }
  28580. if (id == null && idDimIdx != null) {
  28581. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  28582. }
  28583. if (id == null && name != null) {
  28584. var nameRepeatCount = data._nameRepeatCount;
  28585. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  28586. id = name;
  28587. if (nmCnt > 1) {
  28588. id += '__ec__' + nmCnt;
  28589. }
  28590. idList[idx] = id;
  28591. }
  28592. };
  28593. }();
  28594. return SeriesData;
  28595. }();
  28596. /**
  28597. * For outside usage compat (like echarts-gl are using it).
  28598. */
  28599. function createDimensions(source, opt) {
  28600. return prepareSeriesDataSchema(source, opt).dimensions;
  28601. }
  28602. /**
  28603. * This method builds the relationship between:
  28604. * + "what the coord sys or series requires (see `coordDimensions`)",
  28605. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  28606. * + "what the data source provids (see `source`)".
  28607. *
  28608. * Some guess strategy will be adapted if user does not define something.
  28609. * If no 'value' dimension specified, the first no-named dimension will be
  28610. * named as 'value'.
  28611. *
  28612. * @return The results are always sorted by `storeDimIndex` asc.
  28613. */
  28614. function prepareSeriesDataSchema(
  28615. // TODO: TYPE completeDimensions type
  28616. source, opt) {
  28617. if (!isSourceInstance(source)) {
  28618. source = createSourceFromSeriesDataOption(source);
  28619. }
  28620. opt = opt || {};
  28621. var sysDims = opt.coordDimensions || [];
  28622. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  28623. var coordDimNameMap = createHashMap();
  28624. var resultList = [];
  28625. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount);
  28626. // Try to ignore unused dimensions if sharing a high dimension datastore
  28627. // 30 is an experience value.
  28628. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  28629. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  28630. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  28631. var encodeDef = opt.encodeDefine;
  28632. if (!encodeDef && opt.encodeDefaulter) {
  28633. encodeDef = opt.encodeDefaulter(source, dimCount);
  28634. }
  28635. var encodeDefMap = createHashMap(encodeDef);
  28636. var indicesMap = new CtorInt32Array(dimCount);
  28637. for (var i = 0; i < indicesMap.length; i++) {
  28638. indicesMap[i] = -1;
  28639. }
  28640. function getResultItem(dimIdx) {
  28641. var idx = indicesMap[dimIdx];
  28642. if (idx < 0) {
  28643. var dimDefItemRaw = dimsDef[dimIdx];
  28644. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  28645. name: dimDefItemRaw
  28646. };
  28647. var resultItem = new SeriesDimensionDefine();
  28648. var userDimName = dimDefItem.name;
  28649. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  28650. // Only if `series.dimensions` is defined in option
  28651. // displayName, will be set, and dimension will be displayed vertically in
  28652. // tooltip by default.
  28653. resultItem.name = resultItem.displayName = userDimName;
  28654. }
  28655. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28656. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28657. var newIdx = resultList.length;
  28658. indicesMap[dimIdx] = newIdx;
  28659. resultItem.storeDimIndex = dimIdx;
  28660. resultList.push(resultItem);
  28661. return resultItem;
  28662. }
  28663. return resultList[idx];
  28664. }
  28665. if (!omitUnusedDimensions) {
  28666. for (var i = 0; i < dimCount; i++) {
  28667. getResultItem(i);
  28668. }
  28669. }
  28670. // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  28671. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  28672. var dataDims = normalizeToArray(dataDimsRaw).slice();
  28673. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28674. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28675. // this case.
  28676. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28677. encodeDefMap.set(coordDim, false);
  28678. return;
  28679. }
  28680. var validDataDims = encodeDefMap.set(coordDim, []);
  28681. each(dataDims, function (resultDimIdxOrName, idx) {
  28682. // The input resultDimIdx can be dim name or index.
  28683. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  28684. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28685. validDataDims[idx] = resultDimIdx;
  28686. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  28687. }
  28688. });
  28689. });
  28690. // Apply templates and default order from `sysDims`.
  28691. var availDimIdx = 0;
  28692. each(sysDims, function (sysDimItemRaw) {
  28693. var coordDim;
  28694. var sysDimItemDimsDef;
  28695. var sysDimItemOtherDims;
  28696. var sysDimItem;
  28697. if (isString(sysDimItemRaw)) {
  28698. coordDim = sysDimItemRaw;
  28699. sysDimItem = {};
  28700. } else {
  28701. sysDimItem = sysDimItemRaw;
  28702. coordDim = sysDimItem.name;
  28703. var ordinalMeta = sysDimItem.ordinalMeta;
  28704. sysDimItem.ordinalMeta = null;
  28705. sysDimItem = extend({}, sysDimItem);
  28706. sysDimItem.ordinalMeta = ordinalMeta;
  28707. // `coordDimIndex` should not be set directly.
  28708. sysDimItemDimsDef = sysDimItem.dimsDef;
  28709. sysDimItemOtherDims = sysDimItem.otherDims;
  28710. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28711. }
  28712. var dataDims = encodeDefMap.get(coordDim);
  28713. // negative resultDimIdx means no need to mapping.
  28714. if (dataDims === false) {
  28715. return;
  28716. }
  28717. dataDims = normalizeToArray(dataDims);
  28718. // dimensions provides default dim sequences.
  28719. if (!dataDims.length) {
  28720. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28721. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  28722. availDimIdx++;
  28723. }
  28724. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  28725. }
  28726. }
  28727. // Apply templates.
  28728. each(dataDims, function (resultDimIdx, coordDimIndex) {
  28729. var resultItem = getResultItem(resultDimIdx);
  28730. // Coordinate system has a higher priority on dim type than source.
  28731. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  28732. resultItem.type = sysDimItem.type;
  28733. }
  28734. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28735. if (resultItem.name == null && sysDimItemDimsDef) {
  28736. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28737. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  28738. name: sysDimItemDimsDefItem
  28739. });
  28740. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28741. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28742. }
  28743. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28744. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28745. });
  28746. });
  28747. function applyDim(resultItem, coordDim, coordDimIndex) {
  28748. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  28749. resultItem.otherDims[coordDim] = coordDimIndex;
  28750. } else {
  28751. resultItem.coordDim = coordDim;
  28752. resultItem.coordDimIndex = coordDimIndex;
  28753. coordDimNameMap.set(coordDim, true);
  28754. }
  28755. }
  28756. // Make sure the first extra dim is 'value'.
  28757. var generateCoord = opt.generateCoord;
  28758. var generateCoordCount = opt.generateCoordCount;
  28759. var fromZero = generateCoordCount != null;
  28760. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  28761. var extra = generateCoord || 'value';
  28762. function ifNoNameFillWithCoordName(resultItem) {
  28763. if (resultItem.name == null) {
  28764. // Duplication will be removed in the next step.
  28765. resultItem.name = resultItem.coordDim;
  28766. }
  28767. }
  28768. // Set dim `name` and other `coordDim` and other props.
  28769. if (!omitUnusedDimensions) {
  28770. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28771. var resultItem = getResultItem(resultDimIdx);
  28772. var coordDim = resultItem.coordDim;
  28773. if (coordDim == null) {
  28774. // TODO no need to generate coordDim for isExtraCoord?
  28775. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  28776. resultItem.coordDimIndex = 0;
  28777. // Series specified generateCoord is using out.
  28778. if (!generateCoord || generateCoordCount <= 0) {
  28779. resultItem.isExtraCoord = true;
  28780. }
  28781. generateCoordCount--;
  28782. }
  28783. ifNoNameFillWithCoordName(resultItem);
  28784. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must
  28785. // Consider the case:
  28786. // {
  28787. // dataset: {source: [
  28788. // ['2001', 123],
  28789. // ['2002', 456],
  28790. // ...
  28791. // ['The others', 987],
  28792. // ]},
  28793. // series: {type: 'pie'}
  28794. // }
  28795. // The first column should better be treated as a "ordinal" although it
  28796. // might not be detected as an "ordinal" by `guessOrdinal`.
  28797. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  28798. resultItem.type = 'ordinal';
  28799. }
  28800. }
  28801. } else {
  28802. each(resultList, function (resultItem) {
  28803. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  28804. ifNoNameFillWithCoordName(resultItem);
  28805. });
  28806. // Sort dimensions: there are some rule that use the last dim as label,
  28807. // and for some latter travel process easier.
  28808. resultList.sort(function (item0, item1) {
  28809. return item0.storeDimIndex - item1.storeDimIndex;
  28810. });
  28811. }
  28812. removeDuplication(resultList);
  28813. return new SeriesDataSchema({
  28814. source: source,
  28815. dimensions: resultList,
  28816. fullDimensionCount: dimCount,
  28817. dimensionOmitted: omitUnusedDimensions
  28818. });
  28819. }
  28820. function removeDuplication(result) {
  28821. var duplicationMap = createHashMap();
  28822. for (var i = 0; i < result.length; i++) {
  28823. var dim = result[i];
  28824. var dimOriginalName = dim.name;
  28825. var count = duplicationMap.get(dimOriginalName) || 0;
  28826. if (count > 0) {
  28827. // Starts from 0.
  28828. dim.name = dimOriginalName + (count - 1);
  28829. }
  28830. count++;
  28831. duplicationMap.set(dimOriginalName, count);
  28832. }
  28833. }
  28834. // ??? TODO
  28835. // Originally detect dimCount by data[0]. Should we
  28836. // optimize it to only by sysDims and dimensions and encode.
  28837. // So only necessary dims will be initialized.
  28838. // But
  28839. // (1) custom series should be considered. where other dims
  28840. // may be visited.
  28841. // (2) sometimes user need to calculate bubble size or use visualMap
  28842. // on other dimensions besides coordSys needed.
  28843. // So, dims that is not used by system, should be shared in data store?
  28844. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28845. // Note that the result dimCount should not small than columns count
  28846. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28847. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  28848. each(sysDims, function (sysDimItem) {
  28849. var sysDimItemDimsDef;
  28850. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  28851. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  28852. }
  28853. });
  28854. return dimCount;
  28855. }
  28856. function genCoordDimName(name, map, fromZero) {
  28857. if (fromZero || map.hasKey(name)) {
  28858. var i = 0;
  28859. while (map.hasKey(name + i)) {
  28860. i++;
  28861. }
  28862. name += i;
  28863. }
  28864. map.set(name, true);
  28865. return name;
  28866. }
  28867. /**
  28868. * @class
  28869. * For example:
  28870. * {
  28871. * coordSysName: 'cartesian2d',
  28872. * coordSysDims: ['x', 'y', ...],
  28873. * axisMap: HashMap({
  28874. * x: xAxisModel,
  28875. * y: yAxisModel
  28876. * }),
  28877. * categoryAxisMap: HashMap({
  28878. * x: xAxisModel,
  28879. * y: undefined
  28880. * }),
  28881. * // The index of the first category axis in `coordSysDims`.
  28882. * // `null/undefined` means no category axis exists.
  28883. * firstCategoryDimIndex: 1,
  28884. * // To replace user specified encode.
  28885. * }
  28886. */
  28887. var CoordSysInfo = /** @class */function () {
  28888. function CoordSysInfo(coordSysName) {
  28889. this.coordSysDims = [];
  28890. this.axisMap = createHashMap();
  28891. this.categoryAxisMap = createHashMap();
  28892. this.coordSysName = coordSysName;
  28893. }
  28894. return CoordSysInfo;
  28895. }();
  28896. function getCoordSysInfoBySeries(seriesModel) {
  28897. var coordSysName = seriesModel.get('coordinateSystem');
  28898. var result = new CoordSysInfo(coordSysName);
  28899. var fetch = fetchers[coordSysName];
  28900. if (fetch) {
  28901. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28902. return result;
  28903. }
  28904. }
  28905. var fetchers = {
  28906. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28907. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  28908. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  28909. if ("development" !== 'production') {
  28910. if (!xAxisModel) {
  28911. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  28912. }
  28913. if (!yAxisModel) {
  28914. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  28915. }
  28916. }
  28917. result.coordSysDims = ['x', 'y'];
  28918. axisMap.set('x', xAxisModel);
  28919. axisMap.set('y', yAxisModel);
  28920. if (isCategory(xAxisModel)) {
  28921. categoryAxisMap.set('x', xAxisModel);
  28922. result.firstCategoryDimIndex = 0;
  28923. }
  28924. if (isCategory(yAxisModel)) {
  28925. categoryAxisMap.set('y', yAxisModel);
  28926. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28927. }
  28928. },
  28929. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28930. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  28931. if ("development" !== 'production') {
  28932. if (!singleAxisModel) {
  28933. throw new Error('singleAxis should be specified.');
  28934. }
  28935. }
  28936. result.coordSysDims = ['single'];
  28937. axisMap.set('single', singleAxisModel);
  28938. if (isCategory(singleAxisModel)) {
  28939. categoryAxisMap.set('single', singleAxisModel);
  28940. result.firstCategoryDimIndex = 0;
  28941. }
  28942. },
  28943. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28944. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  28945. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28946. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28947. if ("development" !== 'production') {
  28948. if (!angleAxisModel) {
  28949. throw new Error('angleAxis option not found');
  28950. }
  28951. if (!radiusAxisModel) {
  28952. throw new Error('radiusAxis option not found');
  28953. }
  28954. }
  28955. result.coordSysDims = ['radius', 'angle'];
  28956. axisMap.set('radius', radiusAxisModel);
  28957. axisMap.set('angle', angleAxisModel);
  28958. if (isCategory(radiusAxisModel)) {
  28959. categoryAxisMap.set('radius', radiusAxisModel);
  28960. result.firstCategoryDimIndex = 0;
  28961. }
  28962. if (isCategory(angleAxisModel)) {
  28963. categoryAxisMap.set('angle', angleAxisModel);
  28964. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28965. }
  28966. },
  28967. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28968. result.coordSysDims = ['lng', 'lat'];
  28969. },
  28970. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28971. var ecModel = seriesModel.ecModel;
  28972. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  28973. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28974. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28975. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28976. var axisDim = coordSysDims[index];
  28977. axisMap.set(axisDim, axisModel);
  28978. if (isCategory(axisModel)) {
  28979. categoryAxisMap.set(axisDim, axisModel);
  28980. if (result.firstCategoryDimIndex == null) {
  28981. result.firstCategoryDimIndex = index;
  28982. }
  28983. }
  28984. });
  28985. }
  28986. };
  28987. function isCategory(axisModel) {
  28988. return axisModel.get('type') === 'category';
  28989. }
  28990. /**
  28991. * Note that it is too complicated to support 3d stack by value
  28992. * (have to create two-dimension inverted index), so in 3d case
  28993. * we just support that stacked by index.
  28994. *
  28995. * @param seriesModel
  28996. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  28997. * The input will be modified.
  28998. * @param opt
  28999. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29000. * @param opt.byIndex=false
  29001. * @return calculationInfo
  29002. * {
  29003. * stackedDimension: string
  29004. * stackedByDimension: string
  29005. * isStackedByIndex: boolean
  29006. * stackedOverDimension: string
  29007. * stackResultDimension: string
  29008. * }
  29009. */
  29010. function enableDataStack(seriesModel, dimensionsInput, opt) {
  29011. opt = opt || {};
  29012. var byIndex = opt.byIndex;
  29013. var stackedCoordDimension = opt.stackedCoordDimension;
  29014. var dimensionDefineList;
  29015. var schema;
  29016. var store;
  29017. if (isLegacyDimensionsInput(dimensionsInput)) {
  29018. dimensionDefineList = dimensionsInput;
  29019. } else {
  29020. schema = dimensionsInput.schema;
  29021. dimensionDefineList = schema.dimensions;
  29022. store = dimensionsInput.store;
  29023. }
  29024. // Compatibal: when `stack` is set as '', do not stack.
  29025. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29026. var stackedByDimInfo;
  29027. var stackedDimInfo;
  29028. var stackResultDimension;
  29029. var stackedOverDimension;
  29030. each(dimensionDefineList, function (dimensionInfo, index) {
  29031. if (isString(dimensionInfo)) {
  29032. dimensionDefineList[index] = dimensionInfo = {
  29033. name: dimensionInfo
  29034. };
  29035. }
  29036. if (mayStack && !dimensionInfo.isExtraCoord) {
  29037. // Find the first ordinal dimension as the stackedByDimInfo.
  29038. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29039. stackedByDimInfo = dimensionInfo;
  29040. }
  29041. // Find the first stackable dimension as the stackedDimInfo.
  29042. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29043. stackedDimInfo = dimensionInfo;
  29044. }
  29045. }
  29046. });
  29047. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29048. // Compatible with previous design, value axis (time axis) only stack by index.
  29049. // It may make sense if the user provides elaborately constructed data.
  29050. byIndex = true;
  29051. }
  29052. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29053. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29054. // might not be a good way.
  29055. if (stackedDimInfo) {
  29056. // Use a weird name that not duplicated with other names.
  29057. // Also need to use seriesModel.id as postfix because different
  29058. // series may share same data store. The stack dimension needs to be distinguished.
  29059. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  29060. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id;
  29061. // Create inverted index to fast query index by value.
  29062. if (stackedByDimInfo) {
  29063. stackedByDimInfo.createInvertedIndices = true;
  29064. }
  29065. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29066. var stackedDimType = stackedDimInfo.type;
  29067. var stackedDimCoordIndex_1 = 0;
  29068. each(dimensionDefineList, function (dimensionInfo) {
  29069. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29070. stackedDimCoordIndex_1++;
  29071. }
  29072. });
  29073. var stackedOverDimensionDefine = {
  29074. name: stackResultDimension,
  29075. coordDim: stackedDimCoordDim_1,
  29076. coordDimIndex: stackedDimCoordIndex_1,
  29077. type: stackedDimType,
  29078. isExtraCoord: true,
  29079. isCalculationCoord: true,
  29080. storeDimIndex: dimensionDefineList.length
  29081. };
  29082. var stackResultDimensionDefine = {
  29083. name: stackedOverDimension,
  29084. // This dimension contains stack base (generally, 0), so do not set it as
  29085. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29086. coordDim: stackedOverDimension,
  29087. coordDimIndex: stackedDimCoordIndex_1 + 1,
  29088. type: stackedDimType,
  29089. isExtraCoord: true,
  29090. isCalculationCoord: true,
  29091. storeDimIndex: dimensionDefineList.length + 1
  29092. };
  29093. if (schema) {
  29094. if (store) {
  29095. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  29096. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  29097. }
  29098. schema.appendCalculationDimension(stackedOverDimensionDefine);
  29099. schema.appendCalculationDimension(stackResultDimensionDefine);
  29100. } else {
  29101. dimensionDefineList.push(stackedOverDimensionDefine);
  29102. dimensionDefineList.push(stackResultDimensionDefine);
  29103. }
  29104. }
  29105. return {
  29106. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29107. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29108. isStackedByIndex: byIndex,
  29109. stackedOverDimension: stackedOverDimension,
  29110. stackResultDimension: stackResultDimension
  29111. };
  29112. }
  29113. function isLegacyDimensionsInput(dimensionsInput) {
  29114. return !isSeriesDataSchema(dimensionsInput.schema);
  29115. }
  29116. function isDimensionStacked(data, stackedDim) {
  29117. // Each single series only maps to one pair of axis. So we do not need to
  29118. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29119. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29120. }
  29121. function getStackedDimension(data, targetDim) {
  29122. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29123. }
  29124. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  29125. var coordSysName = seriesModel.get('coordinateSystem');
  29126. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29127. var coordSysDimDefs;
  29128. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29129. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29130. var dimInfo = {
  29131. name: dim
  29132. };
  29133. var axisModel = coordSysInfo.axisMap.get(dim);
  29134. if (axisModel) {
  29135. var axisType = axisModel.get('type');
  29136. dimInfo.type = getDimensionTypeByAxis(axisType);
  29137. }
  29138. return dimInfo;
  29139. });
  29140. }
  29141. if (!coordSysDimDefs) {
  29142. // Get dimensions from registered coordinate system
  29143. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29144. }
  29145. return coordSysDimDefs;
  29146. }
  29147. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  29148. var firstCategoryDimIndex;
  29149. var hasNameEncode;
  29150. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29151. var coordDim = dimInfo.coordDim;
  29152. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29153. if (categoryAxisModel) {
  29154. if (firstCategoryDimIndex == null) {
  29155. firstCategoryDimIndex = dimIndex;
  29156. }
  29157. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29158. if (createInvertedIndices) {
  29159. dimInfo.createInvertedIndices = true;
  29160. }
  29161. }
  29162. if (dimInfo.otherDims.itemName != null) {
  29163. hasNameEncode = true;
  29164. }
  29165. });
  29166. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29167. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29168. }
  29169. return firstCategoryDimIndex;
  29170. }
  29171. /**
  29172. * Caution: there are side effects to `sourceManager` in this method.
  29173. * Should better only be called in `Series['getInitialData']`.
  29174. */
  29175. function createSeriesData(sourceRaw, seriesModel, opt) {
  29176. opt = opt || {};
  29177. var sourceManager = seriesModel.getSourceManager();
  29178. var source;
  29179. var isOriginalSource = false;
  29180. if (sourceRaw) {
  29181. isOriginalSource = true;
  29182. source = createSourceFromSeriesDataOption(sourceRaw);
  29183. } else {
  29184. source = sourceManager.getSource();
  29185. // Is series.data. not dataset.
  29186. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  29187. }
  29188. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29189. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  29190. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29191. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  29192. var createDimensionOptions = {
  29193. coordDimensions: coordSysDimDefs,
  29194. generateCoord: opt.generateCoord,
  29195. encodeDefine: seriesModel.getEncode(),
  29196. encodeDefaulter: encodeDefaulter,
  29197. canOmitUnusedDimensions: !isOriginalSource
  29198. };
  29199. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  29200. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  29201. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  29202. var stackCalculationInfo = enableDataStack(seriesModel, {
  29203. schema: schema,
  29204. store: store
  29205. });
  29206. var data = new SeriesData(schema, seriesModel);
  29207. data.setCalculationInfo(stackCalculationInfo);
  29208. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29209. // Use dataIndex as ordinal value in categoryAxis
  29210. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29211. } : null;
  29212. data.hasItemOption = false;
  29213. data.initData(
  29214. // Try to reuse the data store in sourceManager if using dataset.
  29215. isOriginalSource ? source : store, null, dimValueGetter);
  29216. return data;
  29217. }
  29218. function isNeedCompleteOrdinalData(source) {
  29219. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29220. var sampleItem = firstDataNotNull(source.data || []);
  29221. return !isArray(getDataItemValue(sampleItem));
  29222. }
  29223. }
  29224. function firstDataNotNull(arr) {
  29225. var i = 0;
  29226. while (i < arr.length && arr[i] == null) {
  29227. i++;
  29228. }
  29229. return arr[i];
  29230. }
  29231. var Scale = /** @class */function () {
  29232. function Scale(setting) {
  29233. this._setting = setting || {};
  29234. this._extent = [Infinity, -Infinity];
  29235. }
  29236. Scale.prototype.getSetting = function (name) {
  29237. return this._setting[name];
  29238. };
  29239. /**
  29240. * Set extent from data
  29241. */
  29242. Scale.prototype.unionExtent = function (other) {
  29243. var extent = this._extent;
  29244. other[0] < extent[0] && (extent[0] = other[0]);
  29245. other[1] > extent[1] && (extent[1] = other[1]);
  29246. // not setExtent because in log axis it may transformed to power
  29247. // this.setExtent(extent[0], extent[1]);
  29248. };
  29249. /**
  29250. * Set extent from data
  29251. */
  29252. Scale.prototype.unionExtentFromData = function (data, dim) {
  29253. this.unionExtent(data.getApproximateExtent(dim));
  29254. };
  29255. /**
  29256. * Get extent
  29257. *
  29258. * Extent is always in increase order.
  29259. */
  29260. Scale.prototype.getExtent = function () {
  29261. return this._extent.slice();
  29262. };
  29263. /**
  29264. * Set extent
  29265. */
  29266. Scale.prototype.setExtent = function (start, end) {
  29267. var thisExtent = this._extent;
  29268. if (!isNaN(start)) {
  29269. thisExtent[0] = start;
  29270. }
  29271. if (!isNaN(end)) {
  29272. thisExtent[1] = end;
  29273. }
  29274. };
  29275. /**
  29276. * If value is in extent range
  29277. */
  29278. Scale.prototype.isInExtentRange = function (value) {
  29279. return this._extent[0] <= value && this._extent[1] >= value;
  29280. };
  29281. /**
  29282. * When axis extent depends on data and no data exists,
  29283. * axis ticks should not be drawn, which is named 'blank'.
  29284. */
  29285. Scale.prototype.isBlank = function () {
  29286. return this._isBlank;
  29287. };
  29288. /**
  29289. * When axis extent depends on data and no data exists,
  29290. * axis ticks should not be drawn, which is named 'blank'.
  29291. */
  29292. Scale.prototype.setBlank = function (isBlank) {
  29293. this._isBlank = isBlank;
  29294. };
  29295. return Scale;
  29296. }();
  29297. enableClassManagement(Scale);
  29298. var uidBase = 0;
  29299. var OrdinalMeta = /** @class */function () {
  29300. function OrdinalMeta(opt) {
  29301. this.categories = opt.categories || [];
  29302. this._needCollect = opt.needCollect;
  29303. this._deduplication = opt.deduplication;
  29304. this.uid = ++uidBase;
  29305. }
  29306. OrdinalMeta.createByAxisModel = function (axisModel) {
  29307. var option = axisModel.option;
  29308. var data = option.data;
  29309. var categories = data && map(data, getName);
  29310. return new OrdinalMeta({
  29311. categories: categories,
  29312. needCollect: !categories,
  29313. // deduplication is default in axis.
  29314. deduplication: option.dedplication !== false
  29315. });
  29316. };
  29317. OrdinalMeta.prototype.getOrdinal = function (category) {
  29318. // @ts-ignore
  29319. return this._getOrCreateMap().get(category);
  29320. };
  29321. /**
  29322. * @return The ordinal. If not found, return NaN.
  29323. */
  29324. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29325. var index;
  29326. var needCollect = this._needCollect;
  29327. // The value of category dim can be the index of the given category set.
  29328. // This feature is only supported when !needCollect, because we should
  29329. // consider a common case: a value is 2017, which is a number but is
  29330. // expected to be tread as a category. This case usually happen in dataset,
  29331. // where it happent to be no need of the index feature.
  29332. if (!isString(category) && !needCollect) {
  29333. return category;
  29334. }
  29335. // Optimize for the scenario:
  29336. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29337. // data has been ensured not duplicate and is large data.
  29338. // Notice, if a dataset dimension provide categroies, usually echarts
  29339. // should remove duplication except user tell echarts dont do that
  29340. // (set axis.deduplication = false), because echarts do not know whether
  29341. // the values in the category dimension has duplication (consider the
  29342. // parallel-aqi example)
  29343. if (needCollect && !this._deduplication) {
  29344. index = this.categories.length;
  29345. this.categories[index] = category;
  29346. return index;
  29347. }
  29348. var map = this._getOrCreateMap();
  29349. // @ts-ignore
  29350. index = map.get(category);
  29351. if (index == null) {
  29352. if (needCollect) {
  29353. index = this.categories.length;
  29354. this.categories[index] = category;
  29355. // @ts-ignore
  29356. map.set(category, index);
  29357. } else {
  29358. index = NaN;
  29359. }
  29360. }
  29361. return index;
  29362. };
  29363. // Consider big data, do not create map until needed.
  29364. OrdinalMeta.prototype._getOrCreateMap = function () {
  29365. return this._map || (this._map = createHashMap(this.categories));
  29366. };
  29367. return OrdinalMeta;
  29368. }();
  29369. function getName(obj) {
  29370. if (isObject(obj) && obj.value != null) {
  29371. return obj.value;
  29372. } else {
  29373. return obj + '';
  29374. }
  29375. }
  29376. function isValueNice(val) {
  29377. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  29378. var f = Math.abs(val / exp10);
  29379. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  29380. }
  29381. function isIntervalOrLogScale(scale) {
  29382. return scale.type === 'interval' || scale.type === 'log';
  29383. }
  29384. /**
  29385. * @param extent Both extent[0] and extent[1] should be valid number.
  29386. * Should be extent[0] < extent[1].
  29387. * @param splitNumber splitNumber should be >= 1.
  29388. */
  29389. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29390. var result = {};
  29391. var span = extent[1] - extent[0];
  29392. var interval = result.interval = nice(span / splitNumber, true);
  29393. if (minInterval != null && interval < minInterval) {
  29394. interval = result.interval = minInterval;
  29395. }
  29396. if (maxInterval != null && interval > maxInterval) {
  29397. interval = result.interval = maxInterval;
  29398. }
  29399. // Tow more digital for tick.
  29400. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29401. // Niced extent inside original extent
  29402. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  29403. fixExtent(niceTickExtent, extent);
  29404. return result;
  29405. }
  29406. function increaseInterval(interval) {
  29407. var exp10 = Math.pow(10, quantityExponent(interval));
  29408. // Increase interval
  29409. var f = interval / exp10;
  29410. if (!f) {
  29411. f = 1;
  29412. } else if (f === 2) {
  29413. f = 3;
  29414. } else if (f === 3) {
  29415. f = 5;
  29416. } else {
  29417. // f is 1 or 5
  29418. f *= 2;
  29419. }
  29420. return round(f * exp10);
  29421. }
  29422. /**
  29423. * @return interval precision
  29424. */
  29425. function getIntervalPrecision(interval) {
  29426. // Tow more digital for tick.
  29427. return getPrecision(interval) + 2;
  29428. }
  29429. function clamp(niceTickExtent, idx, extent) {
  29430. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29431. }
  29432. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29433. function fixExtent(niceTickExtent, extent) {
  29434. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29435. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29436. clamp(niceTickExtent, 0, extent);
  29437. clamp(niceTickExtent, 1, extent);
  29438. if (niceTickExtent[0] > niceTickExtent[1]) {
  29439. niceTickExtent[0] = niceTickExtent[1];
  29440. }
  29441. }
  29442. function contain$1(val, extent) {
  29443. return val >= extent[0] && val <= extent[1];
  29444. }
  29445. function normalize$1(val, extent) {
  29446. if (extent[1] === extent[0]) {
  29447. return 0.5;
  29448. }
  29449. return (val - extent[0]) / (extent[1] - extent[0]);
  29450. }
  29451. function scale$2(val, extent) {
  29452. return val * (extent[1] - extent[0]) + extent[0];
  29453. }
  29454. var OrdinalScale = /** @class */function (_super) {
  29455. __extends(OrdinalScale, _super);
  29456. function OrdinalScale(setting) {
  29457. var _this = _super.call(this, setting) || this;
  29458. _this.type = 'ordinal';
  29459. var ordinalMeta = _this.getSetting('ordinalMeta');
  29460. // Caution: Should not use instanceof, consider ec-extensions using
  29461. // import approach to get OrdinalMeta class.
  29462. if (!ordinalMeta) {
  29463. ordinalMeta = new OrdinalMeta({});
  29464. }
  29465. if (isArray(ordinalMeta)) {
  29466. ordinalMeta = new OrdinalMeta({
  29467. categories: map(ordinalMeta, function (item) {
  29468. return isObject(item) ? item.value : item;
  29469. })
  29470. });
  29471. }
  29472. _this._ordinalMeta = ordinalMeta;
  29473. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  29474. return _this;
  29475. }
  29476. OrdinalScale.prototype.parse = function (val) {
  29477. // Caution: Math.round(null) will return `0` rather than `NaN`
  29478. if (val == null) {
  29479. return NaN;
  29480. }
  29481. return isString(val) ? this._ordinalMeta.getOrdinal(val)
  29482. // val might be float.
  29483. : Math.round(val);
  29484. };
  29485. OrdinalScale.prototype.contain = function (rank) {
  29486. rank = this.parse(rank);
  29487. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  29488. };
  29489. /**
  29490. * Normalize given rank or name to linear [0, 1]
  29491. * @param val raw ordinal number.
  29492. * @return normalized value in [0, 1].
  29493. */
  29494. OrdinalScale.prototype.normalize = function (val) {
  29495. val = this._getTickNumber(this.parse(val));
  29496. return normalize$1(val, this._extent);
  29497. };
  29498. /**
  29499. * @param val normalized value in [0, 1].
  29500. * @return raw ordinal number.
  29501. */
  29502. OrdinalScale.prototype.scale = function (val) {
  29503. val = Math.round(scale$2(val, this._extent));
  29504. return this.getRawOrdinalNumber(val);
  29505. };
  29506. OrdinalScale.prototype.getTicks = function () {
  29507. var ticks = [];
  29508. var extent = this._extent;
  29509. var rank = extent[0];
  29510. while (rank <= extent[1]) {
  29511. ticks.push({
  29512. value: rank
  29513. });
  29514. rank++;
  29515. }
  29516. return ticks;
  29517. };
  29518. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  29519. // Not support.
  29520. return;
  29521. };
  29522. /**
  29523. * @see `Ordinal['_ordinalNumbersByTick']`
  29524. */
  29525. OrdinalScale.prototype.setSortInfo = function (info) {
  29526. if (info == null) {
  29527. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  29528. return;
  29529. }
  29530. var infoOrdinalNumbers = info.ordinalNumbers;
  29531. var ordinalsByTick = this._ordinalNumbersByTick = [];
  29532. var ticksByOrdinal = this._ticksByOrdinalNumber = [];
  29533. // Unnecessary support negative tick in `realtimeSort`.
  29534. var tickNum = 0;
  29535. var allCategoryLen = this._ordinalMeta.categories.length;
  29536. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  29537. var ordinalNumber = infoOrdinalNumbers[tickNum];
  29538. ordinalsByTick[tickNum] = ordinalNumber;
  29539. ticksByOrdinal[ordinalNumber] = tickNum;
  29540. }
  29541. // Handle that `series.data` only covers part of the `axis.category.data`.
  29542. var unusedOrdinal = 0;
  29543. for (; tickNum < allCategoryLen; ++tickNum) {
  29544. while (ticksByOrdinal[unusedOrdinal] != null) {
  29545. unusedOrdinal++;
  29546. }
  29547. ordinalsByTick.push(unusedOrdinal);
  29548. ticksByOrdinal[unusedOrdinal] = tickNum;
  29549. }
  29550. };
  29551. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  29552. var ticksByOrdinalNumber = this._ticksByOrdinalNumber;
  29553. // also support ordinal out of range of `ordinalMeta.categories.length`,
  29554. // where ordinal numbers are used as tick value directly.
  29555. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  29556. };
  29557. /**
  29558. * @usage
  29559. * ```js
  29560. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  29561. *
  29562. * // case0
  29563. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  29564. * // case1
  29565. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  29566. * // case2
  29567. * const coord = axis.dataToCoord(ordinalNumber);
  29568. * ```
  29569. *
  29570. * @param {OrdinalNumber} tickNumber index of display
  29571. */
  29572. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  29573. var ordinalNumbersByTick = this._ordinalNumbersByTick;
  29574. // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  29575. // where ordinal numbers are used as tick value directly.
  29576. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  29577. };
  29578. /**
  29579. * Get item on tick
  29580. */
  29581. OrdinalScale.prototype.getLabel = function (tick) {
  29582. if (!this.isBlank()) {
  29583. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  29584. var cateogry = this._ordinalMeta.categories[ordinalNumber];
  29585. // Note that if no data, ordinalMeta.categories is an empty array.
  29586. // Return empty if it's not exist.
  29587. return cateogry == null ? '' : cateogry + '';
  29588. }
  29589. };
  29590. OrdinalScale.prototype.count = function () {
  29591. return this._extent[1] - this._extent[0] + 1;
  29592. };
  29593. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  29594. this.unionExtent(data.getApproximateExtent(dim));
  29595. };
  29596. /**
  29597. * @override
  29598. * If value is in extent range
  29599. */
  29600. OrdinalScale.prototype.isInExtentRange = function (value) {
  29601. value = this._getTickNumber(value);
  29602. return this._extent[0] <= value && this._extent[1] >= value;
  29603. };
  29604. OrdinalScale.prototype.getOrdinalMeta = function () {
  29605. return this._ordinalMeta;
  29606. };
  29607. OrdinalScale.prototype.calcNiceTicks = function () {};
  29608. OrdinalScale.prototype.calcNiceExtent = function () {};
  29609. OrdinalScale.type = 'ordinal';
  29610. return OrdinalScale;
  29611. }(Scale);
  29612. Scale.registerClass(OrdinalScale);
  29613. var roundNumber = round;
  29614. var IntervalScale = /** @class */function (_super) {
  29615. __extends(IntervalScale, _super);
  29616. function IntervalScale() {
  29617. var _this = _super !== null && _super.apply(this, arguments) || this;
  29618. _this.type = 'interval';
  29619. // Step is calculated in adjustExtent.
  29620. _this._interval = 0;
  29621. _this._intervalPrecision = 2;
  29622. return _this;
  29623. }
  29624. IntervalScale.prototype.parse = function (val) {
  29625. return val;
  29626. };
  29627. IntervalScale.prototype.contain = function (val) {
  29628. return contain$1(val, this._extent);
  29629. };
  29630. IntervalScale.prototype.normalize = function (val) {
  29631. return normalize$1(val, this._extent);
  29632. };
  29633. IntervalScale.prototype.scale = function (val) {
  29634. return scale$2(val, this._extent);
  29635. };
  29636. IntervalScale.prototype.setExtent = function (start, end) {
  29637. var thisExtent = this._extent;
  29638. // start,end may be a Number like '25',so...
  29639. if (!isNaN(start)) {
  29640. thisExtent[0] = parseFloat(start);
  29641. }
  29642. if (!isNaN(end)) {
  29643. thisExtent[1] = parseFloat(end);
  29644. }
  29645. };
  29646. IntervalScale.prototype.unionExtent = function (other) {
  29647. var extent = this._extent;
  29648. other[0] < extent[0] && (extent[0] = other[0]);
  29649. other[1] > extent[1] && (extent[1] = other[1]);
  29650. // unionExtent may called by it's sub classes
  29651. this.setExtent(extent[0], extent[1]);
  29652. };
  29653. IntervalScale.prototype.getInterval = function () {
  29654. return this._interval;
  29655. };
  29656. IntervalScale.prototype.setInterval = function (interval) {
  29657. this._interval = interval;
  29658. // Dropped auto calculated niceExtent and use user-set extent.
  29659. // We assume user wants to set both interval, min, max to get a better result.
  29660. this._niceExtent = this._extent.slice();
  29661. this._intervalPrecision = getIntervalPrecision(interval);
  29662. };
  29663. /**
  29664. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  29665. */
  29666. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  29667. var interval = this._interval;
  29668. var extent = this._extent;
  29669. var niceTickExtent = this._niceExtent;
  29670. var intervalPrecision = this._intervalPrecision;
  29671. var ticks = [];
  29672. // If interval is 0, return [];
  29673. if (!interval) {
  29674. return ticks;
  29675. }
  29676. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29677. var safeLimit = 10000;
  29678. if (extent[0] < niceTickExtent[0]) {
  29679. if (expandToNicedExtent) {
  29680. ticks.push({
  29681. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  29682. });
  29683. } else {
  29684. ticks.push({
  29685. value: extent[0]
  29686. });
  29687. }
  29688. }
  29689. var tick = niceTickExtent[0];
  29690. while (tick <= niceTickExtent[1]) {
  29691. ticks.push({
  29692. value: tick
  29693. });
  29694. // Avoid rounding error
  29695. tick = roundNumber(tick + interval, intervalPrecision);
  29696. if (tick === ticks[ticks.length - 1].value) {
  29697. // Consider out of safe float point, e.g.,
  29698. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29699. break;
  29700. }
  29701. if (ticks.length > safeLimit) {
  29702. return [];
  29703. }
  29704. }
  29705. // Consider this case: the last item of ticks is smaller
  29706. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29707. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  29708. if (extent[1] > lastNiceTick) {
  29709. if (expandToNicedExtent) {
  29710. ticks.push({
  29711. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  29712. });
  29713. } else {
  29714. ticks.push({
  29715. value: extent[1]
  29716. });
  29717. }
  29718. }
  29719. return ticks;
  29720. };
  29721. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  29722. var ticks = this.getTicks(true);
  29723. var minorTicks = [];
  29724. var extent = this.getExtent();
  29725. for (var i = 1; i < ticks.length; i++) {
  29726. var nextTick = ticks[i];
  29727. var prevTick = ticks[i - 1];
  29728. var count = 0;
  29729. var minorTicksGroup = [];
  29730. var interval = nextTick.value - prevTick.value;
  29731. var minorInterval = interval / splitNumber;
  29732. while (count < splitNumber - 1) {
  29733. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval);
  29734. // For the first and last interval. The count may be less than splitNumber.
  29735. if (minorTick > extent[0] && minorTick < extent[1]) {
  29736. minorTicksGroup.push(minorTick);
  29737. }
  29738. count++;
  29739. }
  29740. minorTicks.push(minorTicksGroup);
  29741. }
  29742. return minorTicks;
  29743. };
  29744. /**
  29745. * @param opt.precision If 'auto', use nice presision.
  29746. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  29747. */
  29748. IntervalScale.prototype.getLabel = function (data, opt) {
  29749. if (data == null) {
  29750. return '';
  29751. }
  29752. var precision = opt && opt.precision;
  29753. if (precision == null) {
  29754. precision = getPrecision(data.value) || 0;
  29755. } else if (precision === 'auto') {
  29756. // Should be more precise then tick.
  29757. precision = this._intervalPrecision;
  29758. }
  29759. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29760. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29761. var dataNum = roundNumber(data.value, precision, true);
  29762. return addCommas(dataNum);
  29763. };
  29764. /**
  29765. * @param splitNumber By default `5`.
  29766. */
  29767. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  29768. splitNumber = splitNumber || 5;
  29769. var extent = this._extent;
  29770. var span = extent[1] - extent[0];
  29771. if (!isFinite(span)) {
  29772. return;
  29773. }
  29774. // User may set axis min 0 and data are all negative
  29775. // FIXME If it needs to reverse ?
  29776. if (span < 0) {
  29777. span = -span;
  29778. extent.reverse();
  29779. }
  29780. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  29781. this._intervalPrecision = result.intervalPrecision;
  29782. this._interval = result.interval;
  29783. this._niceExtent = result.niceTickExtent;
  29784. };
  29785. IntervalScale.prototype.calcNiceExtent = function (opt) {
  29786. var extent = this._extent;
  29787. // If extent start and end are same, expand them
  29788. if (extent[0] === extent[1]) {
  29789. if (extent[0] !== 0) {
  29790. // Expand extent
  29791. // Note that extents can be both negative. See #13154
  29792. var expandSize = Math.abs(extent[0]);
  29793. // In the fowllowing case
  29794. // Axis has been fixed max 100
  29795. // Plus data are all 100 and axis extent are [100, 100].
  29796. // Extend to the both side will cause expanded max is larger than fixed max.
  29797. // So only expand to the smaller side.
  29798. if (!opt.fixMax) {
  29799. extent[1] += expandSize / 2;
  29800. extent[0] -= expandSize / 2;
  29801. } else {
  29802. extent[0] -= expandSize / 2;
  29803. }
  29804. } else {
  29805. extent[1] = 1;
  29806. }
  29807. }
  29808. var span = extent[1] - extent[0];
  29809. // If there are no data and extent are [Infinity, -Infinity]
  29810. if (!isFinite(span)) {
  29811. extent[0] = 0;
  29812. extent[1] = 1;
  29813. }
  29814. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29815. // let extent = this._extent;
  29816. var interval = this._interval;
  29817. if (!opt.fixMin) {
  29818. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29819. }
  29820. if (!opt.fixMax) {
  29821. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29822. }
  29823. };
  29824. IntervalScale.prototype.setNiceExtent = function (min, max) {
  29825. this._niceExtent = [min, max];
  29826. };
  29827. IntervalScale.type = 'interval';
  29828. return IntervalScale;
  29829. }(Scale);
  29830. Scale.registerClass(IntervalScale);
  29831. /* global Float32Array */
  29832. var supportFloat32Array = typeof Float32Array !== 'undefined';
  29833. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  29834. function createFloat32Array(arg) {
  29835. if (isArray(arg)) {
  29836. // Return self directly if don't support TypedArray.
  29837. return supportFloat32Array ? new Float32Array(arg) : arg;
  29838. }
  29839. // Else is number
  29840. return new Float32ArrayCtor(arg);
  29841. }
  29842. var STACK_PREFIX = '__ec_stack_';
  29843. function getSeriesStackId(seriesModel) {
  29844. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29845. }
  29846. function getAxisKey(axis) {
  29847. return axis.dim + axis.index;
  29848. }
  29849. function prepareLayoutBarSeries(seriesType, ecModel) {
  29850. var seriesModels = [];
  29851. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29852. // Check series coordinate, do layout for cartesian2d only
  29853. if (isOnCartesian(seriesModel)) {
  29854. seriesModels.push(seriesModel);
  29855. }
  29856. });
  29857. return seriesModels;
  29858. }
  29859. /**
  29860. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29861. * values.
  29862. * This works for time axes, value axes, and log axes.
  29863. * For a single time axis, return value is in the form like
  29864. * {'x_0': [1000000]}.
  29865. * The value of 1000000 is in milliseconds.
  29866. */
  29867. function getValueAxesMinGaps(barSeries) {
  29868. /**
  29869. * Map from axis.index to values.
  29870. * For a single time axis, axisValues is in the form like
  29871. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29872. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29873. * series.
  29874. */
  29875. var axisValues = {};
  29876. each(barSeries, function (seriesModel) {
  29877. var cartesian = seriesModel.coordinateSystem;
  29878. var baseAxis = cartesian.getBaseAxis();
  29879. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29880. return;
  29881. }
  29882. var data = seriesModel.getData();
  29883. var key = baseAxis.dim + '_' + baseAxis.index;
  29884. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  29885. var store = data.getStore();
  29886. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  29887. var value = store.get(dimIdx, i);
  29888. if (!axisValues[key]) {
  29889. // No previous data for the axis
  29890. axisValues[key] = [value];
  29891. } else {
  29892. // No value in previous series
  29893. axisValues[key].push(value);
  29894. }
  29895. // Ignore duplicated time values in the same axis
  29896. }
  29897. });
  29898. var axisMinGaps = {};
  29899. for (var key in axisValues) {
  29900. if (axisValues.hasOwnProperty(key)) {
  29901. var valuesInAxis = axisValues[key];
  29902. if (valuesInAxis) {
  29903. // Sort axis values into ascending order to calculate gaps
  29904. valuesInAxis.sort(function (a, b) {
  29905. return a - b;
  29906. });
  29907. var min = null;
  29908. for (var j = 1; j < valuesInAxis.length; ++j) {
  29909. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29910. if (delta > 0) {
  29911. // Ignore 0 delta because they are of the same axis value
  29912. min = min === null ? delta : Math.min(min, delta);
  29913. }
  29914. }
  29915. // Set to null if only have one data
  29916. axisMinGaps[key] = min;
  29917. }
  29918. }
  29919. }
  29920. return axisMinGaps;
  29921. }
  29922. function makeColumnLayout(barSeries) {
  29923. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29924. var seriesInfoList = [];
  29925. each(barSeries, function (seriesModel) {
  29926. var cartesian = seriesModel.coordinateSystem;
  29927. var baseAxis = cartesian.getBaseAxis();
  29928. var axisExtent = baseAxis.getExtent();
  29929. var bandWidth;
  29930. if (baseAxis.type === 'category') {
  29931. bandWidth = baseAxis.getBandWidth();
  29932. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29933. var key = baseAxis.dim + '_' + baseAxis.index;
  29934. var minGap = axisMinGaps[key];
  29935. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29936. var scale = baseAxis.scale.getExtent();
  29937. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29938. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  29939. } else {
  29940. var data = seriesModel.getData();
  29941. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29942. }
  29943. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  29944. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  29945. var barMinWidth = parsePercent$1(
  29946. // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  29947. // the auto-calculated bar width might be less than 0.5 / 1.
  29948. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  29949. var barGap = seriesModel.get('barGap');
  29950. var barCategoryGap = seriesModel.get('barCategoryGap');
  29951. seriesInfoList.push({
  29952. bandWidth: bandWidth,
  29953. barWidth: barWidth,
  29954. barMaxWidth: barMaxWidth,
  29955. barMinWidth: barMinWidth,
  29956. barGap: barGap,
  29957. barCategoryGap: barCategoryGap,
  29958. axisKey: getAxisKey(baseAxis),
  29959. stackId: getSeriesStackId(seriesModel)
  29960. });
  29961. });
  29962. return doCalBarWidthAndOffset(seriesInfoList);
  29963. }
  29964. function doCalBarWidthAndOffset(seriesInfoList) {
  29965. // Columns info on each category axis. Key is cartesian name
  29966. var columnsMap = {};
  29967. each(seriesInfoList, function (seriesInfo, idx) {
  29968. var axisKey = seriesInfo.axisKey;
  29969. var bandWidth = seriesInfo.bandWidth;
  29970. var columnsOnAxis = columnsMap[axisKey] || {
  29971. bandWidth: bandWidth,
  29972. remainedWidth: bandWidth,
  29973. autoWidthCount: 0,
  29974. categoryGap: null,
  29975. gap: '20%',
  29976. stacks: {}
  29977. };
  29978. var stacks = columnsOnAxis.stacks;
  29979. columnsMap[axisKey] = columnsOnAxis;
  29980. var stackId = seriesInfo.stackId;
  29981. if (!stacks[stackId]) {
  29982. columnsOnAxis.autoWidthCount++;
  29983. }
  29984. stacks[stackId] = stacks[stackId] || {
  29985. width: 0,
  29986. maxWidth: 0
  29987. };
  29988. // Caution: In a single coordinate system, these barGrid attributes
  29989. // will be shared by series. Consider that they have default values,
  29990. // only the attributes set on the last series will work.
  29991. // Do not change this fact unless there will be a break change.
  29992. var barWidth = seriesInfo.barWidth;
  29993. if (barWidth && !stacks[stackId].width) {
  29994. // See #6312, do not restrict width.
  29995. stacks[stackId].width = barWidth;
  29996. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29997. columnsOnAxis.remainedWidth -= barWidth;
  29998. }
  29999. var barMaxWidth = seriesInfo.barMaxWidth;
  30000. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30001. var barMinWidth = seriesInfo.barMinWidth;
  30002. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30003. var barGap = seriesInfo.barGap;
  30004. barGap != null && (columnsOnAxis.gap = barGap);
  30005. var barCategoryGap = seriesInfo.barCategoryGap;
  30006. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30007. });
  30008. var result = {};
  30009. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30010. result[coordSysName] = {};
  30011. var stacks = columnsOnAxis.stacks;
  30012. var bandWidth = columnsOnAxis.bandWidth;
  30013. var categoryGapPercent = columnsOnAxis.categoryGap;
  30014. if (categoryGapPercent == null) {
  30015. var columnCount = keys(stacks).length;
  30016. // More columns in one group
  30017. // the spaces between group is smaller. Or the column will be too thin.
  30018. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30019. }
  30020. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30021. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30022. var remainedWidth = columnsOnAxis.remainedWidth;
  30023. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30024. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30025. autoWidth = Math.max(autoWidth, 0);
  30026. // Find if any auto calculated bar exceeded maxBarWidth
  30027. each(stacks, function (column) {
  30028. var maxWidth = column.maxWidth;
  30029. var minWidth = column.minWidth;
  30030. if (!column.width) {
  30031. var finalWidth = autoWidth;
  30032. if (maxWidth && maxWidth < finalWidth) {
  30033. finalWidth = Math.min(maxWidth, remainedWidth);
  30034. }
  30035. // `minWidth` has higher priority. `minWidth` decide that whether the
  30036. // bar is able to be visible. So `minWidth` should not be restricted
  30037. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30038. // the extreme cases for `value` axis, bars are allowed to overlap
  30039. // with each other if `minWidth` specified.
  30040. if (minWidth && minWidth > finalWidth) {
  30041. finalWidth = minWidth;
  30042. }
  30043. if (finalWidth !== autoWidth) {
  30044. column.width = finalWidth;
  30045. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30046. autoWidthCount--;
  30047. }
  30048. } else {
  30049. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30050. // CSS does. Because barWidth can be a percent value, where
  30051. // `barMaxWidth` can be used to restrict the final width.
  30052. var finalWidth = column.width;
  30053. if (maxWidth) {
  30054. finalWidth = Math.min(finalWidth, maxWidth);
  30055. }
  30056. // `minWidth` has higher priority, as described above
  30057. if (minWidth) {
  30058. finalWidth = Math.max(finalWidth, minWidth);
  30059. }
  30060. column.width = finalWidth;
  30061. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30062. autoWidthCount--;
  30063. }
  30064. });
  30065. // Recalculate width again
  30066. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30067. autoWidth = Math.max(autoWidth, 0);
  30068. var widthSum = 0;
  30069. var lastColumn;
  30070. each(stacks, function (column, idx) {
  30071. if (!column.width) {
  30072. column.width = autoWidth;
  30073. }
  30074. lastColumn = column;
  30075. widthSum += column.width * (1 + barGapPercent);
  30076. });
  30077. if (lastColumn) {
  30078. widthSum -= lastColumn.width * barGapPercent;
  30079. }
  30080. var offset = -widthSum / 2;
  30081. each(stacks, function (column, stackId) {
  30082. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30083. bandWidth: bandWidth,
  30084. offset: offset,
  30085. width: column.width
  30086. };
  30087. offset += column.width * (1 + barGapPercent);
  30088. });
  30089. });
  30090. return result;
  30091. }
  30092. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30093. if (barWidthAndOffset && axis) {
  30094. var result = barWidthAndOffset[getAxisKey(axis)];
  30095. if (result != null && seriesModel != null) {
  30096. return result[getSeriesStackId(seriesModel)];
  30097. }
  30098. return result;
  30099. }
  30100. }
  30101. function layout(seriesType, ecModel) {
  30102. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30103. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30104. each(seriesModels, function (seriesModel) {
  30105. var data = seriesModel.getData();
  30106. var cartesian = seriesModel.coordinateSystem;
  30107. var baseAxis = cartesian.getBaseAxis();
  30108. var stackId = getSeriesStackId(seriesModel);
  30109. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30110. var columnOffset = columnLayoutInfo.offset;
  30111. var columnWidth = columnLayoutInfo.width;
  30112. data.setLayout({
  30113. bandWidth: columnLayoutInfo.bandWidth,
  30114. offset: columnOffset,
  30115. size: columnWidth
  30116. });
  30117. });
  30118. }
  30119. // TODO: Do not support stack in large mode yet.
  30120. function createProgressiveLayout(seriesType) {
  30121. return {
  30122. seriesType: seriesType,
  30123. plan: createRenderPlanner(),
  30124. reset: function (seriesModel) {
  30125. if (!isOnCartesian(seriesModel)) {
  30126. return;
  30127. }
  30128. var data = seriesModel.getData();
  30129. var cartesian = seriesModel.coordinateSystem;
  30130. var baseAxis = cartesian.getBaseAxis();
  30131. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30132. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  30133. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30134. var drawBackground = seriesModel.get('showBackground', true);
  30135. var valueDim = data.mapDimension(valueAxis.dim);
  30136. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30137. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  30138. var isValueAxisH = valueAxis.isHorizontal();
  30139. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  30140. var isLarge = isInLargeMode(seriesModel);
  30141. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30142. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim);
  30143. // Layout info.
  30144. var columnWidth = data.getLayout('size');
  30145. var columnOffset = data.getLayout('offset');
  30146. return {
  30147. progress: function (params, data) {
  30148. var count = params.count;
  30149. var largePoints = isLarge && createFloat32Array(count * 3);
  30150. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  30151. var largeDataIndices = isLarge && createFloat32Array(count);
  30152. var coordLayout = cartesian.master.getRect();
  30153. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  30154. var dataIndex;
  30155. var store = data.getStore();
  30156. var idxOffset = 0;
  30157. while ((dataIndex = params.next()) != null) {
  30158. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  30159. var baseValue = store.get(baseDimIdx, dataIndex);
  30160. var baseCoord = valueAxisStart;
  30161. var stackStartValue = void 0;
  30162. // Because of the barMinHeight, we can not use the value in
  30163. // stackResultDimension directly.
  30164. if (stacked) {
  30165. stackStartValue = +value - store.get(valueDimIdx, dataIndex);
  30166. }
  30167. var x = void 0;
  30168. var y = void 0;
  30169. var width = void 0;
  30170. var height = void 0;
  30171. if (isValueAxisH) {
  30172. var coord = cartesian.dataToPoint([value, baseValue]);
  30173. if (stacked) {
  30174. var startCoord = cartesian.dataToPoint([stackStartValue, baseValue]);
  30175. baseCoord = startCoord[0];
  30176. }
  30177. x = baseCoord;
  30178. y = coord[1] + columnOffset;
  30179. width = coord[0] - baseCoord;
  30180. height = columnWidth;
  30181. if (Math.abs(width) < barMinHeight) {
  30182. width = (width < 0 ? -1 : 1) * barMinHeight;
  30183. }
  30184. } else {
  30185. var coord = cartesian.dataToPoint([baseValue, value]);
  30186. if (stacked) {
  30187. var startCoord = cartesian.dataToPoint([baseValue, stackStartValue]);
  30188. baseCoord = startCoord[1];
  30189. }
  30190. x = coord[0] + columnOffset;
  30191. y = baseCoord;
  30192. width = columnWidth;
  30193. height = coord[1] - baseCoord;
  30194. if (Math.abs(height) < barMinHeight) {
  30195. // Include zero to has a positive bar
  30196. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30197. }
  30198. }
  30199. if (!isLarge) {
  30200. data.setItemLayout(dataIndex, {
  30201. x: x,
  30202. y: y,
  30203. width: width,
  30204. height: height
  30205. });
  30206. } else {
  30207. largePoints[idxOffset] = x;
  30208. largePoints[idxOffset + 1] = y;
  30209. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  30210. if (largeBackgroundPoints) {
  30211. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  30212. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  30213. largeBackgroundPoints[idxOffset + 2] = bgSize;
  30214. }
  30215. largeDataIndices[dataIndex] = dataIndex;
  30216. }
  30217. idxOffset += 3;
  30218. }
  30219. if (isLarge) {
  30220. data.setLayout({
  30221. largePoints: largePoints,
  30222. largeDataIndices: largeDataIndices,
  30223. largeBackgroundPoints: largeBackgroundPoints,
  30224. valueAxisHorizontal: isValueAxisH
  30225. });
  30226. }
  30227. }
  30228. };
  30229. }
  30230. };
  30231. }
  30232. function isOnCartesian(seriesModel) {
  30233. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30234. }
  30235. function isInLargeMode(seriesModel) {
  30236. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30237. }
  30238. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30239. function getValueAxisStart(baseAxis, valueAxis) {
  30240. var startValue = valueAxis.model.get('startValue');
  30241. if (!startValue) {
  30242. startValue = 0;
  30243. }
  30244. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? startValue > 0 ? startValue : 1 : startValue));
  30245. }
  30246. // FIXME 公用?
  30247. var bisect = function (a, x, lo, hi) {
  30248. while (lo < hi) {
  30249. var mid = lo + hi >>> 1;
  30250. if (a[mid][1] < x) {
  30251. lo = mid + 1;
  30252. } else {
  30253. hi = mid;
  30254. }
  30255. }
  30256. return lo;
  30257. };
  30258. var TimeScale = /** @class */function (_super) {
  30259. __extends(TimeScale, _super);
  30260. function TimeScale(settings) {
  30261. var _this = _super.call(this, settings) || this;
  30262. _this.type = 'time';
  30263. return _this;
  30264. }
  30265. /**
  30266. * Get label is mainly for other components like dataZoom, tooltip.
  30267. */
  30268. TimeScale.prototype.getLabel = function (tick) {
  30269. var useUTC = this.getSetting('useUTC');
  30270. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30271. };
  30272. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30273. var isUTC = this.getSetting('useUTC');
  30274. var lang = this.getSetting('locale');
  30275. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30276. };
  30277. /**
  30278. * @override
  30279. */
  30280. TimeScale.prototype.getTicks = function () {
  30281. var interval = this._interval;
  30282. var extent = this._extent;
  30283. var ticks = [];
  30284. // If interval is 0, return [];
  30285. if (!interval) {
  30286. return ticks;
  30287. }
  30288. ticks.push({
  30289. value: extent[0],
  30290. level: 0
  30291. });
  30292. var useUTC = this.getSetting('useUTC');
  30293. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30294. ticks = ticks.concat(innerTicks);
  30295. ticks.push({
  30296. value: extent[1],
  30297. level: 0
  30298. });
  30299. return ticks;
  30300. };
  30301. TimeScale.prototype.calcNiceExtent = function (opt) {
  30302. var extent = this._extent;
  30303. // If extent start and end are same, expand them
  30304. if (extent[0] === extent[1]) {
  30305. // Expand extent
  30306. extent[0] -= ONE_DAY;
  30307. extent[1] += ONE_DAY;
  30308. }
  30309. // If there are no data and extent are [Infinity, -Infinity]
  30310. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30311. var d = new Date();
  30312. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30313. extent[0] = extent[1] - ONE_DAY;
  30314. }
  30315. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30316. };
  30317. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  30318. approxTickNum = approxTickNum || 10;
  30319. var extent = this._extent;
  30320. var span = extent[1] - extent[0];
  30321. this._approxInterval = span / approxTickNum;
  30322. if (minInterval != null && this._approxInterval < minInterval) {
  30323. this._approxInterval = minInterval;
  30324. }
  30325. if (maxInterval != null && this._approxInterval > maxInterval) {
  30326. this._approxInterval = maxInterval;
  30327. }
  30328. var scaleIntervalsLen = scaleIntervals.length;
  30329. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1);
  30330. // Interval that can be used to calculate ticks
  30331. this._interval = scaleIntervals[idx][1];
  30332. // Min level used when picking ticks from top down.
  30333. // We check one more level to avoid the ticks are to sparse in some case.
  30334. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30335. };
  30336. TimeScale.prototype.parse = function (val) {
  30337. // val might be float.
  30338. return isNumber(val) ? val : +parseDate(val);
  30339. };
  30340. TimeScale.prototype.contain = function (val) {
  30341. return contain$1(this.parse(val), this._extent);
  30342. };
  30343. TimeScale.prototype.normalize = function (val) {
  30344. return normalize$1(this.parse(val), this._extent);
  30345. };
  30346. TimeScale.prototype.scale = function (val) {
  30347. return scale$2(val, this._extent);
  30348. };
  30349. TimeScale.type = 'time';
  30350. return TimeScale;
  30351. }(IntervalScale);
  30352. /**
  30353. * This implementation was originally copied from "d3.js"
  30354. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30355. * with some modifications made for this program.
  30356. * See the license statement at the head of this file.
  30357. */
  30358. var scaleIntervals = [
  30359. // Format interval
  30360. ['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
  30361. ];
  30362. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30363. var dateA = parseDate(valueA);
  30364. var dateB = parseDate(valueB);
  30365. var isSame = function (unit) {
  30366. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30367. };
  30368. var isSameYear = function () {
  30369. return isSame('year');
  30370. };
  30371. // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30372. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30373. var isSameMonth = function () {
  30374. return isSameYear() && isSame('month');
  30375. };
  30376. var isSameDay = function () {
  30377. return isSameMonth() && isSame('day');
  30378. };
  30379. // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30380. var isSameHour = function () {
  30381. return isSameDay() && isSame('hour');
  30382. };
  30383. var isSameMinute = function () {
  30384. return isSameHour() && isSame('minute');
  30385. };
  30386. var isSameSecond = function () {
  30387. return isSameMinute() && isSame('second');
  30388. };
  30389. var isSameMilliSecond = function () {
  30390. return isSameSecond() && isSame('millisecond');
  30391. };
  30392. switch (unit) {
  30393. case 'year':
  30394. return isSameYear();
  30395. case 'month':
  30396. return isSameMonth();
  30397. case 'day':
  30398. return isSameDay();
  30399. case 'hour':
  30400. return isSameHour();
  30401. case 'minute':
  30402. return isSameMinute();
  30403. case 'second':
  30404. return isSameSecond();
  30405. case 'millisecond':
  30406. return isSameMilliSecond();
  30407. }
  30408. }
  30409. // const primaryUnitGetters = {
  30410. // year: fullYearGetterName(),
  30411. // month: monthGetterName(),
  30412. // day: dateGetterName(),
  30413. // hour: hoursGetterName(),
  30414. // minute: minutesGetterName(),
  30415. // second: secondsGetterName(),
  30416. // millisecond: millisecondsGetterName()
  30417. // };
  30418. // const primaryUnitUTCGetters = {
  30419. // year: fullYearGetterName(true),
  30420. // month: monthGetterName(true),
  30421. // day: dateGetterName(true),
  30422. // hour: hoursGetterName(true),
  30423. // minute: minutesGetterName(true),
  30424. // second: secondsGetterName(true),
  30425. // millisecond: millisecondsGetterName(true)
  30426. // };
  30427. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30428. // step = step || 1;
  30429. // switch (getPrimaryTimeUnit(unitName)) {
  30430. // case 'year':
  30431. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30432. // break;
  30433. // case 'month':
  30434. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30435. // break;
  30436. // case 'day':
  30437. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  30438. // break;
  30439. // case 'hour':
  30440. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  30441. // break;
  30442. // case 'minute':
  30443. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  30444. // break;
  30445. // case 'second':
  30446. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  30447. // break;
  30448. // case 'millisecond':
  30449. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  30450. // break;
  30451. // }
  30452. // return date.getTime();
  30453. // }
  30454. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  30455. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  30456. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  30457. function getDateInterval(approxInterval, daysInMonth) {
  30458. approxInterval /= ONE_DAY;
  30459. return approxInterval > 16 ? 16
  30460. // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  30461. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  30462. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  30463. }
  30464. function getMonthInterval(approxInterval) {
  30465. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  30466. approxInterval /= APPROX_ONE_MONTH;
  30467. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  30468. }
  30469. function getHourInterval(approxInterval) {
  30470. approxInterval /= ONE_HOUR;
  30471. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  30472. }
  30473. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  30474. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  30475. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  30476. }
  30477. function getMillisecondsInterval(approxInterval) {
  30478. return nice(approxInterval, true);
  30479. }
  30480. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  30481. var outDate = new Date(date);
  30482. switch (getPrimaryTimeUnit(unitName)) {
  30483. case 'year':
  30484. case 'month':
  30485. outDate[monthSetterName(isUTC)](0);
  30486. case 'day':
  30487. outDate[dateSetterName(isUTC)](1);
  30488. case 'hour':
  30489. outDate[hoursSetterName(isUTC)](0);
  30490. case 'minute':
  30491. outDate[minutesSetterName(isUTC)](0);
  30492. case 'second':
  30493. outDate[secondsSetterName(isUTC)](0);
  30494. outDate[millisecondsSetterName(isUTC)](0);
  30495. }
  30496. return outDate.getTime();
  30497. }
  30498. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  30499. var safeLimit = 10000;
  30500. var unitNames = timeUnits;
  30501. var iter = 0;
  30502. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  30503. var date = new Date(minTimestamp);
  30504. var dateTime = minTimestamp;
  30505. var d = date[getMethodName]();
  30506. // if (isDate) {
  30507. // d -= 1; // Starts with 0; PENDING
  30508. // }
  30509. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  30510. out.push({
  30511. value: dateTime
  30512. });
  30513. d += interval;
  30514. date[setMethodName](d);
  30515. dateTime = date.getTime();
  30516. }
  30517. // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  30518. out.push({
  30519. value: dateTime,
  30520. notAdd: true
  30521. });
  30522. }
  30523. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  30524. var newAddedTicks = [];
  30525. var isFirstLevel = !lastLevelTicks.length;
  30526. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  30527. return;
  30528. }
  30529. if (isFirstLevel) {
  30530. lastLevelTicks = [{
  30531. // TODO Optimize. Not include so may ticks.
  30532. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  30533. }, {
  30534. value: extent[1]
  30535. }];
  30536. }
  30537. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  30538. var startTick = lastLevelTicks[i].value;
  30539. var endTick = lastLevelTicks[i + 1].value;
  30540. if (startTick === endTick) {
  30541. continue;
  30542. }
  30543. var interval = void 0;
  30544. var getterName = void 0;
  30545. var setterName = void 0;
  30546. var isDate = false;
  30547. switch (unitName) {
  30548. case 'year':
  30549. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  30550. getterName = fullYearGetterName(isUTC);
  30551. setterName = fullYearSetterName(isUTC);
  30552. break;
  30553. case 'half-year':
  30554. case 'quarter':
  30555. case 'month':
  30556. interval = getMonthInterval(approxInterval);
  30557. getterName = monthGetterName(isUTC);
  30558. setterName = monthSetterName(isUTC);
  30559. break;
  30560. case 'week': // PENDING If week is added. Ignore day.
  30561. case 'half-week':
  30562. case 'day':
  30563. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  30564. getterName = dateGetterName(isUTC);
  30565. setterName = dateSetterName(isUTC);
  30566. isDate = true;
  30567. break;
  30568. case 'half-day':
  30569. case 'quarter-day':
  30570. case 'hour':
  30571. interval = getHourInterval(approxInterval);
  30572. getterName = hoursGetterName(isUTC);
  30573. setterName = hoursSetterName(isUTC);
  30574. break;
  30575. case 'minute':
  30576. interval = getMinutesAndSecondsInterval(approxInterval, true);
  30577. getterName = minutesGetterName(isUTC);
  30578. setterName = minutesSetterName(isUTC);
  30579. break;
  30580. case 'second':
  30581. interval = getMinutesAndSecondsInterval(approxInterval, false);
  30582. getterName = secondsGetterName(isUTC);
  30583. setterName = secondsSetterName(isUTC);
  30584. break;
  30585. case 'millisecond':
  30586. interval = getMillisecondsInterval(approxInterval);
  30587. getterName = millisecondsGetterName(isUTC);
  30588. setterName = millisecondsSetterName(isUTC);
  30589. break;
  30590. }
  30591. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  30592. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  30593. // Add nearest years to the left extent.
  30594. levelTicks.unshift({
  30595. value: levelTicks[0].value - interval
  30596. });
  30597. }
  30598. }
  30599. for (var i = 0; i < newAddedTicks.length; i++) {
  30600. levelTicks.push(newAddedTicks[i]);
  30601. }
  30602. // newAddedTicks.length && console.log(unitName, newAddedTicks);
  30603. return newAddedTicks;
  30604. }
  30605. var levelsTicks = [];
  30606. var currentLevelTicks = [];
  30607. var tickCount = 0;
  30608. var lastLevelTickCount = 0;
  30609. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  30610. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  30611. if (!isPrimaryTimeUnit(unitNames[i])) {
  30612. // TODO
  30613. continue;
  30614. }
  30615. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  30616. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  30617. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  30618. if (currentLevelTicks.length) {
  30619. lastLevelTickCount = tickCount;
  30620. // Remove the duplicate so the tick count can be precisely.
  30621. currentLevelTicks.sort(function (a, b) {
  30622. return a.value - b.value;
  30623. });
  30624. var levelTicksRemoveDuplicated = [];
  30625. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  30626. var tickValue = currentLevelTicks[i_1].value;
  30627. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  30628. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  30629. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  30630. tickCount++;
  30631. }
  30632. }
  30633. }
  30634. var targetTickNum = (extent[1] - extent[0]) / approxInterval;
  30635. // Added too much in this level and not too less in last level
  30636. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  30637. break;
  30638. }
  30639. // Only treat primary time unit as one level.
  30640. levelsTicks.push(levelTicksRemoveDuplicated);
  30641. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  30642. break;
  30643. }
  30644. }
  30645. // Reset if next unitName is primary
  30646. currentLevelTicks = [];
  30647. }
  30648. }
  30649. if ("development" !== 'production') {
  30650. if (iter >= safeLimit) {
  30651. warn('Exceed safe limit.');
  30652. }
  30653. }
  30654. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  30655. return filter(levelTicks, function (tick) {
  30656. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  30657. });
  30658. }), function (levelTicks) {
  30659. return levelTicks.length > 0;
  30660. });
  30661. var ticks = [];
  30662. var maxLevel = levelsTicksInExtent.length - 1;
  30663. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  30664. var levelTicks = levelsTicksInExtent[i];
  30665. for (var k = 0; k < levelTicks.length; ++k) {
  30666. ticks.push({
  30667. value: levelTicks[k].value,
  30668. level: maxLevel - i
  30669. });
  30670. }
  30671. }
  30672. ticks.sort(function (a, b) {
  30673. return a.value - b.value;
  30674. });
  30675. // Remove duplicates
  30676. var result = [];
  30677. for (var i = 0; i < ticks.length; ++i) {
  30678. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  30679. result.push(ticks[i]);
  30680. }
  30681. }
  30682. return result;
  30683. }
  30684. Scale.registerClass(TimeScale);
  30685. var scaleProto = Scale.prototype;
  30686. // FIXME:TS refactor: not good to call it directly with `this`?
  30687. var intervalScaleProto = IntervalScale.prototype;
  30688. var roundingErrorFix = round;
  30689. var mathFloor = Math.floor;
  30690. var mathCeil = Math.ceil;
  30691. var mathPow$1 = Math.pow;
  30692. var mathLog = Math.log;
  30693. var LogScale = /** @class */function (_super) {
  30694. __extends(LogScale, _super);
  30695. function LogScale() {
  30696. var _this = _super !== null && _super.apply(this, arguments) || this;
  30697. _this.type = 'log';
  30698. _this.base = 10;
  30699. _this._originalScale = new IntervalScale();
  30700. // FIXME:TS actually used by `IntervalScale`
  30701. _this._interval = 0;
  30702. return _this;
  30703. }
  30704. /**
  30705. * @param Whether expand the ticks to niced extent.
  30706. */
  30707. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  30708. var originalScale = this._originalScale;
  30709. var extent = this._extent;
  30710. var originalExtent = originalScale.getExtent();
  30711. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  30712. return map(ticks, function (tick) {
  30713. var val = tick.value;
  30714. var powVal = round(mathPow$1(this.base, val));
  30715. // Fix #4158
  30716. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  30717. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  30718. return {
  30719. value: powVal
  30720. };
  30721. }, this);
  30722. };
  30723. LogScale.prototype.setExtent = function (start, end) {
  30724. var base = mathLog(this.base);
  30725. // log(-Infinity) is NaN, so safe guard here
  30726. start = mathLog(Math.max(0, start)) / base;
  30727. end = mathLog(Math.max(0, end)) / base;
  30728. intervalScaleProto.setExtent.call(this, start, end);
  30729. };
  30730. /**
  30731. * @return {number} end
  30732. */
  30733. LogScale.prototype.getExtent = function () {
  30734. var base = this.base;
  30735. var extent = scaleProto.getExtent.call(this);
  30736. extent[0] = mathPow$1(base, extent[0]);
  30737. extent[1] = mathPow$1(base, extent[1]);
  30738. // Fix #4158
  30739. var originalScale = this._originalScale;
  30740. var originalExtent = originalScale.getExtent();
  30741. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30742. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30743. return extent;
  30744. };
  30745. LogScale.prototype.unionExtent = function (extent) {
  30746. this._originalScale.unionExtent(extent);
  30747. var base = this.base;
  30748. extent[0] = mathLog(extent[0]) / mathLog(base);
  30749. extent[1] = mathLog(extent[1]) / mathLog(base);
  30750. scaleProto.unionExtent.call(this, extent);
  30751. };
  30752. LogScale.prototype.unionExtentFromData = function (data, dim) {
  30753. // TODO
  30754. // filter value that <= 0
  30755. this.unionExtent(data.getApproximateExtent(dim));
  30756. };
  30757. /**
  30758. * Update interval and extent of intervals for nice ticks
  30759. * @param approxTickNum default 10 Given approx tick number
  30760. */
  30761. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  30762. approxTickNum = approxTickNum || 10;
  30763. var extent = this._extent;
  30764. var span = extent[1] - extent[0];
  30765. if (span === Infinity || span <= 0) {
  30766. return;
  30767. }
  30768. var interval = quantity(span);
  30769. var err = approxTickNum / span * interval;
  30770. // Filter ticks to get closer to the desired count.
  30771. if (err <= 0.5) {
  30772. interval *= 10;
  30773. }
  30774. // Interval should be integer
  30775. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30776. interval *= 10;
  30777. }
  30778. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  30779. this._interval = interval;
  30780. this._niceExtent = niceExtent;
  30781. };
  30782. LogScale.prototype.calcNiceExtent = function (opt) {
  30783. intervalScaleProto.calcNiceExtent.call(this, opt);
  30784. this._fixMin = opt.fixMin;
  30785. this._fixMax = opt.fixMax;
  30786. };
  30787. LogScale.prototype.parse = function (val) {
  30788. return val;
  30789. };
  30790. LogScale.prototype.contain = function (val) {
  30791. val = mathLog(val) / mathLog(this.base);
  30792. return contain$1(val, this._extent);
  30793. };
  30794. LogScale.prototype.normalize = function (val) {
  30795. val = mathLog(val) / mathLog(this.base);
  30796. return normalize$1(val, this._extent);
  30797. };
  30798. LogScale.prototype.scale = function (val) {
  30799. val = scale$2(val, this._extent);
  30800. return mathPow$1(this.base, val);
  30801. };
  30802. LogScale.type = 'log';
  30803. return LogScale;
  30804. }(Scale);
  30805. var proto = LogScale.prototype;
  30806. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  30807. proto.getLabel = intervalScaleProto.getLabel;
  30808. function fixRoundingError(val, originalVal) {
  30809. return roundingErrorFix(val, getPrecision(originalVal));
  30810. }
  30811. Scale.registerClass(LogScale);
  30812. var ScaleRawExtentInfo = /** @class */function () {
  30813. function ScaleRawExtentInfo(scale, model,
  30814. // Usually: data extent from all series on this axis.
  30815. originalExtent) {
  30816. this._prepareParams(scale, model, originalExtent);
  30817. }
  30818. /**
  30819. * Parameters depending on outside (like model, user callback)
  30820. * are prepared and fixed here.
  30821. */
  30822. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model,
  30823. // Usually: data extent from all series on this axis.
  30824. dataExtent) {
  30825. if (dataExtent[1] < dataExtent[0]) {
  30826. dataExtent = [NaN, NaN];
  30827. }
  30828. this._dataMin = dataExtent[0];
  30829. this._dataMax = dataExtent[1];
  30830. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  30831. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  30832. var axisMinValue = model.get('min', true);
  30833. if (axisMinValue == null) {
  30834. axisMinValue = model.get('startValue', true);
  30835. }
  30836. var modelMinRaw = this._modelMinRaw = axisMinValue;
  30837. if (isFunction(modelMinRaw)) {
  30838. // This callback always provides users the full data extent (before data is filtered).
  30839. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  30840. min: dataExtent[0],
  30841. max: dataExtent[1]
  30842. }));
  30843. } else if (modelMinRaw !== 'dataMin') {
  30844. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  30845. }
  30846. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  30847. if (isFunction(modelMaxRaw)) {
  30848. // This callback always provides users the full data extent (before data is filtered).
  30849. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  30850. min: dataExtent[0],
  30851. max: dataExtent[1]
  30852. }));
  30853. } else if (modelMaxRaw !== 'dataMax') {
  30854. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  30855. }
  30856. if (isOrdinal) {
  30857. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  30858. // and progressive rendering is using, here the category result might just only contain
  30859. // the processed chunk rather than the entire result.
  30860. this._axisDataLen = model.getCategories().length;
  30861. } else {
  30862. var boundaryGap = model.get('boundaryGap');
  30863. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  30864. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  30865. if ("development" !== 'production') {
  30866. 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.');
  30867. }
  30868. this._boundaryGapInner = [0, 0];
  30869. } else {
  30870. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  30871. }
  30872. }
  30873. };
  30874. /**
  30875. * Calculate extent by prepared parameters.
  30876. * This method has no external dependency and can be called duplicatedly,
  30877. * getting the same result.
  30878. * If parameters changed, should call this method to recalcuate.
  30879. */
  30880. ScaleRawExtentInfo.prototype.calculate = function () {
  30881. // Notice: When min/max is not set (that is, when there are null/undefined,
  30882. // which is the most common case), these cases should be ensured:
  30883. // (1) For 'ordinal', show all axis.data.
  30884. // (2) For others:
  30885. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30886. // disabled).
  30887. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30888. // be the result that originalExtent enlarged by boundaryGap.
  30889. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30890. var isOrdinal = this._isOrdinal;
  30891. var dataMin = this._dataMin;
  30892. var dataMax = this._dataMax;
  30893. var axisDataLen = this._axisDataLen;
  30894. var boundaryGapInner = this._boundaryGapInner;
  30895. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null;
  30896. // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  30897. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  30898. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  30899. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum;
  30900. // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  30901. var minFixed = min != null;
  30902. var maxFixed = max != null;
  30903. if (min == null) {
  30904. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  30905. }
  30906. if (max == null) {
  30907. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  30908. }
  30909. (min == null || !isFinite(min)) && (min = NaN);
  30910. (max == null || !isFinite(max)) && (max = NaN);
  30911. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen;
  30912. // If data extent modified, need to recalculated to ensure cross zero.
  30913. if (this._needCrossZero) {
  30914. // Axis is over zero and min is not set
  30915. if (min > 0 && max > 0 && !minFixed) {
  30916. min = 0;
  30917. // minFixed = true;
  30918. }
  30919. // Axis is under zero and max is not set
  30920. if (min < 0 && max < 0 && !maxFixed) {
  30921. max = 0;
  30922. // maxFixed = true;
  30923. }
  30924. // PENDING:
  30925. // When `needCrossZero` and all data is positive/negative, should it be ensured
  30926. // that the results processed by boundaryGap are positive/negative?
  30927. // If so, here `minFixed`/`maxFixed` need to be set.
  30928. }
  30929. var determinedMin = this._determinedMin;
  30930. var determinedMax = this._determinedMax;
  30931. if (determinedMin != null) {
  30932. min = determinedMin;
  30933. minFixed = true;
  30934. }
  30935. if (determinedMax != null) {
  30936. max = determinedMax;
  30937. maxFixed = true;
  30938. }
  30939. // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  30940. // `NaN` means min/max axis is blank.
  30941. return {
  30942. min: min,
  30943. max: max,
  30944. minFixed: minFixed,
  30945. maxFixed: maxFixed,
  30946. isBlank: isBlank
  30947. };
  30948. };
  30949. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  30950. if ("development" !== 'production') {
  30951. assert(!this.frozen);
  30952. }
  30953. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  30954. };
  30955. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  30956. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  30957. if ("development" !== 'production') {
  30958. assert(!this.frozen
  30959. // Earse them usually means logic flaw.
  30960. && this[attr] == null);
  30961. }
  30962. this[attr] = val;
  30963. };
  30964. ScaleRawExtentInfo.prototype.freeze = function () {
  30965. // @ts-ignore
  30966. this.frozen = true;
  30967. };
  30968. return ScaleRawExtentInfo;
  30969. }();
  30970. var DETERMINED_MIN_MAX_ATTR = {
  30971. min: '_determinedMin',
  30972. max: '_determinedMax'
  30973. };
  30974. var DATA_MIN_MAX_ATTR = {
  30975. min: '_dataMin',
  30976. max: '_dataMax'
  30977. };
  30978. /**
  30979. * Get scale min max and related info only depends on model settings.
  30980. * This method can be called after coordinate system created.
  30981. * For example, in data processing stage.
  30982. *
  30983. * Scale extent info probably be required multiple times during a workflow.
  30984. * For example:
  30985. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  30986. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  30987. * (3) `coordSys.update` use it to finally decide the scale extent.
  30988. * But the callback of `min`/`max` should not be called multiple times.
  30989. * The code below should not be implemented repeatedly either.
  30990. * So we cache the result in the scale instance, which will be recreated at the beginning
  30991. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  30992. */
  30993. function ensureScaleRawExtentInfo(scale, model,
  30994. // Usually: data extent from all series on this axis.
  30995. originalExtent) {
  30996. // Do not permit to recreate.
  30997. var rawExtentInfo = scale.rawExtentInfo;
  30998. if (rawExtentInfo) {
  30999. return rawExtentInfo;
  31000. }
  31001. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent);
  31002. // @ts-ignore
  31003. scale.rawExtentInfo = rawExtentInfo;
  31004. return rawExtentInfo;
  31005. }
  31006. function parseAxisModelMinMax(scale, minMax) {
  31007. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31008. }
  31009. /**
  31010. * Get axis scale extent before niced.
  31011. * Item of returned array can only be number (including Infinity and NaN).
  31012. *
  31013. * Caution:
  31014. * Precondition of calling this method:
  31015. * The scale extent has been initialized using series data extent via
  31016. * `scale.setExtent` or `scale.unionExtentFromData`;
  31017. */
  31018. function getScaleExtent(scale, model) {
  31019. var scaleType = scale.type;
  31020. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31021. scale.setBlank(rawExtentResult.isBlank);
  31022. var min = rawExtentResult.min;
  31023. var max = rawExtentResult.max;
  31024. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  31025. // is base axis
  31026. // FIXME
  31027. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31028. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31029. // Should not depend on series type `bar`?
  31030. // (3) Fix that might overlap when using dataZoom.
  31031. // (4) Consider other chart types using `barGrid`?
  31032. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31033. var ecModel = model.ecModel;
  31034. if (ecModel && scaleType === 'time' /* || scaleType === 'interval' */) {
  31035. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31036. var isBaseAxisAndHasBarSeries_1 = false;
  31037. each(barSeriesModels, function (seriesModel) {
  31038. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31039. });
  31040. if (isBaseAxisAndHasBarSeries_1) {
  31041. // Calculate placement of bars on axis. TODO should be decoupled
  31042. // with barLayout
  31043. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  31044. // Adjust axis min and max to account for overflow
  31045. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31046. min = adjustedScale.min;
  31047. max = adjustedScale.max;
  31048. }
  31049. }
  31050. return {
  31051. extent: [min, max],
  31052. // "fix" means "fixed", the value should not be
  31053. // changed in the subsequent steps.
  31054. fixMin: rawExtentResult.minFixed,
  31055. fixMax: rawExtentResult.maxFixed
  31056. };
  31057. }
  31058. function adjustScaleForOverflow(min, max, model,
  31059. // Only support cartesian coord yet.
  31060. barWidthAndOffset) {
  31061. // Get Axis Length
  31062. var axisExtent = model.axis.getExtent();
  31063. var axisLength = axisExtent[1] - axisExtent[0];
  31064. // Get bars on current base axis and calculate min and max overflow
  31065. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31066. if (barsOnCurrentAxis === undefined) {
  31067. return {
  31068. min: min,
  31069. max: max
  31070. };
  31071. }
  31072. var minOverflow = Infinity;
  31073. each(barsOnCurrentAxis, function (item) {
  31074. minOverflow = Math.min(item.offset, minOverflow);
  31075. });
  31076. var maxOverflow = -Infinity;
  31077. each(barsOnCurrentAxis, function (item) {
  31078. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31079. });
  31080. minOverflow = Math.abs(minOverflow);
  31081. maxOverflow = Math.abs(maxOverflow);
  31082. var totalOverFlow = minOverflow + maxOverflow;
  31083. // Calculate required buffer based on old range and overflow
  31084. var oldRange = max - min;
  31085. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31086. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31087. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31088. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31089. return {
  31090. min: min,
  31091. max: max
  31092. };
  31093. }
  31094. // Precondition of calling this method:
  31095. // The scale extent has been initialized using series data extent via
  31096. // `scale.setExtent` or `scale.unionExtentFromData`;
  31097. function niceScaleExtent(scale, inModel) {
  31098. var model = inModel;
  31099. var extentInfo = getScaleExtent(scale, model);
  31100. var extent = extentInfo.extent;
  31101. var splitNumber = model.get('splitNumber');
  31102. if (scale instanceof LogScale) {
  31103. scale.base = model.get('logBase');
  31104. }
  31105. var scaleType = scale.type;
  31106. var interval = model.get('interval');
  31107. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  31108. scale.setExtent(extent[0], extent[1]);
  31109. scale.calcNiceExtent({
  31110. splitNumber: splitNumber,
  31111. fixMin: extentInfo.fixMin,
  31112. fixMax: extentInfo.fixMax,
  31113. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  31114. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  31115. });
  31116. // If some one specified the min, max. And the default calculated interval
  31117. // is not good enough. He can specify the interval. It is often appeared
  31118. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31119. // to be 60.
  31120. // FIXME
  31121. if (interval != null) {
  31122. scale.setInterval && scale.setInterval(interval);
  31123. }
  31124. }
  31125. /**
  31126. * @param axisType Default retrieve from model.type
  31127. */
  31128. function createScaleByModel(model, axisType) {
  31129. axisType = axisType || model.get('type');
  31130. if (axisType) {
  31131. switch (axisType) {
  31132. // Buildin scale
  31133. case 'category':
  31134. return new OrdinalScale({
  31135. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  31136. extent: [Infinity, -Infinity]
  31137. });
  31138. case 'time':
  31139. return new TimeScale({
  31140. locale: model.ecModel.getLocaleModel(),
  31141. useUTC: model.ecModel.get('useUTC')
  31142. });
  31143. default:
  31144. // case 'value'/'interval', 'log', or others.
  31145. return new (Scale.getClass(axisType) || IntervalScale)();
  31146. }
  31147. }
  31148. }
  31149. /**
  31150. * Check if the axis cross 0
  31151. */
  31152. function ifAxisCrossZero(axis) {
  31153. var dataExtent = axis.scale.getExtent();
  31154. var min = dataExtent[0];
  31155. var max = dataExtent[1];
  31156. return !(min > 0 && max > 0 || min < 0 && max < 0);
  31157. }
  31158. /**
  31159. * @param axis
  31160. * @return Label formatter function.
  31161. * param: {number} tickValue,
  31162. * param: {number} idx, the index in all ticks.
  31163. * If category axis, this param is not required.
  31164. * return: {string} label string.
  31165. */
  31166. function makeLabelFormatter(axis) {
  31167. var labelFormatter = axis.getLabelModel().get('formatter');
  31168. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31169. if (axis.scale.type === 'time') {
  31170. return function (tpl) {
  31171. return function (tick, idx) {
  31172. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31173. };
  31174. }(labelFormatter);
  31175. } else if (isString(labelFormatter)) {
  31176. return function (tpl) {
  31177. return function (tick) {
  31178. // For category axis, get raw value; for numeric axis,
  31179. // get formatted label like '1,333,444'.
  31180. var label = axis.scale.getLabel(tick);
  31181. var text = tpl.replace('{value}', label != null ? label : '');
  31182. return text;
  31183. };
  31184. }(labelFormatter);
  31185. } else if (isFunction(labelFormatter)) {
  31186. return function (cb) {
  31187. return function (tick, idx) {
  31188. // The original intention of `idx` is "the index of the tick in all ticks".
  31189. // But the previous implementation of category axis do not consider the
  31190. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31191. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31192. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31193. // the definition here for back compatibility.
  31194. if (categoryTickStart != null) {
  31195. idx = tick.value - categoryTickStart;
  31196. }
  31197. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31198. level: tick.level
  31199. } : null);
  31200. };
  31201. }(labelFormatter);
  31202. } else {
  31203. return function (tick) {
  31204. return axis.scale.getLabel(tick);
  31205. };
  31206. }
  31207. }
  31208. function getAxisRawValue(axis, tick) {
  31209. // In category axis with data zoom, tick is not the original
  31210. // index of axis.data. So tick should not be exposed to user
  31211. // in category axis.
  31212. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31213. }
  31214. /**
  31215. * @param axis
  31216. * @return Be null/undefined if no labels.
  31217. */
  31218. function estimateLabelUnionRect(axis) {
  31219. var axisModel = axis.model;
  31220. var scale = axis.scale;
  31221. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31222. return;
  31223. }
  31224. var realNumberScaleTicks;
  31225. var tickCount;
  31226. var categoryScaleExtent = scale.getExtent();
  31227. // Optimize for large category data, avoid call `getTicks()`.
  31228. if (scale instanceof OrdinalScale) {
  31229. tickCount = scale.count();
  31230. } else {
  31231. realNumberScaleTicks = scale.getTicks();
  31232. tickCount = realNumberScaleTicks.length;
  31233. }
  31234. var axisLabelModel = axis.getLabelModel();
  31235. var labelFormatter = makeLabelFormatter(axis);
  31236. var rect;
  31237. var step = 1;
  31238. // Simple optimization for large amount of labels
  31239. if (tickCount > 40) {
  31240. step = Math.ceil(tickCount / 40);
  31241. }
  31242. for (var i = 0; i < tickCount; i += step) {
  31243. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31244. value: categoryScaleExtent[0] + i
  31245. };
  31246. var label = labelFormatter(tick, i);
  31247. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31248. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31249. rect ? rect.union(singleRect) : rect = singleRect;
  31250. }
  31251. return rect;
  31252. }
  31253. function rotateTextRect(textRect, rotate) {
  31254. var rotateRadians = rotate * Math.PI / 180;
  31255. var beforeWidth = textRect.width;
  31256. var beforeHeight = textRect.height;
  31257. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31258. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31259. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31260. return rotatedRect;
  31261. }
  31262. /**
  31263. * @param model axisLabelModel or axisTickModel
  31264. * @return {number|String} Can be null|'auto'|number|function
  31265. */
  31266. function getOptionCategoryInterval(model) {
  31267. var interval = model.get('interval');
  31268. return interval == null ? 'auto' : interval;
  31269. }
  31270. /**
  31271. * Set `categoryInterval` as 0 implicitly indicates that
  31272. * show all labels regardless of overlap.
  31273. * @param {Object} axis axisModel.axis
  31274. */
  31275. function shouldShowAllLabels(axis) {
  31276. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31277. }
  31278. function getDataDimensionsOnAxis(data, axisDim) {
  31279. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31280. var dataDimMap = {};
  31281. // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31282. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31283. // there has been stacked result dim?
  31284. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31285. // For example, the extent of the original dimension
  31286. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31287. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31288. // because there is no graphic corresponding to [0.1, 0.5].
  31289. // See the case in `test/area-stack.html` `main1`, where area line
  31290. // stack needs `yAxis` not start from 0.
  31291. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31292. });
  31293. return keys(dataDimMap);
  31294. }
  31295. /*
  31296. * Licensed to the Apache Software Foundation (ASF) under one
  31297. * or more contributor license agreements. See the NOTICE file
  31298. * distributed with this work for additional information
  31299. * regarding copyright ownership. The ASF licenses this file
  31300. * to you under the Apache License, Version 2.0 (the
  31301. * "License"); you may not use this file except in compliance
  31302. * with the License. You may obtain a copy of the License at
  31303. *
  31304. * http://www.apache.org/licenses/LICENSE-2.0
  31305. *
  31306. * Unless required by applicable law or agreed to in writing,
  31307. * software distributed under the License is distributed on an
  31308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31309. * KIND, either express or implied. See the License for the
  31310. * specific language governing permissions and limitations
  31311. * under the License.
  31312. */
  31313. /**
  31314. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31315. */
  31316. /*
  31317. * Licensed to the Apache Software Foundation (ASF) under one
  31318. * or more contributor license agreements. See the NOTICE file
  31319. * distributed with this work for additional information
  31320. * regarding copyright ownership. The ASF licenses this file
  31321. * to you under the Apache License, Version 2.0 (the
  31322. * "License"); you may not use this file except in compliance
  31323. * with the License. You may obtain a copy of the License at
  31324. *
  31325. * http://www.apache.org/licenses/LICENSE-2.0
  31326. *
  31327. * Unless required by applicable law or agreed to in writing,
  31328. * software distributed under the License is distributed on an
  31329. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31330. * KIND, either express or implied. See the License for the
  31331. * specific language governing permissions and limitations
  31332. * under the License.
  31333. */
  31334. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  31335. var AxisModelCommonMixin = /** @class */function () {
  31336. function AxisModelCommonMixin() {}
  31337. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31338. var option = this.option;
  31339. return !option.scale;
  31340. };
  31341. /**
  31342. * Should be implemented by each axis model if necessary.
  31343. * @return coordinate system model
  31344. */
  31345. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31346. return;
  31347. };
  31348. return AxisModelCommonMixin;
  31349. }();
  31350. /**
  31351. * Create a multi dimension List structure from seriesModel.
  31352. */
  31353. function createList(seriesModel) {
  31354. return createSeriesData(null, seriesModel);
  31355. }
  31356. var dataStack$1 = {
  31357. isDimensionStacked: isDimensionStacked,
  31358. enableDataStack: enableDataStack,
  31359. getStackedDimension: getStackedDimension
  31360. };
  31361. /**
  31362. * Create scale
  31363. * @param {Array.<number>} dataExtent
  31364. * @param {Object|module:echarts/Model} option If `optoin.type`
  31365. * is secified, it can only be `'value'` currently.
  31366. */
  31367. function createScale(dataExtent, option) {
  31368. var axisModel = option;
  31369. if (!(option instanceof Model)) {
  31370. axisModel = new Model(option);
  31371. // FIXME
  31372. // Currently AxisModelCommonMixin has nothing to do with the
  31373. // the requirements of `axisHelper.createScaleByModel`. For
  31374. // example the methods `getCategories` and `getOrdinalMeta`
  31375. // are required for `'category'` axis, and ecModel is required
  31376. // for `'time'` axis. But occasionally echarts-gl happened
  31377. // to only use `'value'` axis.
  31378. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31379. }
  31380. var scale = createScaleByModel(axisModel);
  31381. scale.setExtent(dataExtent[0], dataExtent[1]);
  31382. niceScaleExtent(scale, axisModel);
  31383. return scale;
  31384. }
  31385. /**
  31386. * Mixin common methods to axis model,
  31387. *
  31388. * Include methods
  31389. * `getFormattedLabels() => Array.<string>`
  31390. * `getCategories() => Array.<string>`
  31391. * `getMin(origin: boolean) => number`
  31392. * `getMax(origin: boolean) => number`
  31393. * `getNeedCrossZero() => boolean`
  31394. */
  31395. function mixinAxisModelCommonMethods(Model) {
  31396. mixin(Model, AxisModelCommonMixin);
  31397. }
  31398. function createTextStyle$1(textStyleModel, opts) {
  31399. opts = opts || {};
  31400. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31401. }
  31402. var helper = /*#__PURE__*/Object.freeze({
  31403. __proto__: null,
  31404. createList: createList,
  31405. getLayoutRect: getLayoutRect,
  31406. dataStack: dataStack$1,
  31407. createScale: createScale,
  31408. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31409. getECData: getECData,
  31410. createTextStyle: createTextStyle$1,
  31411. createDimensions: createDimensions,
  31412. createSymbol: createSymbol,
  31413. enableHoverEmphasis: enableHoverEmphasis
  31414. });
  31415. var EPSILON$3 = 1e-8;
  31416. function isAroundEqual$1(a, b) {
  31417. return Math.abs(a - b) < EPSILON$3;
  31418. }
  31419. function contain$2(points, x, y) {
  31420. var w = 0;
  31421. var p = points[0];
  31422. if (!p) {
  31423. return false;
  31424. }
  31425. for (var i = 1; i < points.length; i++) {
  31426. var p2 = points[i];
  31427. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31428. p = p2;
  31429. }
  31430. var p0 = points[0];
  31431. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31432. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31433. }
  31434. return w !== 0;
  31435. }
  31436. var TMP_TRANSFORM = [];
  31437. function transformPoints(points, transform) {
  31438. for (var p = 0; p < points.length; p++) {
  31439. applyTransform(points[p], points[p], transform);
  31440. }
  31441. }
  31442. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  31443. for (var i = 0; i < points.length; i++) {
  31444. var p = points[i];
  31445. if (projection) {
  31446. // projection may return null point.
  31447. p = projection.project(p);
  31448. }
  31449. if (p && isFinite(p[0]) && isFinite(p[1])) {
  31450. min(min$1, min$1, p);
  31451. max(max$1, max$1, p);
  31452. }
  31453. }
  31454. }
  31455. function centroid(points) {
  31456. var signedArea = 0;
  31457. var cx = 0;
  31458. var cy = 0;
  31459. var len = points.length;
  31460. var x0 = points[len - 1][0];
  31461. var y0 = points[len - 1][1];
  31462. // Polygon should been closed.
  31463. for (var i = 0; i < len; i++) {
  31464. var x1 = points[i][0];
  31465. var y1 = points[i][1];
  31466. var a = x0 * y1 - x1 * y0;
  31467. signedArea += a;
  31468. cx += (x0 + x1) * a;
  31469. cy += (y0 + y1) * a;
  31470. x0 = x1;
  31471. y0 = y1;
  31472. }
  31473. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  31474. }
  31475. var Region = /** @class */function () {
  31476. function Region(name) {
  31477. this.name = name;
  31478. }
  31479. Region.prototype.setCenter = function (center) {
  31480. this._center = center;
  31481. };
  31482. /**
  31483. * Get center point in data unit. That is,
  31484. * for GeoJSONRegion, the unit is lat/lng,
  31485. * for GeoSVGRegion, the unit is SVG local coord.
  31486. */
  31487. Region.prototype.getCenter = function () {
  31488. var center = this._center;
  31489. if (!center) {
  31490. // In most cases there are no need to calculate this center.
  31491. // So calculate only when called.
  31492. center = this._center = this.calcCenter();
  31493. }
  31494. return center;
  31495. };
  31496. return Region;
  31497. }();
  31498. var GeoJSONPolygonGeometry = /** @class */function () {
  31499. function GeoJSONPolygonGeometry(exterior, interiors) {
  31500. this.type = 'polygon';
  31501. this.exterior = exterior;
  31502. this.interiors = interiors;
  31503. }
  31504. return GeoJSONPolygonGeometry;
  31505. }();
  31506. var GeoJSONLineStringGeometry = /** @class */function () {
  31507. function GeoJSONLineStringGeometry(points) {
  31508. this.type = 'linestring';
  31509. this.points = points;
  31510. }
  31511. return GeoJSONLineStringGeometry;
  31512. }();
  31513. var GeoJSONRegion = /** @class */function (_super) {
  31514. __extends(GeoJSONRegion, _super);
  31515. function GeoJSONRegion(name, geometries, cp) {
  31516. var _this = _super.call(this, name) || this;
  31517. _this.type = 'geoJSON';
  31518. _this.geometries = geometries;
  31519. _this._center = cp && [cp[0], cp[1]];
  31520. return _this;
  31521. }
  31522. GeoJSONRegion.prototype.calcCenter = function () {
  31523. var geometries = this.geometries;
  31524. var largestGeo;
  31525. var largestGeoSize = 0;
  31526. for (var i = 0; i < geometries.length; i++) {
  31527. var geo = geometries[i];
  31528. var exterior = geo.exterior;
  31529. // Simple trick to use points count instead of polygon area as region size.
  31530. // Ignore linestring
  31531. var size = exterior && exterior.length;
  31532. if (size > largestGeoSize) {
  31533. largestGeo = geo;
  31534. largestGeoSize = size;
  31535. }
  31536. }
  31537. if (largestGeo) {
  31538. return centroid(largestGeo.exterior);
  31539. }
  31540. // from bounding rect by default.
  31541. var rect = this.getBoundingRect();
  31542. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31543. };
  31544. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  31545. var rect = this._rect;
  31546. // Always recalculate if using projection.
  31547. if (rect && !projection) {
  31548. return rect;
  31549. }
  31550. var min = [Infinity, Infinity];
  31551. var max = [-Infinity, -Infinity];
  31552. var geometries = this.geometries;
  31553. each(geometries, function (geo) {
  31554. if (geo.type === 'polygon') {
  31555. // Doesn't consider hole
  31556. updateBBoxFromPoints(geo.exterior, min, max, projection);
  31557. } else {
  31558. each(geo.points, function (points) {
  31559. updateBBoxFromPoints(points, min, max, projection);
  31560. });
  31561. }
  31562. });
  31563. // Normalie invalid bounding.
  31564. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  31565. min[0] = min[1] = max[0] = max[1] = 0;
  31566. }
  31567. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  31568. if (!projection) {
  31569. this._rect = rect;
  31570. }
  31571. return rect;
  31572. };
  31573. GeoJSONRegion.prototype.contain = function (coord) {
  31574. var rect = this.getBoundingRect();
  31575. var geometries = this.geometries;
  31576. if (!rect.contain(coord[0], coord[1])) {
  31577. return false;
  31578. }
  31579. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  31580. var geo = geometries[i];
  31581. // Only support polygon.
  31582. if (geo.type !== 'polygon') {
  31583. continue;
  31584. }
  31585. var exterior = geo.exterior;
  31586. var interiors = geo.interiors;
  31587. if (contain$2(exterior, coord[0], coord[1])) {
  31588. // Not in the region if point is in the hole.
  31589. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31590. if (contain$2(interiors[k], coord[0], coord[1])) {
  31591. continue loopGeo;
  31592. }
  31593. }
  31594. return true;
  31595. }
  31596. }
  31597. return false;
  31598. };
  31599. /**
  31600. * Transform the raw coords to target bounding.
  31601. * @param x
  31602. * @param y
  31603. * @param width
  31604. * @param height
  31605. */
  31606. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  31607. var rect = this.getBoundingRect();
  31608. var aspect = rect.width / rect.height;
  31609. if (!width) {
  31610. width = aspect * height;
  31611. } else if (!height) {
  31612. height = width / aspect;
  31613. }
  31614. var target = new BoundingRect(x, y, width, height);
  31615. var transform = rect.calculateTransform(target);
  31616. var geometries = this.geometries;
  31617. for (var i = 0; i < geometries.length; i++) {
  31618. var geo = geometries[i];
  31619. if (geo.type === 'polygon') {
  31620. transformPoints(geo.exterior, transform);
  31621. each(geo.interiors, function (interior) {
  31622. transformPoints(interior, transform);
  31623. });
  31624. } else {
  31625. each(geo.points, function (points) {
  31626. transformPoints(points, transform);
  31627. });
  31628. }
  31629. }
  31630. rect = this._rect;
  31631. rect.copy(target);
  31632. // Update center
  31633. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31634. };
  31635. GeoJSONRegion.prototype.cloneShallow = function (name) {
  31636. name == null && (name = this.name);
  31637. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  31638. newRegion._rect = this._rect;
  31639. newRegion.transformTo = null; // Simply avoid to be called.
  31640. return newRegion;
  31641. };
  31642. return GeoJSONRegion;
  31643. }(Region);
  31644. var GeoSVGRegion = /** @class */function (_super) {
  31645. __extends(GeoSVGRegion, _super);
  31646. function GeoSVGRegion(name, elOnlyForCalculate) {
  31647. var _this = _super.call(this, name) || this;
  31648. _this.type = 'geoSVG';
  31649. _this._elOnlyForCalculate = elOnlyForCalculate;
  31650. return _this;
  31651. }
  31652. GeoSVGRegion.prototype.calcCenter = function () {
  31653. var el = this._elOnlyForCalculate;
  31654. var rect = el.getBoundingRect();
  31655. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31656. var mat = identity(TMP_TRANSFORM);
  31657. var target = el;
  31658. while (target && !target.isGeoSVGGraphicRoot) {
  31659. mul$1(mat, target.getLocalTransform(), mat);
  31660. target = target.parent;
  31661. }
  31662. invert(mat, mat);
  31663. applyTransform(center, center, mat);
  31664. return center;
  31665. };
  31666. return GeoSVGRegion;
  31667. }(Region);
  31668. function decode(json) {
  31669. if (!json.UTF8Encoding) {
  31670. return json;
  31671. }
  31672. var jsonCompressed = json;
  31673. var encodeScale = jsonCompressed.UTF8Scale;
  31674. if (encodeScale == null) {
  31675. encodeScale = 1024;
  31676. }
  31677. var features = jsonCompressed.features;
  31678. each(features, function (feature) {
  31679. var geometry = feature.geometry;
  31680. var encodeOffsets = geometry.encodeOffsets;
  31681. var coordinates = geometry.coordinates;
  31682. // Geometry may be appeded manually in the script after json loaded.
  31683. // In this case this geometry is usually not encoded.
  31684. if (!encodeOffsets) {
  31685. return;
  31686. }
  31687. switch (geometry.type) {
  31688. case 'LineString':
  31689. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  31690. break;
  31691. case 'Polygon':
  31692. decodeRings(coordinates, encodeOffsets, encodeScale);
  31693. break;
  31694. case 'MultiLineString':
  31695. decodeRings(coordinates, encodeOffsets, encodeScale);
  31696. break;
  31697. case 'MultiPolygon':
  31698. each(coordinates, function (rings, idx) {
  31699. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  31700. });
  31701. }
  31702. });
  31703. // Has been decoded
  31704. jsonCompressed.UTF8Encoding = false;
  31705. return jsonCompressed;
  31706. }
  31707. function decodeRings(rings, encodeOffsets, encodeScale) {
  31708. for (var c = 0; c < rings.length; c++) {
  31709. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  31710. }
  31711. }
  31712. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  31713. var result = [];
  31714. var prevX = encodeOffsets[0];
  31715. var prevY = encodeOffsets[1];
  31716. for (var i = 0; i < coordinate.length; i += 2) {
  31717. var x = coordinate.charCodeAt(i) - 64;
  31718. var y = coordinate.charCodeAt(i + 1) - 64;
  31719. // ZigZag decoding
  31720. x = x >> 1 ^ -(x & 1);
  31721. y = y >> 1 ^ -(y & 1);
  31722. // Delta deocding
  31723. x += prevX;
  31724. y += prevY;
  31725. prevX = x;
  31726. prevY = y;
  31727. // Dequantize
  31728. result.push([x / encodeScale, y / encodeScale]);
  31729. }
  31730. return result;
  31731. }
  31732. function parseGeoJSON(geoJson, nameProperty) {
  31733. geoJson = decode(geoJson);
  31734. return map(filter(geoJson.features, function (featureObj) {
  31735. // Output of mapshaper may have geometry null
  31736. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  31737. }), function (featureObj) {
  31738. var properties = featureObj.properties;
  31739. var geo = featureObj.geometry;
  31740. var geometries = [];
  31741. switch (geo.type) {
  31742. case 'Polygon':
  31743. var coordinates = geo.coordinates;
  31744. // According to the GeoJSON specification.
  31745. // First must be exterior, and the rest are all interior(holes).
  31746. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  31747. break;
  31748. case 'MultiPolygon':
  31749. each(geo.coordinates, function (item) {
  31750. if (item[0]) {
  31751. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  31752. }
  31753. });
  31754. break;
  31755. case 'LineString':
  31756. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  31757. break;
  31758. case 'MultiLineString':
  31759. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  31760. }
  31761. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  31762. region.properties = properties;
  31763. return region;
  31764. });
  31765. }
  31766. var number = /*#__PURE__*/Object.freeze({
  31767. __proto__: null,
  31768. linearMap: linearMap,
  31769. round: round,
  31770. asc: asc,
  31771. getPrecision: getPrecision,
  31772. getPrecisionSafe: getPrecisionSafe,
  31773. getPixelPrecision: getPixelPrecision,
  31774. getPercentWithPrecision: getPercentWithPrecision,
  31775. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  31776. remRadian: remRadian,
  31777. isRadianAroundZero: isRadianAroundZero,
  31778. parseDate: parseDate,
  31779. quantity: quantity,
  31780. quantityExponent: quantityExponent,
  31781. nice: nice,
  31782. quantile: quantile,
  31783. reformIntervals: reformIntervals,
  31784. isNumeric: isNumeric,
  31785. numericToNumber: numericToNumber
  31786. });
  31787. var time = /*#__PURE__*/Object.freeze({
  31788. __proto__: null,
  31789. parse: parseDate,
  31790. format: format
  31791. });
  31792. var graphic = /*#__PURE__*/Object.freeze({
  31793. __proto__: null,
  31794. extendShape: extendShape,
  31795. extendPath: extendPath,
  31796. makePath: makePath,
  31797. makeImage: makeImage,
  31798. mergePath: mergePath$1,
  31799. resizePath: resizePath,
  31800. createIcon: createIcon,
  31801. updateProps: updateProps,
  31802. initProps: initProps,
  31803. getTransform: getTransform,
  31804. clipPointsByRect: clipPointsByRect,
  31805. clipRectByRect: clipRectByRect,
  31806. registerShape: registerShape,
  31807. getShapeClass: getShapeClass,
  31808. Group: Group,
  31809. Image: ZRImage,
  31810. Text: ZRText,
  31811. Circle: Circle,
  31812. Ellipse: Ellipse,
  31813. Sector: Sector,
  31814. Ring: Ring,
  31815. Polygon: Polygon,
  31816. Polyline: Polyline,
  31817. Rect: Rect,
  31818. Line: Line,
  31819. BezierCurve: BezierCurve,
  31820. Arc: Arc,
  31821. IncrementalDisplayable: IncrementalDisplayable,
  31822. CompoundPath: CompoundPath,
  31823. LinearGradient: LinearGradient,
  31824. RadialGradient: RadialGradient,
  31825. BoundingRect: BoundingRect
  31826. });
  31827. var format$1 = /*#__PURE__*/Object.freeze({
  31828. __proto__: null,
  31829. addCommas: addCommas,
  31830. toCamelCase: toCamelCase,
  31831. normalizeCssArray: normalizeCssArray$1,
  31832. encodeHTML: encodeHTML,
  31833. formatTpl: formatTpl,
  31834. getTooltipMarker: getTooltipMarker,
  31835. formatTime: formatTime,
  31836. capitalFirst: capitalFirst,
  31837. truncateText: truncateText,
  31838. getTextRect: getTextRect
  31839. });
  31840. var util$1 = /*#__PURE__*/Object.freeze({
  31841. __proto__: null,
  31842. map: map,
  31843. each: each,
  31844. indexOf: indexOf,
  31845. inherits: inherits,
  31846. reduce: reduce,
  31847. filter: filter,
  31848. bind: bind,
  31849. curry: curry,
  31850. isArray: isArray,
  31851. isString: isString,
  31852. isObject: isObject,
  31853. isFunction: isFunction,
  31854. extend: extend,
  31855. defaults: defaults,
  31856. clone: clone,
  31857. merge: merge
  31858. });
  31859. var inner$5 = makeInner();
  31860. function tickValuesToNumbers(axis, values) {
  31861. var nums = map(values, function (val) {
  31862. return axis.scale.parse(val);
  31863. });
  31864. if (axis.type === 'time' && nums.length > 0) {
  31865. // Time axis needs duplicate first/last tick (see TimeScale.getTicks())
  31866. // The first and last tick/label don't get drawn
  31867. nums.sort();
  31868. nums.unshift(nums[0]);
  31869. nums.push(nums[nums.length - 1]);
  31870. }
  31871. return nums;
  31872. }
  31873. function createAxisLabels(axis) {
  31874. var custom = axis.getLabelModel().get('customValues');
  31875. if (custom) {
  31876. var labelFormatter_1 = makeLabelFormatter(axis);
  31877. return {
  31878. labels: tickValuesToNumbers(axis, custom).map(function (numval) {
  31879. var tick = {
  31880. value: numval
  31881. };
  31882. return {
  31883. formattedLabel: labelFormatter_1(tick),
  31884. rawLabel: axis.scale.getLabel(tick),
  31885. tickValue: numval
  31886. };
  31887. })
  31888. };
  31889. }
  31890. // Only ordinal scale support tick interval
  31891. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  31892. }
  31893. /**
  31894. * @param {module:echats/coord/Axis} axis
  31895. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31896. * @return {Object} {
  31897. * ticks: Array.<number>
  31898. * tickCategoryInterval: number
  31899. * }
  31900. */
  31901. function createAxisTicks(axis, tickModel) {
  31902. var custom = axis.getTickModel().get('customValues');
  31903. if (custom) {
  31904. return {
  31905. ticks: tickValuesToNumbers(axis, custom)
  31906. };
  31907. }
  31908. // Only ordinal scale support tick interval
  31909. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  31910. ticks: map(axis.scale.getTicks(), function (tick) {
  31911. return tick.value;
  31912. })
  31913. };
  31914. }
  31915. function makeCategoryLabels(axis) {
  31916. var labelModel = axis.getLabelModel();
  31917. var result = makeCategoryLabelsActually(axis, labelModel);
  31918. return !labelModel.get('show') || axis.scale.isBlank() ? {
  31919. labels: [],
  31920. labelCategoryInterval: result.labelCategoryInterval
  31921. } : result;
  31922. }
  31923. function makeCategoryLabelsActually(axis, labelModel) {
  31924. var labelsCache = getListCache(axis, 'labels');
  31925. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31926. var result = listCacheGet(labelsCache, optionLabelInterval);
  31927. if (result) {
  31928. return result;
  31929. }
  31930. var labels;
  31931. var numericLabelInterval;
  31932. if (isFunction(optionLabelInterval)) {
  31933. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31934. } else {
  31935. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31936. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31937. }
  31938. // Cache to avoid calling interval function repeatedly.
  31939. return listCacheSet(labelsCache, optionLabelInterval, {
  31940. labels: labels,
  31941. labelCategoryInterval: numericLabelInterval
  31942. });
  31943. }
  31944. function makeCategoryTicks(axis, tickModel) {
  31945. var ticksCache = getListCache(axis, 'ticks');
  31946. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31947. var result = listCacheGet(ticksCache, optionTickInterval);
  31948. if (result) {
  31949. return result;
  31950. }
  31951. var ticks;
  31952. var tickCategoryInterval;
  31953. // Optimize for the case that large category data and no label displayed,
  31954. // we should not return all ticks.
  31955. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31956. ticks = [];
  31957. }
  31958. if (isFunction(optionTickInterval)) {
  31959. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31960. }
  31961. // Always use label interval by default despite label show. Consider this
  31962. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31963. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31964. else if (optionTickInterval === 'auto') {
  31965. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31966. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31967. ticks = map(labelsResult.labels, function (labelItem) {
  31968. return labelItem.tickValue;
  31969. });
  31970. } else {
  31971. tickCategoryInterval = optionTickInterval;
  31972. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31973. }
  31974. // Cache to avoid calling interval function repeatedly.
  31975. return listCacheSet(ticksCache, optionTickInterval, {
  31976. ticks: ticks,
  31977. tickCategoryInterval: tickCategoryInterval
  31978. });
  31979. }
  31980. function makeRealNumberLabels(axis) {
  31981. var ticks = axis.scale.getTicks();
  31982. var labelFormatter = makeLabelFormatter(axis);
  31983. return {
  31984. labels: map(ticks, function (tick, idx) {
  31985. return {
  31986. level: tick.level,
  31987. formattedLabel: labelFormatter(tick, idx),
  31988. rawLabel: axis.scale.getLabel(tick),
  31989. tickValue: tick.value
  31990. };
  31991. })
  31992. };
  31993. }
  31994. function getListCache(axis, prop) {
  31995. // Because key can be a function, and cache size always is small, we use array cache.
  31996. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  31997. }
  31998. function listCacheGet(cache, key) {
  31999. for (var i = 0; i < cache.length; i++) {
  32000. if (cache[i].key === key) {
  32001. return cache[i].value;
  32002. }
  32003. }
  32004. }
  32005. function listCacheSet(cache, key, value) {
  32006. cache.push({
  32007. key: key,
  32008. value: value
  32009. });
  32010. return value;
  32011. }
  32012. function makeAutoCategoryInterval(axis) {
  32013. var result = inner$5(axis).autoInterval;
  32014. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  32015. }
  32016. /**
  32017. * Calculate interval for category axis ticks and labels.
  32018. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32019. * should be implemented in axis.
  32020. */
  32021. function calculateCategoryInterval(axis) {
  32022. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32023. var labelFormatter = makeLabelFormatter(axis);
  32024. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32025. var ordinalScale = axis.scale;
  32026. var ordinalExtent = ordinalScale.getExtent();
  32027. // Providing this method is for optimization:
  32028. // avoid generating a long array by `getTicks`
  32029. // in large category data case.
  32030. var tickCount = ordinalScale.count();
  32031. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32032. return 0;
  32033. }
  32034. var step = 1;
  32035. // Simple optimization. Empirical value: tick count should less than 40.
  32036. if (tickCount > 40) {
  32037. step = Math.max(1, Math.floor(tickCount / 40));
  32038. }
  32039. var tickValue = ordinalExtent[0];
  32040. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32041. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32042. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32043. var maxW = 0;
  32044. var maxH = 0;
  32045. // Caution: Performance sensitive for large category data.
  32046. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32047. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32048. var width = 0;
  32049. var height = 0;
  32050. // Not precise, do not consider align and vertical align
  32051. // and each distance from axis line yet.
  32052. var rect = getBoundingRect(labelFormatter({
  32053. value: tickValue
  32054. }), params.font, 'center', 'top');
  32055. // Magic number
  32056. width = rect.width * 1.3;
  32057. height = rect.height * 1.3;
  32058. // Min size, void long loop.
  32059. maxW = Math.max(maxW, width, 7);
  32060. maxH = Math.max(maxH, height, 7);
  32061. }
  32062. var dw = maxW / unitW;
  32063. var dh = maxH / unitH;
  32064. // 0/0 is NaN, 1/0 is Infinity.
  32065. isNaN(dw) && (dw = Infinity);
  32066. isNaN(dh) && (dh = Infinity);
  32067. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32068. var cache = inner$5(axis.model);
  32069. var axisExtent = axis.getExtent();
  32070. var lastAutoInterval = cache.lastAutoInterval;
  32071. var lastTickCount = cache.lastTickCount;
  32072. // Use cache to keep interval stable while moving zoom window,
  32073. // otherwise the calculated interval might jitter when the zoom
  32074. // window size is close to the interval-changing size.
  32075. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32076. // The jitter will cause that sometimes the displayed labels are
  32077. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32078. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1
  32079. // Always choose the bigger one, otherwise the critical
  32080. // point is not the same when zooming in or zooming out.
  32081. && lastAutoInterval > interval
  32082. // If the axis change is caused by chart resize, the cache should not
  32083. // be used. Otherwise some hidden labels might not be shown again.
  32084. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  32085. interval = lastAutoInterval;
  32086. }
  32087. // Only update cache if cache not used, otherwise the
  32088. // changing of interval is too insensitive.
  32089. else {
  32090. cache.lastTickCount = tickCount;
  32091. cache.lastAutoInterval = interval;
  32092. cache.axisExtent0 = axisExtent[0];
  32093. cache.axisExtent1 = axisExtent[1];
  32094. }
  32095. return interval;
  32096. }
  32097. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32098. var labelModel = axis.getLabelModel();
  32099. return {
  32100. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  32101. labelRotate: labelModel.get('rotate') || 0,
  32102. font: labelModel.getFont()
  32103. };
  32104. }
  32105. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32106. var labelFormatter = makeLabelFormatter(axis);
  32107. var ordinalScale = axis.scale;
  32108. var ordinalExtent = ordinalScale.getExtent();
  32109. var labelModel = axis.getLabelModel();
  32110. var result = [];
  32111. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32112. var step = Math.max((categoryInterval || 0) + 1, 1);
  32113. var startTick = ordinalExtent[0];
  32114. var tickCount = ordinalScale.count();
  32115. // Calculate start tick based on zero if possible to keep label consistent
  32116. // while zooming and moving while interval > 0. Otherwise the selection
  32117. // of displayable ticks and symbols probably keep changing.
  32118. // 3 is empirical value.
  32119. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32120. startTick = Math.round(Math.ceil(startTick / step) * step);
  32121. }
  32122. // (1) Only add min max label here but leave overlap checking
  32123. // to render stage, which also ensure the returned list
  32124. // suitable for splitLine and splitArea rendering.
  32125. // (2) Scales except category always contain min max label so
  32126. // do not need to perform this process.
  32127. var showAllLabel = shouldShowAllLabels(axis);
  32128. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32129. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32130. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32131. addItem(ordinalExtent[0]);
  32132. }
  32133. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32134. var tickValue = startTick;
  32135. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32136. addItem(tickValue);
  32137. }
  32138. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32139. addItem(ordinalExtent[1]);
  32140. }
  32141. function addItem(tickValue) {
  32142. var tickObj = {
  32143. value: tickValue
  32144. };
  32145. result.push(onlyTick ? tickValue : {
  32146. formattedLabel: labelFormatter(tickObj),
  32147. rawLabel: ordinalScale.getLabel(tickObj),
  32148. tickValue: tickValue
  32149. });
  32150. }
  32151. return result;
  32152. }
  32153. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32154. var ordinalScale = axis.scale;
  32155. var labelFormatter = makeLabelFormatter(axis);
  32156. var result = [];
  32157. each(ordinalScale.getTicks(), function (tick) {
  32158. var rawLabel = ordinalScale.getLabel(tick);
  32159. var tickValue = tick.value;
  32160. if (categoryInterval(tick.value, rawLabel)) {
  32161. result.push(onlyTick ? tickValue : {
  32162. formattedLabel: labelFormatter(tick),
  32163. rawLabel: rawLabel,
  32164. tickValue: tickValue
  32165. });
  32166. }
  32167. });
  32168. return result;
  32169. }
  32170. var NORMALIZED_EXTENT = [0, 1];
  32171. /**
  32172. * Base class of Axis.
  32173. */
  32174. var Axis = /** @class */function () {
  32175. function Axis(dim, scale, extent) {
  32176. this.onBand = false;
  32177. this.inverse = false;
  32178. this.dim = dim;
  32179. this.scale = scale;
  32180. this._extent = extent || [0, 0];
  32181. }
  32182. /**
  32183. * If axis extent contain given coord
  32184. */
  32185. Axis.prototype.contain = function (coord) {
  32186. var extent = this._extent;
  32187. var min = Math.min(extent[0], extent[1]);
  32188. var max = Math.max(extent[0], extent[1]);
  32189. return coord >= min && coord <= max;
  32190. };
  32191. /**
  32192. * If axis extent contain given data
  32193. */
  32194. Axis.prototype.containData = function (data) {
  32195. return this.scale.contain(data);
  32196. };
  32197. /**
  32198. * Get coord extent.
  32199. */
  32200. Axis.prototype.getExtent = function () {
  32201. return this._extent.slice();
  32202. };
  32203. /**
  32204. * Get precision used for formatting
  32205. */
  32206. Axis.prototype.getPixelPrecision = function (dataExtent) {
  32207. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  32208. };
  32209. /**
  32210. * Set coord extent
  32211. */
  32212. Axis.prototype.setExtent = function (start, end) {
  32213. var extent = this._extent;
  32214. extent[0] = start;
  32215. extent[1] = end;
  32216. };
  32217. /**
  32218. * Convert data to coord. Data is the rank if it has an ordinal scale
  32219. */
  32220. Axis.prototype.dataToCoord = function (data, clamp) {
  32221. var extent = this._extent;
  32222. var scale = this.scale;
  32223. data = scale.normalize(data);
  32224. if (this.onBand && scale.type === 'ordinal') {
  32225. extent = extent.slice();
  32226. fixExtentWithBands(extent, scale.count());
  32227. }
  32228. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32229. };
  32230. /**
  32231. * Convert coord to data. Data is the rank if it has an ordinal scale
  32232. */
  32233. Axis.prototype.coordToData = function (coord, clamp) {
  32234. var extent = this._extent;
  32235. var scale = this.scale;
  32236. if (this.onBand && scale.type === 'ordinal') {
  32237. extent = extent.slice();
  32238. fixExtentWithBands(extent, scale.count());
  32239. }
  32240. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32241. return this.scale.scale(t);
  32242. };
  32243. /**
  32244. * Convert pixel point to data in axis
  32245. */
  32246. Axis.prototype.pointToData = function (point, clamp) {
  32247. // Should be implemented in derived class if necessary.
  32248. return;
  32249. };
  32250. /**
  32251. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32252. * `axis.getTicksCoords` considers `onBand`, which is used by
  32253. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32254. * @param opt.tickModel default: axis.model.getModel('axisTick')
  32255. * @param opt.clamp If `true`, the first and the last
  32256. * tick must be at the axis end points. Otherwise, clip ticks
  32257. * that outside the axis extent.
  32258. */
  32259. Axis.prototype.getTicksCoords = function (opt) {
  32260. opt = opt || {};
  32261. var tickModel = opt.tickModel || this.getTickModel();
  32262. var result = createAxisTicks(this, tickModel);
  32263. var ticks = result.ticks;
  32264. var ticksCoords = map(ticks, function (tickVal) {
  32265. return {
  32266. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  32267. tickValue: tickVal
  32268. };
  32269. }, this);
  32270. var alignWithLabel = tickModel.get('alignWithLabel');
  32271. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  32272. return ticksCoords;
  32273. };
  32274. Axis.prototype.getMinorTicksCoords = function () {
  32275. if (this.scale.type === 'ordinal') {
  32276. // Category axis doesn't support minor ticks
  32277. return [];
  32278. }
  32279. var minorTickModel = this.model.getModel('minorTick');
  32280. var splitNumber = minorTickModel.get('splitNumber');
  32281. // Protection.
  32282. if (!(splitNumber > 0 && splitNumber < 100)) {
  32283. splitNumber = 5;
  32284. }
  32285. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32286. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32287. return map(minorTicksGroup, function (minorTick) {
  32288. return {
  32289. coord: this.dataToCoord(minorTick),
  32290. tickValue: minorTick
  32291. };
  32292. }, this);
  32293. }, this);
  32294. return minorTicksCoords;
  32295. };
  32296. Axis.prototype.getViewLabels = function () {
  32297. return createAxisLabels(this).labels;
  32298. };
  32299. Axis.prototype.getLabelModel = function () {
  32300. return this.model.getModel('axisLabel');
  32301. };
  32302. /**
  32303. * Notice here we only get the default tick model. For splitLine
  32304. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32305. * manually when calling `getTicksCoords`.
  32306. * In GL, this method may be overridden to:
  32307. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32308. */
  32309. Axis.prototype.getTickModel = function () {
  32310. return this.model.getModel('axisTick');
  32311. };
  32312. /**
  32313. * Get width of band
  32314. */
  32315. Axis.prototype.getBandWidth = function () {
  32316. var axisExtent = this._extent;
  32317. var dataExtent = this.scale.getExtent();
  32318. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32319. // Fix #2728, avoid NaN when only one data.
  32320. len === 0 && (len = 1);
  32321. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32322. return Math.abs(size) / len;
  32323. };
  32324. /**
  32325. * Only be called in category axis.
  32326. * Can be overridden, consider other axes like in 3D.
  32327. * @return Auto interval for cateogry axis tick and label
  32328. */
  32329. Axis.prototype.calculateCategoryInterval = function () {
  32330. return calculateCategoryInterval(this);
  32331. };
  32332. return Axis;
  32333. }();
  32334. function fixExtentWithBands(extent, nTick) {
  32335. var size = extent[1] - extent[0];
  32336. var len = nTick;
  32337. var margin = size / len / 2;
  32338. extent[0] += margin;
  32339. extent[1] -= margin;
  32340. }
  32341. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32342. // |---1---|---2---|---3---|---4---|.
  32343. // So the displayed ticks and splitLine/splitArea should between
  32344. // each data item, otherwise cause misleading (e.g., split tow bars
  32345. // of a single data item when there are two bar series).
  32346. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32347. // splitLine/spliteArea should layout appropriately corresponding
  32348. // to displayed labels. (So we should not use `getBandWidth` in this
  32349. // case).
  32350. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32351. var ticksLen = ticksCoords.length;
  32352. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32353. return;
  32354. }
  32355. var axisExtent = axis.getExtent();
  32356. var last;
  32357. var diffSize;
  32358. if (ticksLen === 1) {
  32359. ticksCoords[0].coord = axisExtent[0];
  32360. last = ticksCoords[1] = {
  32361. coord: axisExtent[1]
  32362. };
  32363. } else {
  32364. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32365. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32366. each(ticksCoords, function (ticksItem) {
  32367. ticksItem.coord -= shift_1 / 2;
  32368. });
  32369. var dataExtent = axis.scale.getExtent();
  32370. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32371. last = {
  32372. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32373. };
  32374. ticksCoords.push(last);
  32375. }
  32376. var inverse = axisExtent[0] > axisExtent[1];
  32377. // Handling clamp.
  32378. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32379. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32380. }
  32381. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32382. ticksCoords.unshift({
  32383. coord: axisExtent[0]
  32384. });
  32385. }
  32386. if (littleThan(axisExtent[1], last.coord)) {
  32387. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32388. }
  32389. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32390. ticksCoords.push({
  32391. coord: axisExtent[1]
  32392. });
  32393. }
  32394. function littleThan(a, b) {
  32395. // Avoid rounding error cause calculated tick coord different with extent.
  32396. // It may cause an extra unnecessary tick added.
  32397. a = round(a);
  32398. b = round(b);
  32399. return inverse ? a > b : a < b;
  32400. }
  32401. }
  32402. // --------------------- Deprecated Extension Methods ---------------------
  32403. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32404. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32405. // class Bar3DModel extends ComponentModel {}
  32406. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  32407. // echarts.use(install);
  32408. function extendComponentModel(proto) {
  32409. var Model = ComponentModel.extend(proto);
  32410. ComponentModel.registerClass(Model);
  32411. return Model;
  32412. }
  32413. function extendComponentView(proto) {
  32414. var View = ComponentView.extend(proto);
  32415. ComponentView.registerClass(View);
  32416. return View;
  32417. }
  32418. function extendSeriesModel(proto) {
  32419. var Model = SeriesModel.extend(proto);
  32420. SeriesModel.registerClass(Model);
  32421. return Model;
  32422. }
  32423. function extendChartView(proto) {
  32424. var View = ChartView.extend(proto);
  32425. ChartView.registerClass(View);
  32426. return View;
  32427. }
  32428. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  32429. var dx = x - x1;
  32430. var dy = y - y1;
  32431. var dx1 = x2 - x1;
  32432. var dy1 = y2 - y1;
  32433. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  32434. dx1 /= lineLen;
  32435. dy1 /= lineLen;
  32436. // dot product
  32437. var projectedLen = dx * dx1 + dy * dy1;
  32438. var t = projectedLen / lineLen;
  32439. if (limitToEnds) {
  32440. t = Math.min(Math.max(t, 0), 1);
  32441. }
  32442. t *= lineLen;
  32443. var ox = out[0] = x1 + t * dx1;
  32444. var oy = out[1] = y1 + t * dy1;
  32445. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  32446. }
  32447. // Temporal variable for intermediate usage.
  32448. var pt0 = new Point();
  32449. var pt1 = new Point();
  32450. var pt2 = new Point();
  32451. var dir = new Point();
  32452. var dir2 = new Point();
  32453. // Temporal variable for the limitTurnAngle function
  32454. var tmpArr = [];
  32455. var tmpProjPoint = new Point();
  32456. /**
  32457. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  32458. * @param linePoints
  32459. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  32460. */
  32461. function limitTurnAngle(linePoints, minTurnAngle) {
  32462. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  32463. return;
  32464. }
  32465. minTurnAngle = minTurnAngle / 180 * Math.PI;
  32466. // The line points can be
  32467. // /pt1----pt2 (label)
  32468. // /
  32469. // pt0/
  32470. pt0.fromArray(linePoints[0]);
  32471. pt1.fromArray(linePoints[1]);
  32472. pt2.fromArray(linePoints[2]);
  32473. Point.sub(dir, pt0, pt1);
  32474. Point.sub(dir2, pt2, pt1);
  32475. var len1 = dir.len();
  32476. var len2 = dir2.len();
  32477. if (len1 < 1e-3 || len2 < 1e-3) {
  32478. return;
  32479. }
  32480. dir.scale(1 / len1);
  32481. dir2.scale(1 / len2);
  32482. var angleCos = dir.dot(dir2);
  32483. var minTurnAngleCos = Math.cos(minTurnAngle);
  32484. if (minTurnAngleCos < angleCos) {
  32485. // Smaller than minTurnAngle
  32486. // Calculate project point of pt0 on pt1-pt2
  32487. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  32488. tmpProjPoint.fromArray(tmpArr);
  32489. // Calculate new projected length with limited minTurnAngle and get the new connect point
  32490. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle));
  32491. // Limit the new calculated connect point between pt1 and pt2.
  32492. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  32493. if (isNaN(t)) {
  32494. return;
  32495. }
  32496. if (t < 0) {
  32497. Point.copy(tmpProjPoint, pt1);
  32498. } else if (t > 1) {
  32499. Point.copy(tmpProjPoint, pt2);
  32500. }
  32501. tmpProjPoint.toArray(linePoints[1]);
  32502. }
  32503. }
  32504. /**
  32505. * Limit the angle of line and the surface
  32506. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  32507. */
  32508. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  32509. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  32510. return;
  32511. }
  32512. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  32513. pt0.fromArray(linePoints[0]);
  32514. pt1.fromArray(linePoints[1]);
  32515. pt2.fromArray(linePoints[2]);
  32516. Point.sub(dir, pt1, pt0);
  32517. Point.sub(dir2, pt2, pt1);
  32518. var len1 = dir.len();
  32519. var len2 = dir2.len();
  32520. if (len1 < 1e-3 || len2 < 1e-3) {
  32521. return;
  32522. }
  32523. dir.scale(1 / len1);
  32524. dir2.scale(1 / len2);
  32525. var angleCos = dir.dot(surfaceNormal);
  32526. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  32527. if (angleCos < maxSurfaceAngleCos) {
  32528. // Calculate project point of pt0 on pt1-pt2
  32529. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  32530. tmpProjPoint.fromArray(tmpArr);
  32531. var HALF_PI = Math.PI / 2;
  32532. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  32533. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  32534. if (newAngle >= HALF_PI) {
  32535. // parallel
  32536. Point.copy(tmpProjPoint, pt2);
  32537. } else {
  32538. // Calculate new projected length with limited minTurnAngle and get the new connect point
  32539. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle));
  32540. // Limit the new calculated connect point between pt1 and pt2.
  32541. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  32542. if (isNaN(t)) {
  32543. return;
  32544. }
  32545. if (t < 0) {
  32546. Point.copy(tmpProjPoint, pt1);
  32547. } else if (t > 1) {
  32548. Point.copy(tmpProjPoint, pt2);
  32549. }
  32550. }
  32551. tmpProjPoint.toArray(linePoints[1]);
  32552. }
  32553. }
  32554. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  32555. var isNormal = stateName === 'normal';
  32556. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName);
  32557. // Make sure display.
  32558. stateObj.ignore = ignore;
  32559. // Set smooth
  32560. var smooth = stateModel.get('smooth');
  32561. if (smooth && smooth === true) {
  32562. smooth = 0.3;
  32563. }
  32564. stateObj.shape = stateObj.shape || {};
  32565. if (smooth > 0) {
  32566. stateObj.shape.smooth = smooth;
  32567. }
  32568. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  32569. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  32570. }
  32571. function buildLabelLinePath(path, shape) {
  32572. var smooth = shape.smooth;
  32573. var points = shape.points;
  32574. if (!points) {
  32575. return;
  32576. }
  32577. path.moveTo(points[0][0], points[0][1]);
  32578. if (smooth > 0 && points.length >= 3) {
  32579. var len1 = dist(points[0], points[1]);
  32580. var len2 = dist(points[1], points[2]);
  32581. if (!len1 || !len2) {
  32582. path.lineTo(points[1][0], points[1][1]);
  32583. path.lineTo(points[2][0], points[2][1]);
  32584. return;
  32585. }
  32586. var moveLen = Math.min(len1, len2) * smooth;
  32587. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  32588. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  32589. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  32590. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  32591. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  32592. } else {
  32593. for (var i = 1; i < points.length; i++) {
  32594. path.lineTo(points[i][0], points[i][1]);
  32595. }
  32596. }
  32597. }
  32598. /**
  32599. * Create a label line if necessary and set it's style.
  32600. */
  32601. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  32602. var labelLine = targetEl.getTextGuideLine();
  32603. var label = targetEl.getTextContent();
  32604. if (!label) {
  32605. // Not show label line if there is no label.
  32606. if (labelLine) {
  32607. targetEl.removeTextGuideLine();
  32608. }
  32609. return;
  32610. }
  32611. var normalModel = statesModels.normal;
  32612. var showNormal = normalModel.get('show');
  32613. var labelIgnoreNormal = label.ignore;
  32614. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  32615. var stateName = DISPLAY_STATES[i];
  32616. var stateModel = statesModels[stateName];
  32617. var isNormal = stateName === 'normal';
  32618. if (stateModel) {
  32619. var stateShow = stateModel.get('show');
  32620. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  32621. if (isLabelIgnored // Not show when label is not shown in this state.
  32622. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  32623. ) {
  32624. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  32625. if (stateObj) {
  32626. stateObj.ignore = true;
  32627. }
  32628. if (!!labelLine) {
  32629. setLabelLineState(labelLine, true, stateName, stateModel);
  32630. }
  32631. continue;
  32632. }
  32633. // Create labelLine if not exists
  32634. if (!labelLine) {
  32635. labelLine = new Polyline();
  32636. targetEl.setTextGuideLine(labelLine);
  32637. // Reset state of normal because it's new created.
  32638. // NOTE: NORMAL should always been the first!
  32639. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  32640. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  32641. }
  32642. // Use same state proxy.
  32643. if (targetEl.stateProxy) {
  32644. labelLine.stateProxy = targetEl.stateProxy;
  32645. }
  32646. }
  32647. setLabelLineState(labelLine, false, stateName, stateModel);
  32648. }
  32649. }
  32650. if (labelLine) {
  32651. defaults(labelLine.style, defaultStyle);
  32652. // Not fill.
  32653. labelLine.style.fill = null;
  32654. var showAbove = normalModel.get('showAbove');
  32655. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  32656. labelLineConfig.showAbove = showAbove || false;
  32657. // Custom the buildPath.
  32658. labelLine.buildPath = buildLabelLinePath;
  32659. }
  32660. }
  32661. function getLabelLineStatesModels(itemModel, labelLineName) {
  32662. labelLineName = labelLineName || 'labelLine';
  32663. var statesModels = {
  32664. normal: itemModel.getModel(labelLineName)
  32665. };
  32666. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  32667. var stateName = SPECIAL_STATES[i];
  32668. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  32669. }
  32670. return statesModels;
  32671. }
  32672. function prepareLayoutList(input) {
  32673. var list = [];
  32674. for (var i = 0; i < input.length; i++) {
  32675. var rawItem = input[i];
  32676. if (rawItem.defaultAttr.ignore) {
  32677. continue;
  32678. }
  32679. var label = rawItem.label;
  32680. var transform = label.getComputedTransform();
  32681. // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  32682. var localRect = label.getBoundingRect();
  32683. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  32684. var minMargin = label.style.margin || 0;
  32685. var globalRect = localRect.clone();
  32686. globalRect.applyTransform(transform);
  32687. globalRect.x -= minMargin / 2;
  32688. globalRect.y -= minMargin / 2;
  32689. globalRect.width += minMargin;
  32690. globalRect.height += minMargin;
  32691. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  32692. list.push({
  32693. label: label,
  32694. labelLine: rawItem.labelLine,
  32695. rect: globalRect,
  32696. localRect: localRect,
  32697. obb: obb,
  32698. priority: rawItem.priority,
  32699. defaultAttr: rawItem.defaultAttr,
  32700. layoutOption: rawItem.computedLayoutOption,
  32701. axisAligned: isAxisAligned,
  32702. transform: transform
  32703. });
  32704. }
  32705. return list;
  32706. }
  32707. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  32708. var len = list.length;
  32709. if (len < 2) {
  32710. return;
  32711. }
  32712. list.sort(function (a, b) {
  32713. return a.rect[xyDim] - b.rect[xyDim];
  32714. });
  32715. var lastPos = 0;
  32716. var delta;
  32717. var adjusted = false;
  32718. var totalShifts = 0;
  32719. for (var i = 0; i < len; i++) {
  32720. var item = list[i];
  32721. var rect = item.rect;
  32722. delta = rect[xyDim] - lastPos;
  32723. if (delta < 0) {
  32724. // shiftForward(i, len, -delta);
  32725. rect[xyDim] -= delta;
  32726. item.label[xyDim] -= delta;
  32727. adjusted = true;
  32728. }
  32729. var shift = Math.max(-delta, 0);
  32730. totalShifts += shift;
  32731. lastPos = rect[xyDim] + rect[sizeDim];
  32732. }
  32733. if (totalShifts > 0 && balanceShift) {
  32734. // Shift back to make the distribution more equally.
  32735. shiftList(-totalShifts / len, 0, len);
  32736. }
  32737. // TODO bleedMargin?
  32738. var first = list[0];
  32739. var last = list[len - 1];
  32740. var minGap;
  32741. var maxGap;
  32742. updateMinMaxGap();
  32743. // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  32744. minGap < 0 && squeezeGaps(-minGap, 0.8);
  32745. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  32746. updateMinMaxGap();
  32747. takeBoundsGap(minGap, maxGap, 1);
  32748. takeBoundsGap(maxGap, minGap, -1);
  32749. // Handle bailout when there is not enough space.
  32750. updateMinMaxGap();
  32751. if (minGap < 0) {
  32752. squeezeWhenBailout(-minGap);
  32753. }
  32754. if (maxGap < 0) {
  32755. squeezeWhenBailout(maxGap);
  32756. }
  32757. function updateMinMaxGap() {
  32758. minGap = first.rect[xyDim] - minBound;
  32759. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  32760. }
  32761. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  32762. if (gapThisBound < 0) {
  32763. // Move from other gap if can.
  32764. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  32765. if (moveFromMaxGap > 0) {
  32766. shiftList(moveFromMaxGap * moveDir, 0, len);
  32767. var remained = moveFromMaxGap + gapThisBound;
  32768. if (remained < 0) {
  32769. squeezeGaps(-remained * moveDir, 1);
  32770. }
  32771. } else {
  32772. squeezeGaps(-gapThisBound * moveDir, 1);
  32773. }
  32774. }
  32775. }
  32776. function shiftList(delta, start, end) {
  32777. if (delta !== 0) {
  32778. adjusted = true;
  32779. }
  32780. for (var i = start; i < end; i++) {
  32781. var item = list[i];
  32782. var rect = item.rect;
  32783. rect[xyDim] += delta;
  32784. item.label[xyDim] += delta;
  32785. }
  32786. }
  32787. // Squeeze gaps if the labels exceed margin.
  32788. function squeezeGaps(delta, maxSqeezePercent) {
  32789. var gaps = [];
  32790. var totalGaps = 0;
  32791. for (var i = 1; i < len; i++) {
  32792. var prevItemRect = list[i - 1].rect;
  32793. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  32794. gaps.push(gap);
  32795. totalGaps += gap;
  32796. }
  32797. if (!totalGaps) {
  32798. return;
  32799. }
  32800. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  32801. if (delta > 0) {
  32802. for (var i = 0; i < len - 1; i++) {
  32803. // Distribute the shift delta to all gaps.
  32804. var movement = gaps[i] * squeezePercent;
  32805. // Forward
  32806. shiftList(movement, 0, i + 1);
  32807. }
  32808. } else {
  32809. // Backward
  32810. for (var i = len - 1; i > 0; i--) {
  32811. // Distribute the shift delta to all gaps.
  32812. var movement = gaps[i - 1] * squeezePercent;
  32813. shiftList(-movement, i, len);
  32814. }
  32815. }
  32816. }
  32817. /**
  32818. * Squeeze to allow overlap if there is no more space available.
  32819. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  32820. */
  32821. function squeezeWhenBailout(delta) {
  32822. var dir = delta < 0 ? -1 : 1;
  32823. delta = Math.abs(delta);
  32824. var moveForEachLabel = Math.ceil(delta / (len - 1));
  32825. for (var i = 0; i < len - 1; i++) {
  32826. if (dir > 0) {
  32827. // Forward
  32828. shiftList(moveForEachLabel, 0, i + 1);
  32829. } else {
  32830. // Backward
  32831. shiftList(-moveForEachLabel, len - i - 1, len);
  32832. }
  32833. delta -= moveForEachLabel;
  32834. if (delta <= 0) {
  32835. return;
  32836. }
  32837. }
  32838. }
  32839. return adjusted;
  32840. }
  32841. /**
  32842. * Adjust labels on y direction to avoid overlap.
  32843. */
  32844. function shiftLayoutOnY(list, topBound, bottomBound,
  32845. // If average the shifts on all labels and add them to 0
  32846. balanceShift) {
  32847. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  32848. }
  32849. function hideOverlap(labelList) {
  32850. var displayedLabels = [];
  32851. // TODO, render overflow visible first, put in the displayedLabels.
  32852. labelList.sort(function (a, b) {
  32853. return b.priority - a.priority;
  32854. });
  32855. var globalRect = new BoundingRect(0, 0, 0, 0);
  32856. function hideEl(el) {
  32857. if (!el.ignore) {
  32858. // Show on emphasis.
  32859. var emphasisState = el.ensureState('emphasis');
  32860. if (emphasisState.ignore == null) {
  32861. emphasisState.ignore = false;
  32862. }
  32863. }
  32864. el.ignore = true;
  32865. }
  32866. for (var i = 0; i < labelList.length; i++) {
  32867. var labelItem = labelList[i];
  32868. var isAxisAligned = labelItem.axisAligned;
  32869. var localRect = labelItem.localRect;
  32870. var transform = labelItem.transform;
  32871. var label = labelItem.label;
  32872. var labelLine = labelItem.labelLine;
  32873. globalRect.copy(labelItem.rect);
  32874. // Add a threshold because layout may be aligned precisely.
  32875. globalRect.width -= 0.1;
  32876. globalRect.height -= 0.1;
  32877. globalRect.x += 0.05;
  32878. globalRect.y += 0.05;
  32879. var obb = labelItem.obb;
  32880. var overlapped = false;
  32881. for (var j = 0; j < displayedLabels.length; j++) {
  32882. var existsTextCfg = displayedLabels[j];
  32883. // Fast rejection.
  32884. if (!globalRect.intersect(existsTextCfg.rect)) {
  32885. continue;
  32886. }
  32887. if (isAxisAligned && existsTextCfg.axisAligned) {
  32888. // Is overlapped
  32889. overlapped = true;
  32890. break;
  32891. }
  32892. if (!existsTextCfg.obb) {
  32893. // If self is not axis aligned. But other is.
  32894. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  32895. }
  32896. if (!obb) {
  32897. // If self is axis aligned. But other is not.
  32898. obb = new OrientedBoundingRect(localRect, transform);
  32899. }
  32900. if (obb.intersect(existsTextCfg.obb)) {
  32901. overlapped = true;
  32902. break;
  32903. }
  32904. }
  32905. // TODO Callback to determine if this overlap should be handled?
  32906. if (overlapped) {
  32907. hideEl(label);
  32908. labelLine && hideEl(labelLine);
  32909. } else {
  32910. label.attr('ignore', labelItem.defaultAttr.ignore);
  32911. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  32912. displayedLabels.push(labelItem);
  32913. }
  32914. }
  32915. }
  32916. function createDom(id, painter, dpr) {
  32917. var newDom = platformApi.createCanvas();
  32918. var width = painter.getWidth();
  32919. var height = painter.getHeight();
  32920. var newDomStyle = newDom.style;
  32921. if (newDomStyle) {
  32922. newDomStyle.position = 'absolute';
  32923. newDomStyle.left = '0';
  32924. newDomStyle.top = '0';
  32925. newDomStyle.width = width + 'px';
  32926. newDomStyle.height = height + 'px';
  32927. newDom.setAttribute('data-zr-dom-id', id);
  32928. }
  32929. newDom.width = width * dpr;
  32930. newDom.height = height * dpr;
  32931. return newDom;
  32932. }
  32933. var Layer = (function (_super) {
  32934. __extends(Layer, _super);
  32935. function Layer(id, painter, dpr) {
  32936. var _this = _super.call(this) || this;
  32937. _this.motionBlur = false;
  32938. _this.lastFrameAlpha = 0.7;
  32939. _this.dpr = 1;
  32940. _this.virtual = false;
  32941. _this.config = {};
  32942. _this.incremental = false;
  32943. _this.zlevel = 0;
  32944. _this.maxRepaintRectCount = 5;
  32945. _this.__dirty = true;
  32946. _this.__firstTimePaint = true;
  32947. _this.__used = false;
  32948. _this.__drawIndex = 0;
  32949. _this.__startIndex = 0;
  32950. _this.__endIndex = 0;
  32951. _this.__prevStartIndex = null;
  32952. _this.__prevEndIndex = null;
  32953. var dom;
  32954. dpr = dpr || devicePixelRatio;
  32955. if (typeof id === 'string') {
  32956. dom = createDom(id, painter, dpr);
  32957. }
  32958. else if (isObject(id)) {
  32959. dom = id;
  32960. id = dom.id;
  32961. }
  32962. _this.id = id;
  32963. _this.dom = dom;
  32964. var domStyle = dom.style;
  32965. if (domStyle) {
  32966. disableUserSelect(dom);
  32967. dom.onselectstart = function () { return false; };
  32968. domStyle.padding = '0';
  32969. domStyle.margin = '0';
  32970. domStyle.borderWidth = '0';
  32971. }
  32972. _this.painter = painter;
  32973. _this.dpr = dpr;
  32974. return _this;
  32975. }
  32976. Layer.prototype.getElementCount = function () {
  32977. return this.__endIndex - this.__startIndex;
  32978. };
  32979. Layer.prototype.afterBrush = function () {
  32980. this.__prevStartIndex = this.__startIndex;
  32981. this.__prevEndIndex = this.__endIndex;
  32982. };
  32983. Layer.prototype.initContext = function () {
  32984. this.ctx = this.dom.getContext('2d');
  32985. this.ctx.dpr = this.dpr;
  32986. };
  32987. Layer.prototype.setUnpainted = function () {
  32988. this.__firstTimePaint = true;
  32989. };
  32990. Layer.prototype.createBackBuffer = function () {
  32991. var dpr = this.dpr;
  32992. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  32993. this.ctxBack = this.domBack.getContext('2d');
  32994. if (dpr !== 1) {
  32995. this.ctxBack.scale(dpr, dpr);
  32996. }
  32997. };
  32998. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  32999. if (this.__firstTimePaint) {
  33000. this.__firstTimePaint = false;
  33001. return null;
  33002. }
  33003. var mergedRepaintRects = [];
  33004. var maxRepaintRectCount = this.maxRepaintRectCount;
  33005. var full = false;
  33006. var pendingRect = new BoundingRect(0, 0, 0, 0);
  33007. function addRectToMergePool(rect) {
  33008. if (!rect.isFinite() || rect.isZero()) {
  33009. return;
  33010. }
  33011. if (mergedRepaintRects.length === 0) {
  33012. var boundingRect = new BoundingRect(0, 0, 0, 0);
  33013. boundingRect.copy(rect);
  33014. mergedRepaintRects.push(boundingRect);
  33015. }
  33016. else {
  33017. var isMerged = false;
  33018. var minDeltaArea = Infinity;
  33019. var bestRectToMergeIdx = 0;
  33020. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  33021. var mergedRect = mergedRepaintRects[i];
  33022. if (mergedRect.intersect(rect)) {
  33023. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  33024. pendingRect_1.copy(mergedRect);
  33025. pendingRect_1.union(rect);
  33026. mergedRepaintRects[i] = pendingRect_1;
  33027. isMerged = true;
  33028. break;
  33029. }
  33030. else if (full) {
  33031. pendingRect.copy(rect);
  33032. pendingRect.union(mergedRect);
  33033. var aArea = rect.width * rect.height;
  33034. var bArea = mergedRect.width * mergedRect.height;
  33035. var pendingArea = pendingRect.width * pendingRect.height;
  33036. var deltaArea = pendingArea - aArea - bArea;
  33037. if (deltaArea < minDeltaArea) {
  33038. minDeltaArea = deltaArea;
  33039. bestRectToMergeIdx = i;
  33040. }
  33041. }
  33042. }
  33043. if (full) {
  33044. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  33045. isMerged = true;
  33046. }
  33047. if (!isMerged) {
  33048. var boundingRect = new BoundingRect(0, 0, 0, 0);
  33049. boundingRect.copy(rect);
  33050. mergedRepaintRects.push(boundingRect);
  33051. }
  33052. if (!full) {
  33053. full = mergedRepaintRects.length >= maxRepaintRectCount;
  33054. }
  33055. }
  33056. }
  33057. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  33058. var el = displayList[i];
  33059. if (el) {
  33060. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  33061. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  33062. ? el.getPrevPaintRect()
  33063. : null;
  33064. if (prevRect) {
  33065. addRectToMergePool(prevRect);
  33066. }
  33067. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  33068. ? el.getPaintRect()
  33069. : null;
  33070. if (curRect) {
  33071. addRectToMergePool(curRect);
  33072. }
  33073. }
  33074. }
  33075. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  33076. var el = prevList[i];
  33077. var shouldPaint = el && el.shouldBePainted(viewWidth, viewHeight, true, true);
  33078. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  33079. var prevRect = el.getPrevPaintRect();
  33080. if (prevRect) {
  33081. addRectToMergePool(prevRect);
  33082. }
  33083. }
  33084. }
  33085. var hasIntersections;
  33086. do {
  33087. hasIntersections = false;
  33088. for (var i = 0; i < mergedRepaintRects.length;) {
  33089. if (mergedRepaintRects[i].isZero()) {
  33090. mergedRepaintRects.splice(i, 1);
  33091. continue;
  33092. }
  33093. for (var j = i + 1; j < mergedRepaintRects.length;) {
  33094. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  33095. hasIntersections = true;
  33096. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  33097. mergedRepaintRects.splice(j, 1);
  33098. }
  33099. else {
  33100. j++;
  33101. }
  33102. }
  33103. i++;
  33104. }
  33105. } while (hasIntersections);
  33106. this._paintRects = mergedRepaintRects;
  33107. return mergedRepaintRects;
  33108. };
  33109. Layer.prototype.debugGetPaintRects = function () {
  33110. return (this._paintRects || []).slice();
  33111. };
  33112. Layer.prototype.resize = function (width, height) {
  33113. var dpr = this.dpr;
  33114. var dom = this.dom;
  33115. var domStyle = dom.style;
  33116. var domBack = this.domBack;
  33117. if (domStyle) {
  33118. domStyle.width = width + 'px';
  33119. domStyle.height = height + 'px';
  33120. }
  33121. dom.width = width * dpr;
  33122. dom.height = height * dpr;
  33123. if (domBack) {
  33124. domBack.width = width * dpr;
  33125. domBack.height = height * dpr;
  33126. if (dpr !== 1) {
  33127. this.ctxBack.scale(dpr, dpr);
  33128. }
  33129. }
  33130. };
  33131. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  33132. var dom = this.dom;
  33133. var ctx = this.ctx;
  33134. var width = dom.width;
  33135. var height = dom.height;
  33136. clearColor = clearColor || this.clearColor;
  33137. var haveMotionBLur = this.motionBlur && !clearAll;
  33138. var lastFrameAlpha = this.lastFrameAlpha;
  33139. var dpr = this.dpr;
  33140. var self = this;
  33141. if (haveMotionBLur) {
  33142. if (!this.domBack) {
  33143. this.createBackBuffer();
  33144. }
  33145. this.ctxBack.globalCompositeOperation = 'copy';
  33146. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  33147. }
  33148. var domBack = this.domBack;
  33149. function doClear(x, y, width, height) {
  33150. ctx.clearRect(x, y, width, height);
  33151. if (clearColor && clearColor !== 'transparent') {
  33152. var clearColorGradientOrPattern = void 0;
  33153. if (isGradientObject(clearColor)) {
  33154. var shouldCache = clearColor.global || (clearColor.__width === width
  33155. && clearColor.__height === height);
  33156. clearColorGradientOrPattern = shouldCache
  33157. && clearColor.__canvasGradient
  33158. || getCanvasGradient(ctx, clearColor, {
  33159. x: 0,
  33160. y: 0,
  33161. width: width,
  33162. height: height
  33163. });
  33164. clearColor.__canvasGradient = clearColorGradientOrPattern;
  33165. clearColor.__width = width;
  33166. clearColor.__height = height;
  33167. }
  33168. else if (isImagePatternObject(clearColor)) {
  33169. clearColor.scaleX = clearColor.scaleX || dpr;
  33170. clearColor.scaleY = clearColor.scaleY || dpr;
  33171. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  33172. dirty: function () {
  33173. self.setUnpainted();
  33174. self.painter.refresh();
  33175. }
  33176. });
  33177. }
  33178. ctx.save();
  33179. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  33180. ctx.fillRect(x, y, width, height);
  33181. ctx.restore();
  33182. }
  33183. if (haveMotionBLur) {
  33184. ctx.save();
  33185. ctx.globalAlpha = lastFrameAlpha;
  33186. ctx.drawImage(domBack, x, y, width, height);
  33187. ctx.restore();
  33188. }
  33189. }
  33190. if (!repaintRects || haveMotionBLur) {
  33191. doClear(0, 0, width, height);
  33192. }
  33193. else if (repaintRects.length) {
  33194. each(repaintRects, function (rect) {
  33195. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  33196. });
  33197. }
  33198. };
  33199. return Layer;
  33200. }(Eventful));
  33201. var HOVER_LAYER_ZLEVEL = 1e5;
  33202. var CANVAS_ZLEVEL = 314159;
  33203. var EL_AFTER_INCREMENTAL_INC = 0.01;
  33204. var INCREMENTAL_INC = 0.001;
  33205. function isLayerValid(layer) {
  33206. if (!layer) {
  33207. return false;
  33208. }
  33209. if (layer.__builtin__) {
  33210. return true;
  33211. }
  33212. if (typeof (layer.resize) !== 'function'
  33213. || typeof (layer.refresh) !== 'function') {
  33214. return false;
  33215. }
  33216. return true;
  33217. }
  33218. function createRoot(width, height) {
  33219. var domRoot = document.createElement('div');
  33220. domRoot.style.cssText = [
  33221. 'position:relative',
  33222. 'width:' + width + 'px',
  33223. 'height:' + height + 'px',
  33224. 'padding:0',
  33225. 'margin:0',
  33226. 'border-width:0'
  33227. ].join(';') + ';';
  33228. return domRoot;
  33229. }
  33230. var CanvasPainter = (function () {
  33231. function CanvasPainter(root, storage, opts, id) {
  33232. this.type = 'canvas';
  33233. this._zlevelList = [];
  33234. this._prevDisplayList = [];
  33235. this._layers = {};
  33236. this._layerConfig = {};
  33237. this._needsManuallyCompositing = false;
  33238. this.type = 'canvas';
  33239. var singleCanvas = !root.nodeName
  33240. || root.nodeName.toUpperCase() === 'CANVAS';
  33241. this._opts = opts = extend({}, opts || {});
  33242. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  33243. this._singleCanvas = singleCanvas;
  33244. this.root = root;
  33245. var rootStyle = root.style;
  33246. if (rootStyle) {
  33247. disableUserSelect(root);
  33248. root.innerHTML = '';
  33249. }
  33250. this.storage = storage;
  33251. var zlevelList = this._zlevelList;
  33252. this._prevDisplayList = [];
  33253. var layers = this._layers;
  33254. if (!singleCanvas) {
  33255. this._width = getSize(root, 0, opts);
  33256. this._height = getSize(root, 1, opts);
  33257. var domRoot = this._domRoot = createRoot(this._width, this._height);
  33258. root.appendChild(domRoot);
  33259. }
  33260. else {
  33261. var rootCanvas = root;
  33262. var width = rootCanvas.width;
  33263. var height = rootCanvas.height;
  33264. if (opts.width != null) {
  33265. width = opts.width;
  33266. }
  33267. if (opts.height != null) {
  33268. height = opts.height;
  33269. }
  33270. this.dpr = opts.devicePixelRatio || 1;
  33271. rootCanvas.width = width * this.dpr;
  33272. rootCanvas.height = height * this.dpr;
  33273. this._width = width;
  33274. this._height = height;
  33275. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  33276. mainLayer.__builtin__ = true;
  33277. mainLayer.initContext();
  33278. layers[CANVAS_ZLEVEL] = mainLayer;
  33279. mainLayer.zlevel = CANVAS_ZLEVEL;
  33280. zlevelList.push(CANVAS_ZLEVEL);
  33281. this._domRoot = root;
  33282. }
  33283. }
  33284. CanvasPainter.prototype.getType = function () {
  33285. return 'canvas';
  33286. };
  33287. CanvasPainter.prototype.isSingleCanvas = function () {
  33288. return this._singleCanvas;
  33289. };
  33290. CanvasPainter.prototype.getViewportRoot = function () {
  33291. return this._domRoot;
  33292. };
  33293. CanvasPainter.prototype.getViewportRootOffset = function () {
  33294. var viewportRoot = this.getViewportRoot();
  33295. if (viewportRoot) {
  33296. return {
  33297. offsetLeft: viewportRoot.offsetLeft || 0,
  33298. offsetTop: viewportRoot.offsetTop || 0
  33299. };
  33300. }
  33301. };
  33302. CanvasPainter.prototype.refresh = function (paintAll) {
  33303. var list = this.storage.getDisplayList(true);
  33304. var prevList = this._prevDisplayList;
  33305. var zlevelList = this._zlevelList;
  33306. this._redrawId = Math.random();
  33307. this._paintList(list, prevList, paintAll, this._redrawId);
  33308. for (var i = 0; i < zlevelList.length; i++) {
  33309. var z = zlevelList[i];
  33310. var layer = this._layers[z];
  33311. if (!layer.__builtin__ && layer.refresh) {
  33312. var clearColor = i === 0 ? this._backgroundColor : null;
  33313. layer.refresh(clearColor);
  33314. }
  33315. }
  33316. if (this._opts.useDirtyRect) {
  33317. this._prevDisplayList = list.slice();
  33318. }
  33319. return this;
  33320. };
  33321. CanvasPainter.prototype.refreshHover = function () {
  33322. this._paintHoverList(this.storage.getDisplayList(false));
  33323. };
  33324. CanvasPainter.prototype._paintHoverList = function (list) {
  33325. var len = list.length;
  33326. var hoverLayer = this._hoverlayer;
  33327. hoverLayer && hoverLayer.clear();
  33328. if (!len) {
  33329. return;
  33330. }
  33331. var scope = {
  33332. inHover: true,
  33333. viewWidth: this._width,
  33334. viewHeight: this._height
  33335. };
  33336. var ctx;
  33337. for (var i = 0; i < len; i++) {
  33338. var el = list[i];
  33339. if (el.__inHover) {
  33340. if (!hoverLayer) {
  33341. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  33342. }
  33343. if (!ctx) {
  33344. ctx = hoverLayer.ctx;
  33345. ctx.save();
  33346. }
  33347. brush(ctx, el, scope, i === len - 1);
  33348. }
  33349. }
  33350. if (ctx) {
  33351. ctx.restore();
  33352. }
  33353. };
  33354. CanvasPainter.prototype.getHoverLayer = function () {
  33355. return this.getLayer(HOVER_LAYER_ZLEVEL);
  33356. };
  33357. CanvasPainter.prototype.paintOne = function (ctx, el) {
  33358. brushSingle(ctx, el);
  33359. };
  33360. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  33361. if (this._redrawId !== redrawId) {
  33362. return;
  33363. }
  33364. paintAll = paintAll || false;
  33365. this._updateLayerStatus(list);
  33366. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  33367. if (this._needsManuallyCompositing) {
  33368. this._compositeManually();
  33369. }
  33370. if (needsRefreshHover) {
  33371. this._paintHoverList(list);
  33372. }
  33373. if (!finished) {
  33374. var self_1 = this;
  33375. requestAnimationFrame$1(function () {
  33376. self_1._paintList(list, prevList, paintAll, redrawId);
  33377. });
  33378. }
  33379. else {
  33380. this.eachLayer(function (layer) {
  33381. layer.afterBrush && layer.afterBrush();
  33382. });
  33383. }
  33384. };
  33385. CanvasPainter.prototype._compositeManually = function () {
  33386. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  33387. var width = this._domRoot.width;
  33388. var height = this._domRoot.height;
  33389. ctx.clearRect(0, 0, width, height);
  33390. this.eachBuiltinLayer(function (layer) {
  33391. if (layer.virtual) {
  33392. ctx.drawImage(layer.dom, 0, 0, width, height);
  33393. }
  33394. });
  33395. };
  33396. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  33397. var _this = this;
  33398. var layerList = [];
  33399. var useDirtyRect = this._opts.useDirtyRect;
  33400. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  33401. var zlevel = this._zlevelList[zi];
  33402. var layer = this._layers[zlevel];
  33403. if (layer.__builtin__
  33404. && layer !== this._hoverlayer
  33405. && (layer.__dirty || paintAll)) {
  33406. layerList.push(layer);
  33407. }
  33408. }
  33409. var finished = true;
  33410. var needsRefreshHover = false;
  33411. var _loop_1 = function (k) {
  33412. var layer = layerList[k];
  33413. var ctx = layer.ctx;
  33414. var repaintRects = useDirtyRect
  33415. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  33416. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  33417. var useTimer = !paintAll && layer.incremental && Date.now;
  33418. var startTime = useTimer && Date.now();
  33419. var clearColor = layer.zlevel === this_1._zlevelList[0]
  33420. ? this_1._backgroundColor : null;
  33421. if (layer.__startIndex === layer.__endIndex) {
  33422. layer.clear(false, clearColor, repaintRects);
  33423. }
  33424. else if (start === layer.__startIndex) {
  33425. var firstEl = list[start];
  33426. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  33427. layer.clear(false, clearColor, repaintRects);
  33428. }
  33429. }
  33430. if (start === -1) {
  33431. console.error('For some unknown reason. drawIndex is -1');
  33432. start = layer.__startIndex;
  33433. }
  33434. var i;
  33435. var repaint = function (repaintRect) {
  33436. var scope = {
  33437. inHover: false,
  33438. allClipped: false,
  33439. prevEl: null,
  33440. viewWidth: _this._width,
  33441. viewHeight: _this._height
  33442. };
  33443. for (i = start; i < layer.__endIndex; i++) {
  33444. var el = list[i];
  33445. if (el.__inHover) {
  33446. needsRefreshHover = true;
  33447. }
  33448. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  33449. if (useTimer) {
  33450. var dTime = Date.now() - startTime;
  33451. if (dTime > 15) {
  33452. break;
  33453. }
  33454. }
  33455. }
  33456. if (scope.prevElClipPaths) {
  33457. ctx.restore();
  33458. }
  33459. };
  33460. if (repaintRects) {
  33461. if (repaintRects.length === 0) {
  33462. i = layer.__endIndex;
  33463. }
  33464. else {
  33465. var dpr = this_1.dpr;
  33466. for (var r = 0; r < repaintRects.length; ++r) {
  33467. var rect = repaintRects[r];
  33468. ctx.save();
  33469. ctx.beginPath();
  33470. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  33471. ctx.clip();
  33472. repaint(rect);
  33473. ctx.restore();
  33474. }
  33475. }
  33476. }
  33477. else {
  33478. ctx.save();
  33479. repaint();
  33480. ctx.restore();
  33481. }
  33482. layer.__drawIndex = i;
  33483. if (layer.__drawIndex < layer.__endIndex) {
  33484. finished = false;
  33485. }
  33486. };
  33487. var this_1 = this;
  33488. for (var k = 0; k < layerList.length; k++) {
  33489. _loop_1(k);
  33490. }
  33491. if (env.wxa) {
  33492. each(this._layers, function (layer) {
  33493. if (layer && layer.ctx && layer.ctx.draw) {
  33494. layer.ctx.draw();
  33495. }
  33496. });
  33497. }
  33498. return {
  33499. finished: finished,
  33500. needsRefreshHover: needsRefreshHover
  33501. };
  33502. };
  33503. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  33504. var ctx = currentLayer.ctx;
  33505. if (useDirtyRect) {
  33506. var paintRect = el.getPaintRect();
  33507. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  33508. brush(ctx, el, scope, isLast);
  33509. el.setPrevPaintRect(paintRect);
  33510. }
  33511. }
  33512. else {
  33513. brush(ctx, el, scope, isLast);
  33514. }
  33515. };
  33516. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  33517. if (this._singleCanvas && !this._needsManuallyCompositing) {
  33518. zlevel = CANVAS_ZLEVEL;
  33519. }
  33520. var layer = this._layers[zlevel];
  33521. if (!layer) {
  33522. layer = new Layer('zr_' + zlevel, this, this.dpr);
  33523. layer.zlevel = zlevel;
  33524. layer.__builtin__ = true;
  33525. if (this._layerConfig[zlevel]) {
  33526. merge(layer, this._layerConfig[zlevel], true);
  33527. }
  33528. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  33529. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  33530. }
  33531. if (virtual) {
  33532. layer.virtual = virtual;
  33533. }
  33534. this.insertLayer(zlevel, layer);
  33535. layer.initContext();
  33536. }
  33537. return layer;
  33538. };
  33539. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  33540. var layersMap = this._layers;
  33541. var zlevelList = this._zlevelList;
  33542. var len = zlevelList.length;
  33543. var domRoot = this._domRoot;
  33544. var prevLayer = null;
  33545. var i = -1;
  33546. if (layersMap[zlevel]) {
  33547. if ("development" !== 'production') {
  33548. logError('ZLevel ' + zlevel + ' has been used already');
  33549. }
  33550. return;
  33551. }
  33552. if (!isLayerValid(layer)) {
  33553. if ("development" !== 'production') {
  33554. logError('Layer of zlevel ' + zlevel + ' is not valid');
  33555. }
  33556. return;
  33557. }
  33558. if (len > 0 && zlevel > zlevelList[0]) {
  33559. for (i = 0; i < len - 1; i++) {
  33560. if (zlevelList[i] < zlevel
  33561. && zlevelList[i + 1] > zlevel) {
  33562. break;
  33563. }
  33564. }
  33565. prevLayer = layersMap[zlevelList[i]];
  33566. }
  33567. zlevelList.splice(i + 1, 0, zlevel);
  33568. layersMap[zlevel] = layer;
  33569. if (!layer.virtual) {
  33570. if (prevLayer) {
  33571. var prevDom = prevLayer.dom;
  33572. if (prevDom.nextSibling) {
  33573. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  33574. }
  33575. else {
  33576. domRoot.appendChild(layer.dom);
  33577. }
  33578. }
  33579. else {
  33580. if (domRoot.firstChild) {
  33581. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  33582. }
  33583. else {
  33584. domRoot.appendChild(layer.dom);
  33585. }
  33586. }
  33587. }
  33588. layer.painter || (layer.painter = this);
  33589. };
  33590. CanvasPainter.prototype.eachLayer = function (cb, context) {
  33591. var zlevelList = this._zlevelList;
  33592. for (var i = 0; i < zlevelList.length; i++) {
  33593. var z = zlevelList[i];
  33594. cb.call(context, this._layers[z], z);
  33595. }
  33596. };
  33597. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  33598. var zlevelList = this._zlevelList;
  33599. for (var i = 0; i < zlevelList.length; i++) {
  33600. var z = zlevelList[i];
  33601. var layer = this._layers[z];
  33602. if (layer.__builtin__) {
  33603. cb.call(context, layer, z);
  33604. }
  33605. }
  33606. };
  33607. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  33608. var zlevelList = this._zlevelList;
  33609. for (var i = 0; i < zlevelList.length; i++) {
  33610. var z = zlevelList[i];
  33611. var layer = this._layers[z];
  33612. if (!layer.__builtin__) {
  33613. cb.call(context, layer, z);
  33614. }
  33615. }
  33616. };
  33617. CanvasPainter.prototype.getLayers = function () {
  33618. return this._layers;
  33619. };
  33620. CanvasPainter.prototype._updateLayerStatus = function (list) {
  33621. this.eachBuiltinLayer(function (layer, z) {
  33622. layer.__dirty = layer.__used = false;
  33623. });
  33624. function updatePrevLayer(idx) {
  33625. if (prevLayer) {
  33626. if (prevLayer.__endIndex !== idx) {
  33627. prevLayer.__dirty = true;
  33628. }
  33629. prevLayer.__endIndex = idx;
  33630. }
  33631. }
  33632. if (this._singleCanvas) {
  33633. for (var i_1 = 1; i_1 < list.length; i_1++) {
  33634. var el = list[i_1];
  33635. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  33636. this._needsManuallyCompositing = true;
  33637. break;
  33638. }
  33639. }
  33640. }
  33641. var prevLayer = null;
  33642. var incrementalLayerCount = 0;
  33643. var prevZlevel;
  33644. var i;
  33645. for (i = 0; i < list.length; i++) {
  33646. var el = list[i];
  33647. var zlevel = el.zlevel;
  33648. var layer = void 0;
  33649. if (prevZlevel !== zlevel) {
  33650. prevZlevel = zlevel;
  33651. incrementalLayerCount = 0;
  33652. }
  33653. if (el.incremental) {
  33654. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  33655. layer.incremental = true;
  33656. incrementalLayerCount = 1;
  33657. }
  33658. else {
  33659. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  33660. }
  33661. if (!layer.__builtin__) {
  33662. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  33663. }
  33664. if (layer !== prevLayer) {
  33665. layer.__used = true;
  33666. if (layer.__startIndex !== i) {
  33667. layer.__dirty = true;
  33668. }
  33669. layer.__startIndex = i;
  33670. if (!layer.incremental) {
  33671. layer.__drawIndex = i;
  33672. }
  33673. else {
  33674. layer.__drawIndex = -1;
  33675. }
  33676. updatePrevLayer(i);
  33677. prevLayer = layer;
  33678. }
  33679. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  33680. layer.__dirty = true;
  33681. if (layer.incremental && layer.__drawIndex < 0) {
  33682. layer.__drawIndex = i;
  33683. }
  33684. }
  33685. }
  33686. updatePrevLayer(i);
  33687. this.eachBuiltinLayer(function (layer, z) {
  33688. if (!layer.__used && layer.getElementCount() > 0) {
  33689. layer.__dirty = true;
  33690. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  33691. }
  33692. if (layer.__dirty && layer.__drawIndex < 0) {
  33693. layer.__drawIndex = layer.__startIndex;
  33694. }
  33695. });
  33696. };
  33697. CanvasPainter.prototype.clear = function () {
  33698. this.eachBuiltinLayer(this._clearLayer);
  33699. return this;
  33700. };
  33701. CanvasPainter.prototype._clearLayer = function (layer) {
  33702. layer.clear();
  33703. };
  33704. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  33705. this._backgroundColor = backgroundColor;
  33706. each(this._layers, function (layer) {
  33707. layer.setUnpainted();
  33708. });
  33709. };
  33710. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  33711. if (config) {
  33712. var layerConfig = this._layerConfig;
  33713. if (!layerConfig[zlevel]) {
  33714. layerConfig[zlevel] = config;
  33715. }
  33716. else {
  33717. merge(layerConfig[zlevel], config, true);
  33718. }
  33719. for (var i = 0; i < this._zlevelList.length; i++) {
  33720. var _zlevel = this._zlevelList[i];
  33721. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  33722. var layer = this._layers[_zlevel];
  33723. merge(layer, layerConfig[zlevel], true);
  33724. }
  33725. }
  33726. }
  33727. };
  33728. CanvasPainter.prototype.delLayer = function (zlevel) {
  33729. var layers = this._layers;
  33730. var zlevelList = this._zlevelList;
  33731. var layer = layers[zlevel];
  33732. if (!layer) {
  33733. return;
  33734. }
  33735. layer.dom.parentNode.removeChild(layer.dom);
  33736. delete layers[zlevel];
  33737. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  33738. };
  33739. CanvasPainter.prototype.resize = function (width, height) {
  33740. if (!this._domRoot.style) {
  33741. if (width == null || height == null) {
  33742. return;
  33743. }
  33744. this._width = width;
  33745. this._height = height;
  33746. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  33747. }
  33748. else {
  33749. var domRoot = this._domRoot;
  33750. domRoot.style.display = 'none';
  33751. var opts = this._opts;
  33752. var root = this.root;
  33753. width != null && (opts.width = width);
  33754. height != null && (opts.height = height);
  33755. width = getSize(root, 0, opts);
  33756. height = getSize(root, 1, opts);
  33757. domRoot.style.display = '';
  33758. if (this._width !== width || height !== this._height) {
  33759. domRoot.style.width = width + 'px';
  33760. domRoot.style.height = height + 'px';
  33761. for (var id in this._layers) {
  33762. if (this._layers.hasOwnProperty(id)) {
  33763. this._layers[id].resize(width, height);
  33764. }
  33765. }
  33766. this.refresh(true);
  33767. }
  33768. this._width = width;
  33769. this._height = height;
  33770. }
  33771. return this;
  33772. };
  33773. CanvasPainter.prototype.clearLayer = function (zlevel) {
  33774. var layer = this._layers[zlevel];
  33775. if (layer) {
  33776. layer.clear();
  33777. }
  33778. };
  33779. CanvasPainter.prototype.dispose = function () {
  33780. this.root.innerHTML = '';
  33781. this.root =
  33782. this.storage =
  33783. this._domRoot =
  33784. this._layers = null;
  33785. };
  33786. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  33787. opts = opts || {};
  33788. if (this._singleCanvas && !this._compositeManually) {
  33789. return this._layers[CANVAS_ZLEVEL].dom;
  33790. }
  33791. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  33792. imageLayer.initContext();
  33793. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  33794. var ctx = imageLayer.ctx;
  33795. if (opts.pixelRatio <= this.dpr) {
  33796. this.refresh();
  33797. var width_1 = imageLayer.dom.width;
  33798. var height_1 = imageLayer.dom.height;
  33799. this.eachLayer(function (layer) {
  33800. if (layer.__builtin__) {
  33801. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  33802. }
  33803. else if (layer.renderToCanvas) {
  33804. ctx.save();
  33805. layer.renderToCanvas(ctx);
  33806. ctx.restore();
  33807. }
  33808. });
  33809. }
  33810. else {
  33811. var scope = {
  33812. inHover: false,
  33813. viewWidth: this._width,
  33814. viewHeight: this._height
  33815. };
  33816. var displayList = this.storage.getDisplayList(true);
  33817. for (var i = 0, len = displayList.length; i < len; i++) {
  33818. var el = displayList[i];
  33819. brush(ctx, el, scope, i === len - 1);
  33820. }
  33821. }
  33822. return imageLayer.dom;
  33823. };
  33824. CanvasPainter.prototype.getWidth = function () {
  33825. return this._width;
  33826. };
  33827. CanvasPainter.prototype.getHeight = function () {
  33828. return this._height;
  33829. };
  33830. return CanvasPainter;
  33831. }());
  33832. function install(registers) {
  33833. registers.registerPainter('canvas', CanvasPainter);
  33834. }
  33835. var LineSeriesModel = /** @class */function (_super) {
  33836. __extends(LineSeriesModel, _super);
  33837. function LineSeriesModel() {
  33838. var _this = _super !== null && _super.apply(this, arguments) || this;
  33839. _this.type = LineSeriesModel.type;
  33840. _this.hasSymbolVisual = true;
  33841. return _this;
  33842. }
  33843. LineSeriesModel.prototype.getInitialData = function (option) {
  33844. if ("development" !== 'production') {
  33845. var coordSys = option.coordinateSystem;
  33846. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  33847. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  33848. }
  33849. }
  33850. return createSeriesData(null, this, {
  33851. useEncodeDefaulter: true
  33852. });
  33853. };
  33854. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  33855. var group = new Group();
  33856. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  33857. group.add(line);
  33858. line.setStyle(opt.lineStyle);
  33859. var visualType = this.getData().getVisual('symbol');
  33860. var visualRotate = this.getData().getVisual('symbolRotate');
  33861. var symbolType = visualType === 'none' ? 'circle' : visualType;
  33862. // Symbol size is 80% when there is a line
  33863. var size = opt.itemHeight * 0.8;
  33864. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  33865. group.add(symbol);
  33866. symbol.setStyle(opt.itemStyle);
  33867. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  33868. symbol.rotation = symbolRotate * Math.PI / 180;
  33869. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  33870. if (symbolType.indexOf('empty') > -1) {
  33871. symbol.style.stroke = symbol.style.fill;
  33872. symbol.style.fill = '#fff';
  33873. symbol.style.lineWidth = 2;
  33874. }
  33875. return group;
  33876. };
  33877. LineSeriesModel.type = 'series.line';
  33878. LineSeriesModel.dependencies = ['grid', 'polar'];
  33879. LineSeriesModel.defaultOption = {
  33880. // zlevel: 0,
  33881. z: 3,
  33882. coordinateSystem: 'cartesian2d',
  33883. legendHoverLink: true,
  33884. clip: true,
  33885. label: {
  33886. position: 'top'
  33887. },
  33888. // itemStyle: {
  33889. // },
  33890. endLabel: {
  33891. show: false,
  33892. valueAnimation: true,
  33893. distance: 8
  33894. },
  33895. lineStyle: {
  33896. width: 2,
  33897. type: 'solid'
  33898. },
  33899. emphasis: {
  33900. scale: true
  33901. },
  33902. // areaStyle: {
  33903. // origin of areaStyle. Valid values:
  33904. // `'auto'/null/undefined`: from axisLine to data
  33905. // `'start'`: from min to data
  33906. // `'end'`: from data to max
  33907. // origin: 'auto'
  33908. // },
  33909. // false, 'start', 'end', 'middle'
  33910. step: false,
  33911. // Disabled if step is true
  33912. smooth: false,
  33913. smoothMonotone: null,
  33914. symbol: 'emptyCircle',
  33915. symbolSize: 4,
  33916. symbolRotate: null,
  33917. showSymbol: true,
  33918. // `false`: follow the label interval strategy.
  33919. // `true`: show all symbols.
  33920. // `'auto'`: If possible, show all symbols, otherwise
  33921. // follow the label interval strategy.
  33922. showAllSymbol: 'auto',
  33923. // Whether to connect break point.
  33924. connectNulls: false,
  33925. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  33926. sampling: 'none',
  33927. animationEasing: 'linear',
  33928. // Disable progressive
  33929. progressive: 0,
  33930. hoverLayerThreshold: Infinity,
  33931. universalTransition: {
  33932. divideShape: 'clone'
  33933. },
  33934. triggerLineEvent: false
  33935. };
  33936. return LineSeriesModel;
  33937. }(SeriesModel);
  33938. /**
  33939. * @return label string. Not null/undefined
  33940. */
  33941. function getDefaultLabel(data, dataIndex) {
  33942. var labelDims = data.mapDimensionsAll('defaultedLabel');
  33943. var len = labelDims.length;
  33944. // Simple optimization (in lots of cases, label dims length is 1)
  33945. if (len === 1) {
  33946. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  33947. return rawVal != null ? rawVal + '' : null;
  33948. } else if (len) {
  33949. var vals = [];
  33950. for (var i = 0; i < labelDims.length; i++) {
  33951. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  33952. }
  33953. return vals.join(' ');
  33954. }
  33955. }
  33956. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  33957. var labelDims = data.mapDimensionsAll('defaultedLabel');
  33958. if (!isArray(interpolatedValue)) {
  33959. return interpolatedValue + '';
  33960. }
  33961. var vals = [];
  33962. for (var i = 0; i < labelDims.length; i++) {
  33963. var dimIndex = data.getDimensionIndex(labelDims[i]);
  33964. if (dimIndex >= 0) {
  33965. vals.push(interpolatedValue[dimIndex]);
  33966. }
  33967. }
  33968. return vals.join(' ');
  33969. }
  33970. var Symbol = /** @class */function (_super) {
  33971. __extends(Symbol, _super);
  33972. function Symbol(data, idx, seriesScope, opts) {
  33973. var _this = _super.call(this) || this;
  33974. _this.updateData(data, idx, seriesScope, opts);
  33975. return _this;
  33976. }
  33977. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  33978. // Remove paths created before
  33979. this.removeAll();
  33980. // let symbolPath = createSymbol(
  33981. // symbolType, -0.5, -0.5, 1, 1, color
  33982. // );
  33983. // If width/height are set too small (e.g., set to 1) on ios10
  33984. // and macOS Sierra, a circle stroke become a rect, no matter what
  33985. // the scale is set. So we set width/height as 2. See #4150.
  33986. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  33987. symbolPath.attr({
  33988. z2: 100,
  33989. culling: true,
  33990. scaleX: symbolSize[0] / 2,
  33991. scaleY: symbolSize[1] / 2
  33992. });
  33993. // Rewrite drift method
  33994. symbolPath.drift = driftSymbol;
  33995. this._symbolType = symbolType;
  33996. this.add(symbolPath);
  33997. };
  33998. /**
  33999. * Stop animation
  34000. * @param {boolean} toLastFrame
  34001. */
  34002. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  34003. this.childAt(0).stopAnimation(null, toLastFrame);
  34004. };
  34005. Symbol.prototype.getSymbolType = function () {
  34006. return this._symbolType;
  34007. };
  34008. /**
  34009. * FIXME:
  34010. * Caution: This method breaks the encapsulation of this module,
  34011. * but it indeed brings convenience. So do not use the method
  34012. * unless you detailedly know all the implements of `Symbol`,
  34013. * especially animation.
  34014. *
  34015. * Get symbol path element.
  34016. */
  34017. Symbol.prototype.getSymbolPath = function () {
  34018. return this.childAt(0);
  34019. };
  34020. /**
  34021. * Highlight symbol
  34022. */
  34023. Symbol.prototype.highlight = function () {
  34024. enterEmphasis(this.childAt(0));
  34025. };
  34026. /**
  34027. * Downplay symbol
  34028. */
  34029. Symbol.prototype.downplay = function () {
  34030. leaveEmphasis(this.childAt(0));
  34031. };
  34032. /**
  34033. * @param {number} zlevel
  34034. * @param {number} z
  34035. */
  34036. Symbol.prototype.setZ = function (zlevel, z) {
  34037. var symbolPath = this.childAt(0);
  34038. symbolPath.zlevel = zlevel;
  34039. symbolPath.z = z;
  34040. };
  34041. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  34042. var symbolPath = this.childAt(0);
  34043. symbolPath.draggable = draggable;
  34044. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  34045. };
  34046. /**
  34047. * Update symbol properties
  34048. */
  34049. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  34050. this.silent = false;
  34051. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  34052. var seriesModel = data.hostModel;
  34053. var symbolSize = Symbol.getSymbolSize(data, idx);
  34054. var isInit = symbolType !== this._symbolType;
  34055. var disableAnimation = opts && opts.disableAnimation;
  34056. if (isInit) {
  34057. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  34058. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  34059. } else {
  34060. var symbolPath = this.childAt(0);
  34061. symbolPath.silent = false;
  34062. var target = {
  34063. scaleX: symbolSize[0] / 2,
  34064. scaleY: symbolSize[1] / 2
  34065. };
  34066. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  34067. saveOldStyle(symbolPath);
  34068. }
  34069. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  34070. if (isInit) {
  34071. var symbolPath = this.childAt(0);
  34072. if (!disableAnimation) {
  34073. var target = {
  34074. scaleX: this._sizeX,
  34075. scaleY: this._sizeY,
  34076. style: {
  34077. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  34078. opacity: symbolPath.style.opacity
  34079. }
  34080. };
  34081. symbolPath.scaleX = symbolPath.scaleY = 0;
  34082. symbolPath.style.opacity = 0;
  34083. initProps(symbolPath, target, seriesModel, idx);
  34084. }
  34085. }
  34086. if (disableAnimation) {
  34087. // Must stop leave transition manually if don't call initProps or updateProps.
  34088. this.childAt(0).stopAnimation('leave');
  34089. }
  34090. };
  34091. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  34092. var symbolPath = this.childAt(0);
  34093. var seriesModel = data.hostModel;
  34094. var emphasisItemStyle;
  34095. var blurItemStyle;
  34096. var selectItemStyle;
  34097. var focus;
  34098. var blurScope;
  34099. var emphasisDisabled;
  34100. var labelStatesModels;
  34101. var hoverScale;
  34102. var cursorStyle;
  34103. if (seriesScope) {
  34104. emphasisItemStyle = seriesScope.emphasisItemStyle;
  34105. blurItemStyle = seriesScope.blurItemStyle;
  34106. selectItemStyle = seriesScope.selectItemStyle;
  34107. focus = seriesScope.focus;
  34108. blurScope = seriesScope.blurScope;
  34109. labelStatesModels = seriesScope.labelStatesModels;
  34110. hoverScale = seriesScope.hoverScale;
  34111. cursorStyle = seriesScope.cursorStyle;
  34112. emphasisDisabled = seriesScope.emphasisDisabled;
  34113. }
  34114. if (!seriesScope || data.hasItemOption) {
  34115. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  34116. var emphasisModel = itemModel.getModel('emphasis');
  34117. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  34118. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  34119. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  34120. focus = emphasisModel.get('focus');
  34121. blurScope = emphasisModel.get('blurScope');
  34122. emphasisDisabled = emphasisModel.get('disabled');
  34123. labelStatesModels = getLabelStatesModels(itemModel);
  34124. hoverScale = emphasisModel.getShallow('scale');
  34125. cursorStyle = itemModel.getShallow('cursor');
  34126. }
  34127. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  34128. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  34129. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  34130. if (symbolOffset) {
  34131. symbolPath.x = symbolOffset[0];
  34132. symbolPath.y = symbolOffset[1];
  34133. }
  34134. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  34135. var symbolStyle = data.getItemVisual(idx, 'style');
  34136. var visualColor = symbolStyle.fill;
  34137. if (symbolPath instanceof ZRImage) {
  34138. var pathStyle = symbolPath.style;
  34139. symbolPath.useStyle(extend({
  34140. // TODO other properties like x, y ?
  34141. image: pathStyle.image,
  34142. x: pathStyle.x,
  34143. y: pathStyle.y,
  34144. width: pathStyle.width,
  34145. height: pathStyle.height
  34146. }, symbolStyle));
  34147. } else {
  34148. if (symbolPath.__isEmptyBrush) {
  34149. // fill and stroke will be swapped if it's empty.
  34150. // So we cloned a new style to avoid it affecting the original style in visual storage.
  34151. // TODO Better implementation. No empty logic!
  34152. symbolPath.useStyle(extend({}, symbolStyle));
  34153. } else {
  34154. symbolPath.useStyle(symbolStyle);
  34155. }
  34156. // Disable decal because symbol scale will been applied on the decal.
  34157. symbolPath.style.decal = null;
  34158. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  34159. symbolPath.style.strokeNoScale = true;
  34160. }
  34161. var liftZ = data.getItemVisual(idx, 'liftZ');
  34162. var z2Origin = this._z2;
  34163. if (liftZ != null) {
  34164. if (z2Origin == null) {
  34165. this._z2 = symbolPath.z2;
  34166. symbolPath.z2 += liftZ;
  34167. }
  34168. } else if (z2Origin != null) {
  34169. symbolPath.z2 = z2Origin;
  34170. this._z2 = null;
  34171. }
  34172. var useNameLabel = opts && opts.useNameLabel;
  34173. setLabelStyle(symbolPath, labelStatesModels, {
  34174. labelFetcher: seriesModel,
  34175. labelDataIndex: idx,
  34176. defaultText: getLabelDefaultText,
  34177. inheritColor: visualColor,
  34178. defaultOpacity: symbolStyle.opacity
  34179. });
  34180. // Do not execute util needed.
  34181. function getLabelDefaultText(idx) {
  34182. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  34183. }
  34184. this._sizeX = symbolSize[0] / 2;
  34185. this._sizeY = symbolSize[1] / 2;
  34186. var emphasisState = symbolPath.ensureState('emphasis');
  34187. emphasisState.style = emphasisItemStyle;
  34188. symbolPath.ensureState('select').style = selectItemStyle;
  34189. symbolPath.ensureState('blur').style = blurItemStyle;
  34190. // null / undefined / true means to use default strategy.
  34191. // 0 / false / negative number / NaN / Infinity means no scale.
  34192. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY)
  34193. // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  34194. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1;
  34195. // always set scale to allow resetting
  34196. emphasisState.scaleX = this._sizeX * scaleRatio;
  34197. emphasisState.scaleY = this._sizeY * scaleRatio;
  34198. this.setSymbolScale(1);
  34199. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  34200. };
  34201. Symbol.prototype.setSymbolScale = function (scale) {
  34202. this.scaleX = this.scaleY = scale;
  34203. };
  34204. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  34205. var symbolPath = this.childAt(0);
  34206. var dataIndex = getECData(this).dataIndex;
  34207. var animationOpt = opt && opt.animation;
  34208. // Avoid mistaken hover when fading out
  34209. this.silent = symbolPath.silent = true;
  34210. // Not show text when animating
  34211. if (opt && opt.fadeLabel) {
  34212. var textContent = symbolPath.getTextContent();
  34213. if (textContent) {
  34214. removeElement(textContent, {
  34215. style: {
  34216. opacity: 0
  34217. }
  34218. }, seriesModel, {
  34219. dataIndex: dataIndex,
  34220. removeOpt: animationOpt,
  34221. cb: function () {
  34222. symbolPath.removeTextContent();
  34223. }
  34224. });
  34225. }
  34226. } else {
  34227. symbolPath.removeTextContent();
  34228. }
  34229. removeElement(symbolPath, {
  34230. style: {
  34231. opacity: 0
  34232. },
  34233. scaleX: 0,
  34234. scaleY: 0
  34235. }, seriesModel, {
  34236. dataIndex: dataIndex,
  34237. cb: cb,
  34238. removeOpt: animationOpt
  34239. });
  34240. };
  34241. Symbol.getSymbolSize = function (data, idx) {
  34242. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  34243. };
  34244. return Symbol;
  34245. }(Group);
  34246. function driftSymbol(dx, dy) {
  34247. this.parent.drift(dx, dy);
  34248. }
  34249. function symbolNeedsDraw(data, point, idx, opt) {
  34250. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx))
  34251. // We do not set clipShape on group, because it will cut part of
  34252. // the symbol element shape. We use the same clip shape here as
  34253. // the line clip.
  34254. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  34255. }
  34256. function normalizeUpdateOpt(opt) {
  34257. if (opt != null && !isObject(opt)) {
  34258. opt = {
  34259. isIgnore: opt
  34260. };
  34261. }
  34262. return opt || {};
  34263. }
  34264. function makeSeriesScope(data) {
  34265. var seriesModel = data.hostModel;
  34266. var emphasisModel = seriesModel.getModel('emphasis');
  34267. return {
  34268. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  34269. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  34270. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  34271. focus: emphasisModel.get('focus'),
  34272. blurScope: emphasisModel.get('blurScope'),
  34273. emphasisDisabled: emphasisModel.get('disabled'),
  34274. hoverScale: emphasisModel.get('scale'),
  34275. labelStatesModels: getLabelStatesModels(seriesModel),
  34276. cursorStyle: seriesModel.get('cursor')
  34277. };
  34278. }
  34279. var SymbolDraw = /** @class */function () {
  34280. function SymbolDraw(SymbolCtor) {
  34281. this.group = new Group();
  34282. this._SymbolCtor = SymbolCtor || Symbol;
  34283. }
  34284. /**
  34285. * Update symbols draw by new data
  34286. */
  34287. SymbolDraw.prototype.updateData = function (data, opt) {
  34288. // Remove progressive els.
  34289. this._progressiveEls = null;
  34290. opt = normalizeUpdateOpt(opt);
  34291. var group = this.group;
  34292. var seriesModel = data.hostModel;
  34293. var oldData = this._data;
  34294. var SymbolCtor = this._SymbolCtor;
  34295. var disableAnimation = opt.disableAnimation;
  34296. var seriesScope = makeSeriesScope(data);
  34297. var symbolUpdateOpt = {
  34298. disableAnimation: disableAnimation
  34299. };
  34300. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  34301. return data.getItemLayout(idx);
  34302. };
  34303. // There is no oldLineData only when first rendering or switching from
  34304. // stream mode to normal mode, where previous elements should be removed.
  34305. if (!oldData) {
  34306. group.removeAll();
  34307. }
  34308. data.diff(oldData).add(function (newIdx) {
  34309. var point = getSymbolPoint(newIdx);
  34310. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  34311. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  34312. symbolEl.setPosition(point);
  34313. data.setItemGraphicEl(newIdx, symbolEl);
  34314. group.add(symbolEl);
  34315. }
  34316. }).update(function (newIdx, oldIdx) {
  34317. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  34318. var point = getSymbolPoint(newIdx);
  34319. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  34320. group.remove(symbolEl);
  34321. return;
  34322. }
  34323. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  34324. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  34325. if (!symbolEl
  34326. // Create a new if symbol type changed.
  34327. || oldSymbolType && oldSymbolType !== newSymbolType) {
  34328. group.remove(symbolEl);
  34329. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  34330. symbolEl.setPosition(point);
  34331. } else {
  34332. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  34333. var target = {
  34334. x: point[0],
  34335. y: point[1]
  34336. };
  34337. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  34338. }
  34339. // Add back
  34340. group.add(symbolEl);
  34341. data.setItemGraphicEl(newIdx, symbolEl);
  34342. }).remove(function (oldIdx) {
  34343. var el = oldData.getItemGraphicEl(oldIdx);
  34344. el && el.fadeOut(function () {
  34345. group.remove(el);
  34346. }, seriesModel);
  34347. }).execute();
  34348. this._getSymbolPoint = getSymbolPoint;
  34349. this._data = data;
  34350. };
  34351. SymbolDraw.prototype.updateLayout = function () {
  34352. var _this = this;
  34353. var data = this._data;
  34354. if (data) {
  34355. // Not use animation
  34356. data.eachItemGraphicEl(function (el, idx) {
  34357. var point = _this._getSymbolPoint(idx);
  34358. el.setPosition(point);
  34359. el.markRedraw();
  34360. });
  34361. }
  34362. };
  34363. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  34364. this._seriesScope = makeSeriesScope(data);
  34365. this._data = null;
  34366. this.group.removeAll();
  34367. };
  34368. /**
  34369. * Update symbols draw by new data
  34370. */
  34371. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  34372. // Clear
  34373. this._progressiveEls = [];
  34374. opt = normalizeUpdateOpt(opt);
  34375. function updateIncrementalAndHover(el) {
  34376. if (!el.isGroup) {
  34377. el.incremental = true;
  34378. el.ensureState('emphasis').hoverLayer = true;
  34379. }
  34380. }
  34381. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  34382. var point = data.getItemLayout(idx);
  34383. if (symbolNeedsDraw(data, point, idx, opt)) {
  34384. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  34385. el.traverse(updateIncrementalAndHover);
  34386. el.setPosition(point);
  34387. this.group.add(el);
  34388. data.setItemGraphicEl(idx, el);
  34389. this._progressiveEls.push(el);
  34390. }
  34391. }
  34392. };
  34393. SymbolDraw.prototype.eachRendered = function (cb) {
  34394. traverseElements(this._progressiveEls || this.group, cb);
  34395. };
  34396. SymbolDraw.prototype.remove = function (enableAnimation) {
  34397. var group = this.group;
  34398. var data = this._data;
  34399. // Incremental model do not have this._data.
  34400. if (data && enableAnimation) {
  34401. data.eachItemGraphicEl(function (el) {
  34402. el.fadeOut(function () {
  34403. group.remove(el);
  34404. }, data.hostModel);
  34405. });
  34406. } else {
  34407. group.removeAll();
  34408. }
  34409. };
  34410. return SymbolDraw;
  34411. }();
  34412. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  34413. var baseAxis = coordSys.getBaseAxis();
  34414. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34415. var valueStart = getValueStart(valueAxis, valueOrigin);
  34416. var baseAxisDim = baseAxis.dim;
  34417. var valueAxisDim = valueAxis.dim;
  34418. var valueDim = data.mapDimension(valueAxisDim);
  34419. var baseDim = data.mapDimension(baseAxisDim);
  34420. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  34421. var dims = map(coordSys.dimensions, function (coordDim) {
  34422. return data.mapDimension(coordDim);
  34423. });
  34424. var stacked = false;
  34425. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34426. if (isDimensionStacked(data, dims[0] /* , dims[1] */)) {
  34427. // jshint ignore:line
  34428. stacked = true;
  34429. dims[0] = stackResultDim;
  34430. }
  34431. if (isDimensionStacked(data, dims[1] /* , dims[0] */)) {
  34432. // jshint ignore:line
  34433. stacked = true;
  34434. dims[1] = stackResultDim;
  34435. }
  34436. return {
  34437. dataDimsForPoint: dims,
  34438. valueStart: valueStart,
  34439. valueAxisDim: valueAxisDim,
  34440. baseAxisDim: baseAxisDim,
  34441. stacked: !!stacked,
  34442. valueDim: valueDim,
  34443. baseDim: baseDim,
  34444. baseDataOffset: baseDataOffset,
  34445. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  34446. };
  34447. }
  34448. function getValueStart(valueAxis, valueOrigin) {
  34449. var valueStart = 0;
  34450. var extent = valueAxis.scale.getExtent();
  34451. if (valueOrigin === 'start') {
  34452. valueStart = extent[0];
  34453. } else if (valueOrigin === 'end') {
  34454. valueStart = extent[1];
  34455. }
  34456. // If origin is specified as a number, use it as
  34457. // valueStart directly
  34458. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  34459. valueStart = valueOrigin;
  34460. }
  34461. // auto
  34462. else {
  34463. // Both positive
  34464. if (extent[0] > 0) {
  34465. valueStart = extent[0];
  34466. }
  34467. // Both negative
  34468. else if (extent[1] < 0) {
  34469. valueStart = extent[1];
  34470. }
  34471. // If is one positive, and one negative, onZero shall be true
  34472. }
  34473. return valueStart;
  34474. }
  34475. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  34476. var value = NaN;
  34477. if (dataCoordInfo.stacked) {
  34478. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  34479. }
  34480. if (isNaN(value)) {
  34481. value = dataCoordInfo.valueStart;
  34482. }
  34483. var baseDataOffset = dataCoordInfo.baseDataOffset;
  34484. var stackedData = [];
  34485. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  34486. stackedData[1 - baseDataOffset] = value;
  34487. return coordSys.dataToPoint(stackedData);
  34488. }
  34489. function diffData(oldData, newData) {
  34490. var diffResult = [];
  34491. newData.diff(oldData).add(function (idx) {
  34492. diffResult.push({
  34493. cmd: '+',
  34494. idx: idx
  34495. });
  34496. }).update(function (newIdx, oldIdx) {
  34497. diffResult.push({
  34498. cmd: '=',
  34499. idx: oldIdx,
  34500. idx1: newIdx
  34501. });
  34502. }).remove(function (idx) {
  34503. diffResult.push({
  34504. cmd: '-',
  34505. idx: idx
  34506. });
  34507. }).execute();
  34508. return diffResult;
  34509. }
  34510. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  34511. var diff = diffData(oldData, newData);
  34512. // let newIdList = newData.mapArray(newData.getId);
  34513. // let oldIdList = oldData.mapArray(oldData.getId);
  34514. // convertToIntId(newIdList, oldIdList);
  34515. // // FIXME One data ?
  34516. // diff = arrayDiff(oldIdList, newIdList);
  34517. var currPoints = [];
  34518. var nextPoints = [];
  34519. // Points for stacking base line
  34520. var currStackedPoints = [];
  34521. var nextStackedPoints = [];
  34522. var status = [];
  34523. var sortedIndices = [];
  34524. var rawIndices = [];
  34525. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  34526. // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  34527. var oldPoints = oldData.getLayout('points') || [];
  34528. var newPoints = newData.getLayout('points') || [];
  34529. for (var i = 0; i < diff.length; i++) {
  34530. var diffItem = diff[i];
  34531. var pointAdded = true;
  34532. var oldIdx2 = void 0;
  34533. var newIdx2 = void 0;
  34534. // FIXME, animation is not so perfect when dataZoom window moves fast
  34535. // Which is in case remvoing or add more than one data in the tail or head
  34536. switch (diffItem.cmd) {
  34537. case '=':
  34538. oldIdx2 = diffItem.idx * 2;
  34539. newIdx2 = diffItem.idx1 * 2;
  34540. var currentX = oldPoints[oldIdx2];
  34541. var currentY = oldPoints[oldIdx2 + 1];
  34542. var nextX = newPoints[newIdx2];
  34543. var nextY = newPoints[newIdx2 + 1];
  34544. // If previous data is NaN, use next point directly
  34545. if (isNaN(currentX) || isNaN(currentY)) {
  34546. currentX = nextX;
  34547. currentY = nextY;
  34548. }
  34549. currPoints.push(currentX, currentY);
  34550. nextPoints.push(nextX, nextY);
  34551. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  34552. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  34553. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  34554. break;
  34555. case '+':
  34556. var newIdx = diffItem.idx;
  34557. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  34558. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  34559. newIdx2 = newIdx * 2;
  34560. currPoints.push(oldPt[0], oldPt[1]);
  34561. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  34562. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  34563. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  34564. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  34565. rawIndices.push(newData.getRawIndex(newIdx));
  34566. break;
  34567. case '-':
  34568. pointAdded = false;
  34569. }
  34570. // Original indices
  34571. if (pointAdded) {
  34572. status.push(diffItem);
  34573. sortedIndices.push(sortedIndices.length);
  34574. }
  34575. }
  34576. // Diff result may be crossed if all items are changed
  34577. // Sort by data index
  34578. sortedIndices.sort(function (a, b) {
  34579. return rawIndices[a] - rawIndices[b];
  34580. });
  34581. var len = currPoints.length;
  34582. var sortedCurrPoints = createFloat32Array(len);
  34583. var sortedNextPoints = createFloat32Array(len);
  34584. var sortedCurrStackedPoints = createFloat32Array(len);
  34585. var sortedNextStackedPoints = createFloat32Array(len);
  34586. var sortedStatus = [];
  34587. for (var i = 0; i < sortedIndices.length; i++) {
  34588. var idx = sortedIndices[i];
  34589. var i2 = i * 2;
  34590. var idx2 = idx * 2;
  34591. sortedCurrPoints[i2] = currPoints[idx2];
  34592. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  34593. sortedNextPoints[i2] = nextPoints[idx2];
  34594. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  34595. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  34596. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  34597. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  34598. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  34599. sortedStatus[i] = status[idx];
  34600. }
  34601. return {
  34602. current: sortedCurrPoints,
  34603. next: sortedNextPoints,
  34604. stackedOnCurrent: sortedCurrStackedPoints,
  34605. stackedOnNext: sortedNextStackedPoints,
  34606. status: sortedStatus
  34607. };
  34608. }
  34609. var mathMin$5 = Math.min;
  34610. var mathMax$5 = Math.max;
  34611. function isPointNull(x, y) {
  34612. return isNaN(x) || isNaN(y);
  34613. }
  34614. /**
  34615. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  34616. * situations. This should be used when points are non-monotone neither in x or
  34617. * y dimension.
  34618. */
  34619. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  34620. var prevX;
  34621. var prevY;
  34622. var cpx0;
  34623. var cpy0;
  34624. var cpx1;
  34625. var cpy1;
  34626. var idx = start;
  34627. var k = 0;
  34628. for (; k < segLen; k++) {
  34629. var x = points[idx * 2];
  34630. var y = points[idx * 2 + 1];
  34631. if (idx >= allLen || idx < 0) {
  34632. break;
  34633. }
  34634. if (isPointNull(x, y)) {
  34635. if (connectNulls) {
  34636. idx += dir;
  34637. continue;
  34638. }
  34639. break;
  34640. }
  34641. if (idx === start) {
  34642. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  34643. cpx0 = x;
  34644. cpy0 = y;
  34645. } else {
  34646. var dx = x - prevX;
  34647. var dy = y - prevY;
  34648. // Ignore tiny segment.
  34649. if (dx * dx + dy * dy < 0.5) {
  34650. idx += dir;
  34651. continue;
  34652. }
  34653. if (smooth > 0) {
  34654. var nextIdx = idx + dir;
  34655. var nextX = points[nextIdx * 2];
  34656. var nextY = points[nextIdx * 2 + 1];
  34657. // Ignore duplicate point
  34658. while (nextX === x && nextY === y && k < segLen) {
  34659. k++;
  34660. nextIdx += dir;
  34661. idx += dir;
  34662. nextX = points[nextIdx * 2];
  34663. nextY = points[nextIdx * 2 + 1];
  34664. x = points[idx * 2];
  34665. y = points[idx * 2 + 1];
  34666. dx = x - prevX;
  34667. dy = y - prevY;
  34668. }
  34669. var tmpK = k + 1;
  34670. if (connectNulls) {
  34671. // Find next point not null
  34672. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  34673. tmpK++;
  34674. nextIdx += dir;
  34675. nextX = points[nextIdx * 2];
  34676. nextY = points[nextIdx * 2 + 1];
  34677. }
  34678. }
  34679. var ratioNextSeg = 0.5;
  34680. var vx = 0;
  34681. var vy = 0;
  34682. var nextCpx0 = void 0;
  34683. var nextCpy0 = void 0;
  34684. // Is last point
  34685. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  34686. cpx1 = x;
  34687. cpy1 = y;
  34688. } else {
  34689. vx = nextX - prevX;
  34690. vy = nextY - prevY;
  34691. var dx0 = x - prevX;
  34692. var dx1 = nextX - x;
  34693. var dy0 = y - prevY;
  34694. var dy1 = nextY - y;
  34695. var lenPrevSeg = void 0;
  34696. var lenNextSeg = void 0;
  34697. if (smoothMonotone === 'x') {
  34698. lenPrevSeg = Math.abs(dx0);
  34699. lenNextSeg = Math.abs(dx1);
  34700. var dir_1 = vx > 0 ? 1 : -1;
  34701. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  34702. cpy1 = y;
  34703. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  34704. nextCpy0 = y;
  34705. } else if (smoothMonotone === 'y') {
  34706. lenPrevSeg = Math.abs(dy0);
  34707. lenNextSeg = Math.abs(dy1);
  34708. var dir_2 = vy > 0 ? 1 : -1;
  34709. cpx1 = x;
  34710. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  34711. nextCpx0 = x;
  34712. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  34713. } else {
  34714. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  34715. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  34716. // Use ratio of seg length
  34717. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  34718. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  34719. cpy1 = y - vy * smooth * (1 - ratioNextSeg);
  34720. // cp0 of next segment
  34721. nextCpx0 = x + vx * smooth * ratioNextSeg;
  34722. nextCpy0 = y + vy * smooth * ratioNextSeg;
  34723. // Smooth constraint between point and next point.
  34724. // Avoid exceeding extreme after smoothing.
  34725. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  34726. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  34727. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  34728. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y));
  34729. // Reclaculate cp1 based on the adjusted cp0 of next seg.
  34730. vx = nextCpx0 - x;
  34731. vy = nextCpy0 - y;
  34732. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  34733. cpy1 = y - vy * lenPrevSeg / lenNextSeg;
  34734. // Smooth constraint between point and prev point.
  34735. // Avoid exceeding extreme after smoothing.
  34736. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  34737. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  34738. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  34739. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y));
  34740. // Adjust next cp0 again.
  34741. vx = x - cpx1;
  34742. vy = y - cpy1;
  34743. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  34744. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  34745. }
  34746. }
  34747. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  34748. cpx0 = nextCpx0;
  34749. cpy0 = nextCpy0;
  34750. } else {
  34751. ctx.lineTo(x, y);
  34752. }
  34753. }
  34754. prevX = x;
  34755. prevY = y;
  34756. idx += dir;
  34757. }
  34758. return k;
  34759. }
  34760. var ECPolylineShape = /** @class */function () {
  34761. function ECPolylineShape() {
  34762. this.smooth = 0;
  34763. this.smoothConstraint = true;
  34764. }
  34765. return ECPolylineShape;
  34766. }();
  34767. var ECPolyline = /** @class */function (_super) {
  34768. __extends(ECPolyline, _super);
  34769. function ECPolyline(opts) {
  34770. var _this = _super.call(this, opts) || this;
  34771. _this.type = 'ec-polyline';
  34772. return _this;
  34773. }
  34774. ECPolyline.prototype.getDefaultStyle = function () {
  34775. return {
  34776. stroke: '#000',
  34777. fill: null
  34778. };
  34779. };
  34780. ECPolyline.prototype.getDefaultShape = function () {
  34781. return new ECPolylineShape();
  34782. };
  34783. ECPolyline.prototype.buildPath = function (ctx, shape) {
  34784. var points = shape.points;
  34785. var i = 0;
  34786. var len = points.length / 2;
  34787. // const result = getBoundingBox(points, shape.smoothConstraint);
  34788. if (shape.connectNulls) {
  34789. // Must remove first and last null values avoid draw error in polygon
  34790. for (; len > 0; len--) {
  34791. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  34792. break;
  34793. }
  34794. }
  34795. for (; i < len; i++) {
  34796. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  34797. break;
  34798. }
  34799. }
  34800. }
  34801. while (i < len) {
  34802. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  34803. }
  34804. };
  34805. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  34806. if (!this.path) {
  34807. this.createPathProxy();
  34808. this.buildPath(this.path, this.shape);
  34809. }
  34810. var path = this.path;
  34811. var data = path.data;
  34812. var CMD = PathProxy.CMD;
  34813. var x0;
  34814. var y0;
  34815. var isDimX = dim === 'x';
  34816. var roots = [];
  34817. for (var i = 0; i < data.length;) {
  34818. var cmd = data[i++];
  34819. var x = void 0;
  34820. var y = void 0;
  34821. var x2 = void 0;
  34822. var y2 = void 0;
  34823. var x3 = void 0;
  34824. var y3 = void 0;
  34825. var t = void 0;
  34826. switch (cmd) {
  34827. case CMD.M:
  34828. x0 = data[i++];
  34829. y0 = data[i++];
  34830. break;
  34831. case CMD.L:
  34832. x = data[i++];
  34833. y = data[i++];
  34834. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  34835. if (t <= 1 && t >= 0) {
  34836. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  34837. return isDimX ? [xOrY, val] : [val, xOrY];
  34838. }
  34839. x0 = x;
  34840. y0 = y;
  34841. break;
  34842. case CMD.C:
  34843. x = data[i++];
  34844. y = data[i++];
  34845. x2 = data[i++];
  34846. y2 = data[i++];
  34847. x3 = data[i++];
  34848. y3 = data[i++];
  34849. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  34850. if (nRoot > 0) {
  34851. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  34852. var t_1 = roots[i_1];
  34853. if (t_1 <= 1 && t_1 >= 0) {
  34854. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  34855. return isDimX ? [xOrY, val] : [val, xOrY];
  34856. }
  34857. }
  34858. }
  34859. x0 = x3;
  34860. y0 = y3;
  34861. break;
  34862. }
  34863. }
  34864. };
  34865. return ECPolyline;
  34866. }(Path);
  34867. var ECPolygonShape = /** @class */function (_super) {
  34868. __extends(ECPolygonShape, _super);
  34869. function ECPolygonShape() {
  34870. return _super !== null && _super.apply(this, arguments) || this;
  34871. }
  34872. return ECPolygonShape;
  34873. }(ECPolylineShape);
  34874. var ECPolygon = /** @class */function (_super) {
  34875. __extends(ECPolygon, _super);
  34876. function ECPolygon(opts) {
  34877. var _this = _super.call(this, opts) || this;
  34878. _this.type = 'ec-polygon';
  34879. return _this;
  34880. }
  34881. ECPolygon.prototype.getDefaultShape = function () {
  34882. return new ECPolygonShape();
  34883. };
  34884. ECPolygon.prototype.buildPath = function (ctx, shape) {
  34885. var points = shape.points;
  34886. var stackedOnPoints = shape.stackedOnPoints;
  34887. var i = 0;
  34888. var len = points.length / 2;
  34889. var smoothMonotone = shape.smoothMonotone;
  34890. if (shape.connectNulls) {
  34891. // Must remove first and last null values avoid draw error in polygon
  34892. for (; len > 0; len--) {
  34893. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  34894. break;
  34895. }
  34896. }
  34897. for (; i < len; i++) {
  34898. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  34899. break;
  34900. }
  34901. }
  34902. }
  34903. while (i < len) {
  34904. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  34905. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  34906. i += k + 1;
  34907. ctx.closePath();
  34908. }
  34909. };
  34910. return ECPolygon;
  34911. }(Path);
  34912. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  34913. var rect = cartesian.getArea();
  34914. var x = rect.x;
  34915. var y = rect.y;
  34916. var width = rect.width;
  34917. var height = rect.height;
  34918. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2;
  34919. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  34920. x -= lineWidth / 2;
  34921. y -= lineWidth / 2;
  34922. width += lineWidth;
  34923. height += lineWidth;
  34924. // fix: https://github.com/apache/incubator-echarts/issues/11369
  34925. width = Math.ceil(width);
  34926. if (x !== Math.floor(x)) {
  34927. x = Math.floor(x);
  34928. // if no extra 1px on `width`, it will still be clipped since `x` is floored
  34929. width++;
  34930. }
  34931. var clipPath = new Rect({
  34932. shape: {
  34933. x: x,
  34934. y: y,
  34935. width: width,
  34936. height: height
  34937. }
  34938. });
  34939. if (hasAnimation) {
  34940. var baseAxis = cartesian.getBaseAxis();
  34941. var isHorizontal = baseAxis.isHorizontal();
  34942. var isAxisInversed = baseAxis.inverse;
  34943. if (isHorizontal) {
  34944. if (isAxisInversed) {
  34945. clipPath.shape.x += width;
  34946. }
  34947. clipPath.shape.width = 0;
  34948. } else {
  34949. if (!isAxisInversed) {
  34950. clipPath.shape.y += height;
  34951. }
  34952. clipPath.shape.height = 0;
  34953. }
  34954. var duringCb = isFunction(during) ? function (percent) {
  34955. during(percent, clipPath);
  34956. } : null;
  34957. initProps(clipPath, {
  34958. shape: {
  34959. width: width,
  34960. height: height,
  34961. x: x,
  34962. y: y
  34963. }
  34964. }, seriesModel, null, done, duringCb);
  34965. }
  34966. return clipPath;
  34967. }
  34968. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  34969. var sectorArea = polar.getArea();
  34970. // Avoid float number rounding error for symbol on the edge of axis extent.
  34971. var r0 = round(sectorArea.r0, 1);
  34972. var r = round(sectorArea.r, 1);
  34973. var clipPath = new Sector({
  34974. shape: {
  34975. cx: round(polar.cx, 1),
  34976. cy: round(polar.cy, 1),
  34977. r0: r0,
  34978. r: r,
  34979. startAngle: sectorArea.startAngle,
  34980. endAngle: sectorArea.endAngle,
  34981. clockwise: sectorArea.clockwise
  34982. }
  34983. });
  34984. if (hasAnimation) {
  34985. var isRadial = polar.getBaseAxis().dim === 'angle';
  34986. if (isRadial) {
  34987. clipPath.shape.endAngle = sectorArea.startAngle;
  34988. } else {
  34989. clipPath.shape.r = r0;
  34990. }
  34991. initProps(clipPath, {
  34992. shape: {
  34993. endAngle: sectorArea.endAngle,
  34994. r: r
  34995. }
  34996. }, seriesModel);
  34997. }
  34998. return clipPath;
  34999. }
  35000. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  35001. if (!coordSys) {
  35002. return null;
  35003. } else if (coordSys.type === 'polar') {
  35004. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  35005. } else if (coordSys.type === 'cartesian2d') {
  35006. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  35007. }
  35008. return null;
  35009. }
  35010. /*
  35011. * Licensed to the Apache Software Foundation (ASF) under one
  35012. * or more contributor license agreements. See the NOTICE file
  35013. * distributed with this work for additional information
  35014. * regarding copyright ownership. The ASF licenses this file
  35015. * to you under the Apache License, Version 2.0 (the
  35016. * "License"); you may not use this file except in compliance
  35017. * with the License. You may obtain a copy of the License at
  35018. *
  35019. * http://www.apache.org/licenses/LICENSE-2.0
  35020. *
  35021. * Unless required by applicable law or agreed to in writing,
  35022. * software distributed under the License is distributed on an
  35023. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35024. * KIND, either express or implied. See the License for the
  35025. * specific language governing permissions and limitations
  35026. * under the License.
  35027. */
  35028. /**
  35029. * AUTO-GENERATED FILE. DO NOT MODIFY.
  35030. */
  35031. /*
  35032. * Licensed to the Apache Software Foundation (ASF) under one
  35033. * or more contributor license agreements. See the NOTICE file
  35034. * distributed with this work for additional information
  35035. * regarding copyright ownership. The ASF licenses this file
  35036. * to you under the Apache License, Version 2.0 (the
  35037. * "License"); you may not use this file except in compliance
  35038. * with the License. You may obtain a copy of the License at
  35039. *
  35040. * http://www.apache.org/licenses/LICENSE-2.0
  35041. *
  35042. * Unless required by applicable law or agreed to in writing,
  35043. * software distributed under the License is distributed on an
  35044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35045. * KIND, either express or implied. See the License for the
  35046. * specific language governing permissions and limitations
  35047. * under the License.
  35048. */
  35049. function isCoordinateSystemType(coordSys, type) {
  35050. return coordSys.type === type;
  35051. }
  35052. function isPointsSame(points1, points2) {
  35053. if (points1.length !== points2.length) {
  35054. return;
  35055. }
  35056. for (var i = 0; i < points1.length; i++) {
  35057. if (points1[i] !== points2[i]) {
  35058. return;
  35059. }
  35060. }
  35061. return true;
  35062. }
  35063. function bboxFromPoints(points) {
  35064. var minX = Infinity;
  35065. var minY = Infinity;
  35066. var maxX = -Infinity;
  35067. var maxY = -Infinity;
  35068. for (var i = 0; i < points.length;) {
  35069. var x = points[i++];
  35070. var y = points[i++];
  35071. if (!isNaN(x)) {
  35072. minX = Math.min(x, minX);
  35073. maxX = Math.max(x, maxX);
  35074. }
  35075. if (!isNaN(y)) {
  35076. minY = Math.min(y, minY);
  35077. maxY = Math.max(y, maxY);
  35078. }
  35079. }
  35080. return [[minX, minY], [maxX, maxY]];
  35081. }
  35082. function getBoundingDiff(points1, points2) {
  35083. var _a = bboxFromPoints(points1),
  35084. min1 = _a[0],
  35085. max1 = _a[1];
  35086. var _b = bboxFromPoints(points2),
  35087. min2 = _b[0],
  35088. max2 = _b[1];
  35089. // Get a max value from each corner of two boundings.
  35090. 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]));
  35091. }
  35092. function getSmooth(smooth) {
  35093. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  35094. }
  35095. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  35096. if (!dataCoordInfo.valueDim) {
  35097. return [];
  35098. }
  35099. var len = data.count();
  35100. var points = createFloat32Array(len * 2);
  35101. for (var idx = 0; idx < len; idx++) {
  35102. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  35103. points[idx * 2] = pt[0];
  35104. points[idx * 2 + 1] = pt[1];
  35105. }
  35106. return points;
  35107. }
  35108. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  35109. var baseAxis = coordSys.getBaseAxis();
  35110. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  35111. var stepPoints = [];
  35112. var i = 0;
  35113. var stepPt = [];
  35114. var pt = [];
  35115. var nextPt = [];
  35116. var filteredPoints = [];
  35117. if (connectNulls) {
  35118. for (i = 0; i < points.length; i += 2) {
  35119. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  35120. filteredPoints.push(points[i], points[i + 1]);
  35121. }
  35122. }
  35123. points = filteredPoints;
  35124. }
  35125. for (i = 0; i < points.length - 2; i += 2) {
  35126. nextPt[0] = points[i + 2];
  35127. nextPt[1] = points[i + 3];
  35128. pt[0] = points[i];
  35129. pt[1] = points[i + 1];
  35130. stepPoints.push(pt[0], pt[1]);
  35131. switch (stepTurnAt) {
  35132. case 'end':
  35133. stepPt[baseIndex] = nextPt[baseIndex];
  35134. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  35135. stepPoints.push(stepPt[0], stepPt[1]);
  35136. break;
  35137. case 'middle':
  35138. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  35139. var stepPt2 = [];
  35140. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  35141. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  35142. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  35143. stepPoints.push(stepPt[0], stepPt[1]);
  35144. stepPoints.push(stepPt2[0], stepPt2[1]);
  35145. break;
  35146. default:
  35147. // default is start
  35148. stepPt[baseIndex] = pt[baseIndex];
  35149. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  35150. stepPoints.push(stepPt[0], stepPt[1]);
  35151. }
  35152. }
  35153. // Last points
  35154. stepPoints.push(points[i++], points[i++]);
  35155. return stepPoints;
  35156. }
  35157. /**
  35158. * Clip color stops to edge. Avoid creating too large gradients.
  35159. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  35160. *
  35161. * The stops has been sorted from small to large.
  35162. */
  35163. function clipColorStops(colorStops, maxSize) {
  35164. var newColorStops = [];
  35165. var len = colorStops.length;
  35166. // coord will always < 0 in prevOutOfRangeColorStop.
  35167. var prevOutOfRangeColorStop;
  35168. var prevInRangeColorStop;
  35169. function lerpStop(stop0, stop1, clippedCoord) {
  35170. var coord0 = stop0.coord;
  35171. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  35172. var color = lerp$1(p, [stop0.color, stop1.color]);
  35173. return {
  35174. coord: clippedCoord,
  35175. color: color
  35176. };
  35177. }
  35178. for (var i = 0; i < len; i++) {
  35179. var stop_1 = colorStops[i];
  35180. var coord = stop_1.coord;
  35181. if (coord < 0) {
  35182. prevOutOfRangeColorStop = stop_1;
  35183. } else if (coord > maxSize) {
  35184. if (prevInRangeColorStop) {
  35185. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  35186. } else if (prevOutOfRangeColorStop) {
  35187. // If there are two stops and coord range is between these two stops
  35188. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  35189. }
  35190. // All following stop will be out of range. So just ignore them.
  35191. break;
  35192. } else {
  35193. if (prevOutOfRangeColorStop) {
  35194. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0));
  35195. // Reset
  35196. prevOutOfRangeColorStop = null;
  35197. }
  35198. newColorStops.push(stop_1);
  35199. prevInRangeColorStop = stop_1;
  35200. }
  35201. }
  35202. return newColorStops;
  35203. }
  35204. function getVisualGradient(data, coordSys, api) {
  35205. var visualMetaList = data.getVisual('visualMeta');
  35206. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  35207. // When data.count() is 0, gradient range can not be calculated.
  35208. return;
  35209. }
  35210. if (coordSys.type !== 'cartesian2d') {
  35211. if ("development" !== 'production') {
  35212. console.warn('Visual map on line style is only supported on cartesian2d.');
  35213. }
  35214. return;
  35215. }
  35216. var coordDim;
  35217. var visualMeta;
  35218. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  35219. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  35220. coordDim = dimInfo && dimInfo.coordDim;
  35221. // Can only be x or y
  35222. if (coordDim === 'x' || coordDim === 'y') {
  35223. visualMeta = visualMetaList[i];
  35224. break;
  35225. }
  35226. }
  35227. if (!visualMeta) {
  35228. if ("development" !== 'production') {
  35229. console.warn('Visual map on line style only support x or y dimension.');
  35230. }
  35231. return;
  35232. }
  35233. // If the area to be rendered is bigger than area defined by LinearGradient,
  35234. // the canvas spec prescribes that the color of the first stop and the last
  35235. // stop should be used. But if two stops are added at offset 0, in effect
  35236. // browsers use the color of the second stop to render area outside
  35237. // LinearGradient. So we can only infinitesimally extend area defined in
  35238. // LinearGradient to render `outerColors`.
  35239. var axis = coordSys.getAxis(coordDim);
  35240. // dataToCoord mapping may not be linear, but must be monotonic.
  35241. var colorStops = map(visualMeta.stops, function (stop) {
  35242. // offset will be calculated later.
  35243. return {
  35244. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  35245. color: stop.color
  35246. };
  35247. });
  35248. var stopLen = colorStops.length;
  35249. var outerColors = visualMeta.outerColors.slice();
  35250. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  35251. colorStops.reverse();
  35252. outerColors.reverse();
  35253. }
  35254. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  35255. var inRangeStopLen = colorStopsInRange.length;
  35256. if (!inRangeStopLen && stopLen) {
  35257. // All stops are out of range. All will be the same color.
  35258. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  35259. }
  35260. var tinyExtent = 10; // Arbitrary value: 10px
  35261. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  35262. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  35263. var coordSpan = maxCoord - minCoord;
  35264. if (coordSpan < 1e-3) {
  35265. return 'transparent';
  35266. }
  35267. each(colorStopsInRange, function (stop) {
  35268. stop.offset = (stop.coord - minCoord) / coordSpan;
  35269. });
  35270. colorStopsInRange.push({
  35271. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  35272. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  35273. color: outerColors[1] || 'transparent'
  35274. });
  35275. colorStopsInRange.unshift({
  35276. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  35277. color: outerColors[0] || 'transparent'
  35278. });
  35279. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  35280. gradient[coordDim] = minCoord;
  35281. gradient[coordDim + '2'] = maxCoord;
  35282. return gradient;
  35283. }
  35284. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  35285. var showAllSymbol = seriesModel.get('showAllSymbol');
  35286. var isAuto = showAllSymbol === 'auto';
  35287. if (showAllSymbol && !isAuto) {
  35288. return;
  35289. }
  35290. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  35291. if (!categoryAxis) {
  35292. return;
  35293. }
  35294. // Note that category label interval strategy might bring some weird effect
  35295. // in some scenario: users may wonder why some of the symbols are not
  35296. // displayed. So we show all symbols as possible as we can.
  35297. if (isAuto
  35298. // Simplify the logic, do not determine label overlap here.
  35299. && canShowAllSymbolForCategory(categoryAxis, data)) {
  35300. return;
  35301. }
  35302. // Otherwise follow the label interval strategy on category axis.
  35303. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  35304. var labelMap = {};
  35305. each(categoryAxis.getViewLabels(), function (labelItem) {
  35306. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  35307. labelMap[ordinalNumber] = 1;
  35308. });
  35309. return function (dataIndex) {
  35310. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  35311. };
  35312. }
  35313. function canShowAllSymbolForCategory(categoryAxis, data) {
  35314. // In most cases, line is monotonous on category axis, and the label size
  35315. // is close with each other. So we check the symbol size and some of the
  35316. // label size alone with the category axis to estimate whether all symbol
  35317. // can be shown without overlap.
  35318. var axisExtent = categoryAxis.getExtent();
  35319. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  35320. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  35321. // Sampling some points, max 5.
  35322. var dataLen = data.count();
  35323. var step = Math.max(1, Math.round(dataLen / 5));
  35324. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  35325. if (Symbol.getSymbolSize(data, dataIndex
  35326. // Only for cartesian, where `isHorizontal` exists.
  35327. )[categoryAxis.isHorizontal() ? 1 : 0]
  35328. // Empirical number
  35329. * 1.5 > availSize) {
  35330. return false;
  35331. }
  35332. }
  35333. return true;
  35334. }
  35335. function isPointNull$1(x, y) {
  35336. return isNaN(x) || isNaN(y);
  35337. }
  35338. function getLastIndexNotNull(points) {
  35339. var len = points.length / 2;
  35340. for (; len > 0; len--) {
  35341. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  35342. break;
  35343. }
  35344. }
  35345. return len - 1;
  35346. }
  35347. function getPointAtIndex(points, idx) {
  35348. return [points[idx * 2], points[idx * 2 + 1]];
  35349. }
  35350. function getIndexRange(points, xOrY, dim) {
  35351. var len = points.length / 2;
  35352. var dimIdx = dim === 'x' ? 0 : 1;
  35353. var a;
  35354. var b;
  35355. var prevIndex = 0;
  35356. var nextIndex = -1;
  35357. for (var i = 0; i < len; i++) {
  35358. b = points[i * 2 + dimIdx];
  35359. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  35360. continue;
  35361. }
  35362. if (i === 0) {
  35363. a = b;
  35364. continue;
  35365. }
  35366. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  35367. nextIndex = i;
  35368. break;
  35369. }
  35370. prevIndex = i;
  35371. a = b;
  35372. }
  35373. return {
  35374. range: [prevIndex, nextIndex],
  35375. t: (xOrY - a) / (b - a)
  35376. };
  35377. }
  35378. function anyStateShowEndLabel(seriesModel) {
  35379. if (seriesModel.get(['endLabel', 'show'])) {
  35380. return true;
  35381. }
  35382. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  35383. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  35384. return true;
  35385. }
  35386. }
  35387. return false;
  35388. }
  35389. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  35390. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  35391. var endLabelModel_1 = seriesModel.getModel('endLabel');
  35392. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  35393. var data_1 = seriesModel.getData();
  35394. var labelAnimationRecord_1 = {
  35395. lastFrameIndex: 0
  35396. };
  35397. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  35398. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  35399. } : null;
  35400. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  35401. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  35402. var endLabel = lineView._endLabel;
  35403. if (endLabel && hasAnimation) {
  35404. if (labelAnimationRecord_1.originalX != null) {
  35405. endLabel.attr({
  35406. x: labelAnimationRecord_1.originalX,
  35407. y: labelAnimationRecord_1.originalY
  35408. });
  35409. }
  35410. }
  35411. }, during);
  35412. // Expand clip shape to avoid clipping when line value exceeds axis
  35413. if (!seriesModel.get('clip', true)) {
  35414. var rectShape = clipPath.shape;
  35415. var expandSize = Math.max(rectShape.width, rectShape.height);
  35416. if (isHorizontal) {
  35417. rectShape.y -= expandSize;
  35418. rectShape.height += expandSize * 2;
  35419. } else {
  35420. rectShape.x -= expandSize;
  35421. rectShape.width += expandSize * 2;
  35422. }
  35423. }
  35424. // Set to the final frame. To make sure label layout is right.
  35425. if (during) {
  35426. during(1, clipPath);
  35427. }
  35428. return clipPath;
  35429. } else {
  35430. if ("development" !== 'production') {
  35431. if (seriesModel.get(['endLabel', 'show'])) {
  35432. console.warn('endLabel is not supported for lines in polar systems.');
  35433. }
  35434. }
  35435. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  35436. }
  35437. }
  35438. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  35439. var baseAxis = coordSys.getBaseAxis();
  35440. var isHorizontal = baseAxis.isHorizontal();
  35441. var isBaseInversed = baseAxis.inverse;
  35442. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  35443. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  35444. return {
  35445. normal: {
  35446. align: endLabelModel.get('align') || align,
  35447. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  35448. }
  35449. };
  35450. }
  35451. var LineView = /** @class */function (_super) {
  35452. __extends(LineView, _super);
  35453. function LineView() {
  35454. return _super !== null && _super.apply(this, arguments) || this;
  35455. }
  35456. LineView.prototype.init = function () {
  35457. var lineGroup = new Group();
  35458. var symbolDraw = new SymbolDraw();
  35459. this.group.add(symbolDraw.group);
  35460. this._symbolDraw = symbolDraw;
  35461. this._lineGroup = lineGroup;
  35462. };
  35463. LineView.prototype.render = function (seriesModel, ecModel, api) {
  35464. var _this = this;
  35465. var coordSys = seriesModel.coordinateSystem;
  35466. var group = this.group;
  35467. var data = seriesModel.getData();
  35468. var lineStyleModel = seriesModel.getModel('lineStyle');
  35469. var areaStyleModel = seriesModel.getModel('areaStyle');
  35470. var points = data.getLayout('points') || [];
  35471. var isCoordSysPolar = coordSys.type === 'polar';
  35472. var prevCoordSys = this._coordSys;
  35473. var symbolDraw = this._symbolDraw;
  35474. var polyline = this._polyline;
  35475. var polygon = this._polygon;
  35476. var lineGroup = this._lineGroup;
  35477. var hasAnimation = !ecModel.ssr && seriesModel.get('animation');
  35478. var isAreaChart = !areaStyleModel.isEmpty();
  35479. var valueOrigin = areaStyleModel.get('origin');
  35480. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  35481. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  35482. var showSymbol = seriesModel.get('showSymbol');
  35483. var connectNulls = seriesModel.get('connectNulls');
  35484. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys);
  35485. // Remove temporary symbols
  35486. var oldData = this._data;
  35487. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  35488. if (el.__temp) {
  35489. group.remove(el);
  35490. oldData.setItemGraphicEl(idx, null);
  35491. }
  35492. });
  35493. // Remove previous created symbols if showSymbol changed to false
  35494. if (!showSymbol) {
  35495. symbolDraw.remove();
  35496. }
  35497. group.add(lineGroup);
  35498. // FIXME step not support polar
  35499. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  35500. var clipShapeForSymbol;
  35501. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  35502. clipShapeForSymbol = coordSys.getArea();
  35503. // Avoid float number rounding error for symbol on the edge of axis extent.
  35504. // See #7913 and `test/dataZoom-clip.html`.
  35505. if (clipShapeForSymbol.width != null) {
  35506. clipShapeForSymbol.x -= 0.1;
  35507. clipShapeForSymbol.y -= 0.1;
  35508. clipShapeForSymbol.width += 0.2;
  35509. clipShapeForSymbol.height += 0.2;
  35510. } else if (clipShapeForSymbol.r0) {
  35511. clipShapeForSymbol.r0 -= 0.5;
  35512. clipShapeForSymbol.r += 0.5;
  35513. }
  35514. }
  35515. this._clipShapeForSymbol = clipShapeForSymbol;
  35516. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')];
  35517. // Initialization animation or coordinate system changed
  35518. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  35519. showSymbol && symbolDraw.updateData(data, {
  35520. isIgnore: isIgnoreFunc,
  35521. clipShape: clipShapeForSymbol,
  35522. disableAnimation: true,
  35523. getSymbolPoint: function (idx) {
  35524. return [points[idx * 2], points[idx * 2 + 1]];
  35525. }
  35526. });
  35527. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  35528. if (step) {
  35529. // TODO If stacked series is not step
  35530. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  35531. if (stackedOnPoints) {
  35532. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  35533. }
  35534. }
  35535. polyline = this._newPolyline(points);
  35536. if (isAreaChart) {
  35537. polygon = this._newPolygon(points, stackedOnPoints);
  35538. } // If areaStyle is removed
  35539. else if (polygon) {
  35540. lineGroup.remove(polygon);
  35541. polygon = this._polygon = null;
  35542. }
  35543. // NOTE: Must update _endLabel before setClipPath.
  35544. if (!isCoordSysPolar) {
  35545. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  35546. }
  35547. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  35548. } else {
  35549. if (isAreaChart && !polygon) {
  35550. // If areaStyle is added
  35551. polygon = this._newPolygon(points, stackedOnPoints);
  35552. } else if (polygon && !isAreaChart) {
  35553. // If areaStyle is removed
  35554. lineGroup.remove(polygon);
  35555. polygon = this._polygon = null;
  35556. }
  35557. // NOTE: Must update _endLabel before setClipPath.
  35558. if (!isCoordSysPolar) {
  35559. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  35560. }
  35561. // Update clipPath
  35562. var oldClipPath = lineGroup.getClipPath();
  35563. if (oldClipPath) {
  35564. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  35565. initProps(oldClipPath, {
  35566. shape: newClipPath.shape
  35567. }, seriesModel);
  35568. } else {
  35569. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  35570. }
  35571. // Always update, or it is wrong in the case turning on legend
  35572. // because points are not changed.
  35573. showSymbol && symbolDraw.updateData(data, {
  35574. isIgnore: isIgnoreFunc,
  35575. clipShape: clipShapeForSymbol,
  35576. disableAnimation: true,
  35577. getSymbolPoint: function (idx) {
  35578. return [points[idx * 2], points[idx * 2 + 1]];
  35579. }
  35580. });
  35581. // In the case data zoom triggered refreshing frequently
  35582. // Data may not change if line has a category axis. So it should animate nothing.
  35583. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  35584. if (hasAnimation) {
  35585. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  35586. } else {
  35587. // Not do it in update with animation
  35588. if (step) {
  35589. // TODO If stacked series is not step
  35590. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  35591. if (stackedOnPoints) {
  35592. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  35593. }
  35594. }
  35595. polyline.setShape({
  35596. points: points
  35597. });
  35598. polygon && polygon.setShape({
  35599. points: points,
  35600. stackedOnPoints: stackedOnPoints
  35601. });
  35602. }
  35603. }
  35604. }
  35605. var emphasisModel = seriesModel.getModel('emphasis');
  35606. var focus = emphasisModel.get('focus');
  35607. var blurScope = emphasisModel.get('blurScope');
  35608. var emphasisDisabled = emphasisModel.get('disabled');
  35609. polyline.useStyle(defaults(
  35610. // Use color in lineStyle first
  35611. lineStyleModel.getLineStyle(), {
  35612. fill: 'none',
  35613. stroke: visualColor,
  35614. lineJoin: 'bevel'
  35615. }));
  35616. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  35617. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  35618. var emphasisLineStyle = polyline.getState('emphasis').style;
  35619. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  35620. }
  35621. // Needs seriesIndex for focus
  35622. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  35623. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  35624. var smooth = getSmooth(seriesModel.get('smooth'));
  35625. var smoothMonotone = seriesModel.get('smoothMonotone');
  35626. polyline.setShape({
  35627. smooth: smooth,
  35628. smoothMonotone: smoothMonotone,
  35629. connectNulls: connectNulls
  35630. });
  35631. if (polygon) {
  35632. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  35633. var stackedOnSmooth = 0;
  35634. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  35635. fill: visualColor,
  35636. opacity: 0.7,
  35637. lineJoin: 'bevel',
  35638. decal: data.getVisual('style').decal
  35639. }));
  35640. if (stackedOnSeries) {
  35641. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  35642. }
  35643. polygon.setShape({
  35644. smooth: smooth,
  35645. stackedOnSmooth: stackedOnSmooth,
  35646. smoothMonotone: smoothMonotone,
  35647. connectNulls: connectNulls
  35648. });
  35649. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle');
  35650. // Needs seriesIndex for focus
  35651. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  35652. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  35653. }
  35654. var changePolyState = function (toState) {
  35655. _this._changePolyState(toState);
  35656. };
  35657. data.eachItemGraphicEl(function (el) {
  35658. // Switch polyline / polygon state if element changed its state.
  35659. el && (el.onHoverStateChange = changePolyState);
  35660. });
  35661. this._polyline.onHoverStateChange = changePolyState;
  35662. this._data = data;
  35663. // Save the coordinate system for transition animation when data changed
  35664. this._coordSys = coordSys;
  35665. this._stackedOnPoints = stackedOnPoints;
  35666. this._points = points;
  35667. this._step = step;
  35668. this._valueOrigin = valueOrigin;
  35669. if (seriesModel.get('triggerLineEvent')) {
  35670. this.packEventData(seriesModel, polyline);
  35671. polygon && this.packEventData(seriesModel, polygon);
  35672. }
  35673. };
  35674. LineView.prototype.packEventData = function (seriesModel, el) {
  35675. getECData(el).eventData = {
  35676. componentType: 'series',
  35677. componentSubType: 'line',
  35678. componentIndex: seriesModel.componentIndex,
  35679. seriesIndex: seriesModel.seriesIndex,
  35680. seriesName: seriesModel.name,
  35681. seriesType: 'line'
  35682. };
  35683. };
  35684. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  35685. var data = seriesModel.getData();
  35686. var dataIndex = queryDataIndex(data, payload);
  35687. this._changePolyState('emphasis');
  35688. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  35689. var points = data.getLayout('points');
  35690. var symbol = data.getItemGraphicEl(dataIndex);
  35691. if (!symbol) {
  35692. // Create a temporary symbol if it is not exists
  35693. var x = points[dataIndex * 2];
  35694. var y = points[dataIndex * 2 + 1];
  35695. if (isNaN(x) || isNaN(y)) {
  35696. // Null data
  35697. return;
  35698. }
  35699. // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  35700. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  35701. return;
  35702. }
  35703. var zlevel = seriesModel.get('zlevel') || 0;
  35704. var z = seriesModel.get('z') || 0;
  35705. symbol = new Symbol(data, dataIndex);
  35706. symbol.x = x;
  35707. symbol.y = y;
  35708. symbol.setZ(zlevel, z);
  35709. // ensure label text of the temporary symbol is in front of line and area polygon
  35710. var symbolLabel = symbol.getSymbolPath().getTextContent();
  35711. if (symbolLabel) {
  35712. symbolLabel.zlevel = zlevel;
  35713. symbolLabel.z = z;
  35714. symbolLabel.z2 = this._polyline.z2 + 1;
  35715. }
  35716. symbol.__temp = true;
  35717. data.setItemGraphicEl(dataIndex, symbol);
  35718. // Stop scale animation
  35719. symbol.stopSymbolAnimation(true);
  35720. this.group.add(symbol);
  35721. }
  35722. symbol.highlight();
  35723. } else {
  35724. // Highlight whole series
  35725. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  35726. }
  35727. };
  35728. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  35729. var data = seriesModel.getData();
  35730. var dataIndex = queryDataIndex(data, payload);
  35731. this._changePolyState('normal');
  35732. if (dataIndex != null && dataIndex >= 0) {
  35733. var symbol = data.getItemGraphicEl(dataIndex);
  35734. if (symbol) {
  35735. if (symbol.__temp) {
  35736. data.setItemGraphicEl(dataIndex, null);
  35737. this.group.remove(symbol);
  35738. } else {
  35739. symbol.downplay();
  35740. }
  35741. }
  35742. } else {
  35743. // FIXME
  35744. // can not downplay completely.
  35745. // Downplay whole series
  35746. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  35747. }
  35748. };
  35749. LineView.prototype._changePolyState = function (toState) {
  35750. var polygon = this._polygon;
  35751. setStatesFlag(this._polyline, toState);
  35752. polygon && setStatesFlag(polygon, toState);
  35753. };
  35754. LineView.prototype._newPolyline = function (points) {
  35755. var polyline = this._polyline;
  35756. // Remove previous created polyline
  35757. if (polyline) {
  35758. this._lineGroup.remove(polyline);
  35759. }
  35760. polyline = new ECPolyline({
  35761. shape: {
  35762. points: points
  35763. },
  35764. segmentIgnoreThreshold: 2,
  35765. z2: 10
  35766. });
  35767. this._lineGroup.add(polyline);
  35768. this._polyline = polyline;
  35769. return polyline;
  35770. };
  35771. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  35772. var polygon = this._polygon;
  35773. // Remove previous created polygon
  35774. if (polygon) {
  35775. this._lineGroup.remove(polygon);
  35776. }
  35777. polygon = new ECPolygon({
  35778. shape: {
  35779. points: points,
  35780. stackedOnPoints: stackedOnPoints
  35781. },
  35782. segmentIgnoreThreshold: 2
  35783. });
  35784. this._lineGroup.add(polygon);
  35785. this._polygon = polygon;
  35786. return polygon;
  35787. };
  35788. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  35789. var isHorizontalOrRadial;
  35790. var isCoordSysPolar;
  35791. var baseAxis = coordSys.getBaseAxis();
  35792. var isAxisInverse = baseAxis.inverse;
  35793. if (coordSys.type === 'cartesian2d') {
  35794. isHorizontalOrRadial = baseAxis.isHorizontal();
  35795. isCoordSysPolar = false;
  35796. } else if (coordSys.type === 'polar') {
  35797. isHorizontalOrRadial = baseAxis.dim === 'angle';
  35798. isCoordSysPolar = true;
  35799. }
  35800. var seriesModel = data.hostModel;
  35801. var seriesDuration = seriesModel.get('animationDuration');
  35802. if (isFunction(seriesDuration)) {
  35803. seriesDuration = seriesDuration(null);
  35804. }
  35805. var seriesDelay = seriesModel.get('animationDelay') || 0;
  35806. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  35807. data.eachItemGraphicEl(function (symbol, idx) {
  35808. var el = symbol;
  35809. if (el) {
  35810. var point = [symbol.x, symbol.y];
  35811. var start = void 0;
  35812. var end = void 0;
  35813. var current = void 0;
  35814. if (clipShape) {
  35815. if (isCoordSysPolar) {
  35816. var polarClip = clipShape;
  35817. var coord = coordSys.pointToCoord(point);
  35818. if (isHorizontalOrRadial) {
  35819. start = polarClip.startAngle;
  35820. end = polarClip.endAngle;
  35821. current = -coord[1] / 180 * Math.PI;
  35822. } else {
  35823. start = polarClip.r0;
  35824. end = polarClip.r;
  35825. current = coord[0];
  35826. }
  35827. } else {
  35828. var gridClip = clipShape;
  35829. if (isHorizontalOrRadial) {
  35830. start = gridClip.x;
  35831. end = gridClip.x + gridClip.width;
  35832. current = symbol.x;
  35833. } else {
  35834. start = gridClip.y + gridClip.height;
  35835. end = gridClip.y;
  35836. current = symbol.y;
  35837. }
  35838. }
  35839. }
  35840. var ratio = end === start ? 0 : (current - start) / (end - start);
  35841. if (isAxisInverse) {
  35842. ratio = 1 - ratio;
  35843. }
  35844. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  35845. var symbolPath = el.getSymbolPath();
  35846. var text = symbolPath.getTextContent();
  35847. el.attr({
  35848. scaleX: 0,
  35849. scaleY: 0
  35850. });
  35851. el.animateTo({
  35852. scaleX: 1,
  35853. scaleY: 1
  35854. }, {
  35855. duration: 200,
  35856. setToFinal: true,
  35857. delay: delay
  35858. });
  35859. if (text) {
  35860. text.animateFrom({
  35861. style: {
  35862. opacity: 0
  35863. }
  35864. }, {
  35865. duration: 300,
  35866. delay: delay
  35867. });
  35868. }
  35869. symbolPath.disableLabelAnimation = true;
  35870. }
  35871. });
  35872. };
  35873. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  35874. var endLabelModel = seriesModel.getModel('endLabel');
  35875. if (anyStateShowEndLabel(seriesModel)) {
  35876. var data_2 = seriesModel.getData();
  35877. var polyline = this._polyline;
  35878. // series may be filtered.
  35879. var points = data_2.getLayout('points');
  35880. if (!points) {
  35881. polyline.removeTextContent();
  35882. this._endLabel = null;
  35883. return;
  35884. }
  35885. var endLabel = this._endLabel;
  35886. if (!endLabel) {
  35887. endLabel = this._endLabel = new ZRText({
  35888. z2: 200 // should be higher than item symbol
  35889. });
  35890. endLabel.ignoreClip = true;
  35891. polyline.setTextContent(this._endLabel);
  35892. polyline.disableLabelAnimation = true;
  35893. }
  35894. // Find last non-NaN data to display data
  35895. var dataIndex = getLastIndexNotNull(points);
  35896. if (dataIndex >= 0) {
  35897. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  35898. inheritColor: inheritColor,
  35899. labelFetcher: seriesModel,
  35900. labelDataIndex: dataIndex,
  35901. defaultText: function (dataIndex, opt, interpolatedValue) {
  35902. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  35903. },
  35904. enableTextSetter: true
  35905. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  35906. polyline.textConfig.position = null;
  35907. }
  35908. } else if (this._endLabel) {
  35909. this._polyline.removeTextContent();
  35910. this._endLabel = null;
  35911. }
  35912. };
  35913. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  35914. var endLabel = this._endLabel;
  35915. var polyline = this._polyline;
  35916. if (endLabel) {
  35917. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  35918. // The label is not prepared at this time.
  35919. if (percent < 1 && animationRecord.originalX == null) {
  35920. animationRecord.originalX = endLabel.x;
  35921. animationRecord.originalY = endLabel.y;
  35922. }
  35923. var points = data.getLayout('points');
  35924. var seriesModel = data.hostModel;
  35925. var connectNulls = seriesModel.get('connectNulls');
  35926. var precision = endLabelModel.get('precision');
  35927. var distance = endLabelModel.get('distance') || 0;
  35928. var baseAxis = coordSys.getBaseAxis();
  35929. var isHorizontal = baseAxis.isHorizontal();
  35930. var isBaseInversed = baseAxis.inverse;
  35931. var clipShape = clipRect.shape;
  35932. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  35933. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  35934. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  35935. var dim = isHorizontal ? 'x' : 'y';
  35936. var dataIndexRange = getIndexRange(points, xOrY, dim);
  35937. var indices = dataIndexRange.range;
  35938. var diff = indices[1] - indices[0];
  35939. var value = void 0;
  35940. if (diff >= 1) {
  35941. // diff > 1 && connectNulls, which is on the null data.
  35942. if (diff > 1 && !connectNulls) {
  35943. var pt = getPointAtIndex(points, indices[0]);
  35944. endLabel.attr({
  35945. x: pt[0] + distanceX,
  35946. y: pt[1] + distanceY
  35947. });
  35948. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  35949. } else {
  35950. var pt = polyline.getPointOn(xOrY, dim);
  35951. pt && endLabel.attr({
  35952. x: pt[0] + distanceX,
  35953. y: pt[1] + distanceY
  35954. });
  35955. var startValue = seriesModel.getRawValue(indices[0]);
  35956. var endValue = seriesModel.getRawValue(indices[1]);
  35957. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  35958. }
  35959. animationRecord.lastFrameIndex = indices[0];
  35960. } else {
  35961. // If diff <= 0, which is the range is not found(Include NaN)
  35962. // Choose the first point or last point.
  35963. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  35964. var pt = getPointAtIndex(points, idx);
  35965. valueAnimation && (value = seriesModel.getRawValue(idx));
  35966. endLabel.attr({
  35967. x: pt[0] + distanceX,
  35968. y: pt[1] + distanceY
  35969. });
  35970. }
  35971. if (valueAnimation) {
  35972. var inner = labelInner(endLabel);
  35973. if (typeof inner.setLabelText === 'function') {
  35974. inner.setLabelText(value);
  35975. }
  35976. }
  35977. }
  35978. };
  35979. /**
  35980. * @private
  35981. */
  35982. // FIXME Two value axis
  35983. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  35984. var polyline = this._polyline;
  35985. var polygon = this._polygon;
  35986. var seriesModel = data.hostModel;
  35987. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  35988. var current = diff.current;
  35989. var stackedOnCurrent = diff.stackedOnCurrent;
  35990. var next = diff.next;
  35991. var stackedOnNext = diff.stackedOnNext;
  35992. if (step) {
  35993. // TODO If stacked series is not step
  35994. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  35995. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  35996. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  35997. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  35998. }
  35999. // Don't apply animation if diff is large.
  36000. // For better result and avoid memory explosion problems like
  36001. // https://github.com/apache/incubator-echarts/issues/12229
  36002. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  36003. polyline.stopAnimation();
  36004. polyline.setShape({
  36005. points: next
  36006. });
  36007. if (polygon) {
  36008. polygon.stopAnimation();
  36009. polygon.setShape({
  36010. points: next,
  36011. stackedOnPoints: stackedOnNext
  36012. });
  36013. }
  36014. return;
  36015. }
  36016. polyline.shape.__points = diff.current;
  36017. polyline.shape.points = current;
  36018. var target = {
  36019. shape: {
  36020. points: next
  36021. }
  36022. };
  36023. // Also animate the original points.
  36024. // If points reference is changed when turning into step line.
  36025. if (diff.current !== current) {
  36026. target.shape.__points = diff.next;
  36027. }
  36028. // Stop previous animation.
  36029. polyline.stopAnimation();
  36030. updateProps(polyline, target, seriesModel);
  36031. if (polygon) {
  36032. polygon.setShape({
  36033. // Reuse the points with polyline.
  36034. points: current,
  36035. stackedOnPoints: stackedOnCurrent
  36036. });
  36037. polygon.stopAnimation();
  36038. updateProps(polygon, {
  36039. shape: {
  36040. stackedOnPoints: stackedOnNext
  36041. }
  36042. }, seriesModel);
  36043. // If use attr directly in updateProps.
  36044. if (polyline.shape.points !== polygon.shape.points) {
  36045. polygon.shape.points = polyline.shape.points;
  36046. }
  36047. }
  36048. var updatedDataInfo = [];
  36049. var diffStatus = diff.status;
  36050. for (var i = 0; i < diffStatus.length; i++) {
  36051. var cmd = diffStatus[i].cmd;
  36052. if (cmd === '=') {
  36053. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  36054. if (el) {
  36055. updatedDataInfo.push({
  36056. el: el,
  36057. ptIdx: i // Index of points
  36058. });
  36059. }
  36060. }
  36061. }
  36062. if (polyline.animators && polyline.animators.length) {
  36063. polyline.animators[0].during(function () {
  36064. polygon && polygon.dirtyShape();
  36065. var points = polyline.shape.__points;
  36066. for (var i = 0; i < updatedDataInfo.length; i++) {
  36067. var el = updatedDataInfo[i].el;
  36068. var offset = updatedDataInfo[i].ptIdx * 2;
  36069. el.x = points[offset];
  36070. el.y = points[offset + 1];
  36071. el.markRedraw();
  36072. }
  36073. });
  36074. }
  36075. };
  36076. LineView.prototype.remove = function (ecModel) {
  36077. var group = this.group;
  36078. var oldData = this._data;
  36079. this._lineGroup.removeAll();
  36080. this._symbolDraw.remove(true);
  36081. // Remove temporary created elements when highlighting
  36082. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  36083. if (el.__temp) {
  36084. group.remove(el);
  36085. oldData.setItemGraphicEl(idx, null);
  36086. }
  36087. });
  36088. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  36089. };
  36090. LineView.type = 'line';
  36091. return LineView;
  36092. }(ChartView);
  36093. function pointsLayout(seriesType, forceStoreInTypedArray) {
  36094. return {
  36095. seriesType: seriesType,
  36096. plan: createRenderPlanner(),
  36097. reset: function (seriesModel) {
  36098. var data = seriesModel.getData();
  36099. var coordSys = seriesModel.coordinateSystem;
  36100. var pipelineContext = seriesModel.pipelineContext;
  36101. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  36102. if (!coordSys) {
  36103. return;
  36104. }
  36105. var dims = map(coordSys.dimensions, function (dim) {
  36106. return data.mapDimension(dim);
  36107. }).slice(0, 2);
  36108. var dimLen = dims.length;
  36109. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  36110. if (isDimensionStacked(data, dims[0])) {
  36111. dims[0] = stackResultDim;
  36112. }
  36113. if (isDimensionStacked(data, dims[1])) {
  36114. dims[1] = stackResultDim;
  36115. }
  36116. var store = data.getStore();
  36117. var dimIdx0 = data.getDimensionIndex(dims[0]);
  36118. var dimIdx1 = data.getDimensionIndex(dims[1]);
  36119. return dimLen && {
  36120. progress: function (params, data) {
  36121. var segCount = params.end - params.start;
  36122. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  36123. var tmpIn = [];
  36124. var tmpOut = [];
  36125. for (var i = params.start, offset = 0; i < params.end; i++) {
  36126. var point = void 0;
  36127. if (dimLen === 1) {
  36128. var x = store.get(dimIdx0, i);
  36129. // NOTE: Make sure the second parameter is null to use default strategy.
  36130. point = coordSys.dataToPoint(x, null, tmpOut);
  36131. } else {
  36132. tmpIn[0] = store.get(dimIdx0, i);
  36133. tmpIn[1] = store.get(dimIdx1, i);
  36134. // Let coordinate system to handle the NaN data.
  36135. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  36136. }
  36137. if (useTypedArray) {
  36138. points[offset++] = point[0];
  36139. points[offset++] = point[1];
  36140. } else {
  36141. data.setItemLayout(i, point.slice());
  36142. }
  36143. }
  36144. useTypedArray && data.setLayout('points', points);
  36145. }
  36146. };
  36147. }
  36148. };
  36149. }
  36150. var samplers = {
  36151. average: function (frame) {
  36152. var sum = 0;
  36153. var count = 0;
  36154. for (var i = 0; i < frame.length; i++) {
  36155. if (!isNaN(frame[i])) {
  36156. sum += frame[i];
  36157. count++;
  36158. }
  36159. }
  36160. // Return NaN if count is 0
  36161. return count === 0 ? NaN : sum / count;
  36162. },
  36163. sum: function (frame) {
  36164. var sum = 0;
  36165. for (var i = 0; i < frame.length; i++) {
  36166. // Ignore NaN
  36167. sum += frame[i] || 0;
  36168. }
  36169. return sum;
  36170. },
  36171. max: function (frame) {
  36172. var max = -Infinity;
  36173. for (var i = 0; i < frame.length; i++) {
  36174. frame[i] > max && (max = frame[i]);
  36175. }
  36176. // NaN will cause illegal axis extent.
  36177. return isFinite(max) ? max : NaN;
  36178. },
  36179. min: function (frame) {
  36180. var min = Infinity;
  36181. for (var i = 0; i < frame.length; i++) {
  36182. frame[i] < min && (min = frame[i]);
  36183. }
  36184. // NaN will cause illegal axis extent.
  36185. return isFinite(min) ? min : NaN;
  36186. },
  36187. minmax: function (frame) {
  36188. var turningPointAbsoluteValue = -Infinity;
  36189. var turningPointOriginalValue = -Infinity;
  36190. for (var i = 0; i < frame.length; i++) {
  36191. var originalValue = frame[i];
  36192. var absoluteValue = Math.abs(originalValue);
  36193. if (absoluteValue > turningPointAbsoluteValue) {
  36194. turningPointAbsoluteValue = absoluteValue;
  36195. turningPointOriginalValue = originalValue;
  36196. }
  36197. }
  36198. return isFinite(turningPointOriginalValue) ? turningPointOriginalValue : NaN;
  36199. },
  36200. // TODO
  36201. // Median
  36202. nearest: function (frame) {
  36203. return frame[0];
  36204. }
  36205. };
  36206. var indexSampler = function (frame) {
  36207. return Math.round(frame.length / 2);
  36208. };
  36209. function dataSample(seriesType) {
  36210. return {
  36211. seriesType: seriesType,
  36212. // FIXME:TS never used, so comment it
  36213. // modifyOutputEnd: true,
  36214. reset: function (seriesModel, ecModel, api) {
  36215. var data = seriesModel.getData();
  36216. var sampling = seriesModel.get('sampling');
  36217. var coordSys = seriesModel.coordinateSystem;
  36218. var count = data.count();
  36219. // Only cartesian2d support down sampling. Disable it when there is few data.
  36220. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  36221. var baseAxis = coordSys.getBaseAxis();
  36222. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36223. var extent = baseAxis.getExtent();
  36224. var dpr = api.getDevicePixelRatio();
  36225. // Coordinste system has been resized
  36226. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  36227. var rate = Math.round(count / size);
  36228. if (isFinite(rate) && rate > 1) {
  36229. if (sampling === 'lttb') {
  36230. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  36231. }
  36232. var sampler = void 0;
  36233. if (isString(sampling)) {
  36234. sampler = samplers[sampling];
  36235. } else if (isFunction(sampling)) {
  36236. sampler = sampling;
  36237. }
  36238. if (sampler) {
  36239. // Only support sample the first dim mapped from value axis.
  36240. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  36241. }
  36242. }
  36243. }
  36244. }
  36245. };
  36246. }
  36247. function install$1(registers) {
  36248. registers.registerChartView(LineView);
  36249. registers.registerSeriesModel(LineSeriesModel);
  36250. registers.registerLayout(pointsLayout('line', true));
  36251. registers.registerVisual({
  36252. seriesType: 'line',
  36253. reset: function (seriesModel) {
  36254. var data = seriesModel.getData();
  36255. // Visual coding for legend
  36256. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  36257. if (lineStyle && !lineStyle.stroke) {
  36258. // Fill in visual should be palette color if
  36259. // has color callback
  36260. lineStyle.stroke = data.getVisual('style').fill;
  36261. }
  36262. data.setVisual('legendLineStyle', lineStyle);
  36263. }
  36264. });
  36265. // Down sample after filter
  36266. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  36267. }
  36268. var BaseBarSeriesModel = /** @class */function (_super) {
  36269. __extends(BaseBarSeriesModel, _super);
  36270. function BaseBarSeriesModel() {
  36271. var _this = _super !== null && _super.apply(this, arguments) || this;
  36272. _this.type = BaseBarSeriesModel.type;
  36273. return _this;
  36274. }
  36275. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  36276. return createSeriesData(null, this, {
  36277. useEncodeDefaulter: true
  36278. });
  36279. };
  36280. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  36281. var coordSys = this.coordinateSystem;
  36282. if (coordSys && coordSys.clampData) {
  36283. // PENDING if clamp ?
  36284. var clampData_1 = coordSys.clampData(value);
  36285. var pt_1 = coordSys.dataToPoint(clampData_1);
  36286. if (startingAtTick) {
  36287. each(coordSys.getAxes(), function (axis, idx) {
  36288. // If axis type is category, use tick coords instead
  36289. if (axis.type === 'category' && dims != null) {
  36290. var tickCoords = axis.getTicksCoords();
  36291. var alignTicksWithLabel = axis.getTickModel().get('alignWithLabel');
  36292. var targetTickId = clampData_1[idx];
  36293. // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  36294. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  36295. if (isEnd && !alignTicksWithLabel) {
  36296. targetTickId += 1;
  36297. }
  36298. // The only contains one tick, tickCoords is
  36299. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  36300. // to the length should always be larger than 1
  36301. if (tickCoords.length < 2) {
  36302. return;
  36303. } else if (tickCoords.length === 2) {
  36304. // The left value and right value of the axis are
  36305. // the same. coord is 0 in both items. Use the max
  36306. // value of the axis as the coord
  36307. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  36308. return;
  36309. }
  36310. var leftCoord = void 0;
  36311. var coord = void 0;
  36312. var stepTickValue = 1;
  36313. for (var i = 0; i < tickCoords.length; i++) {
  36314. var tickCoord = tickCoords[i].coord;
  36315. // The last item of tickCoords doesn't contain
  36316. // tickValue
  36317. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  36318. if (tickValue === targetTickId) {
  36319. coord = tickCoord;
  36320. break;
  36321. } else if (tickValue < targetTickId) {
  36322. leftCoord = tickCoord;
  36323. } else if (leftCoord != null && tickValue > targetTickId) {
  36324. coord = (tickCoord + leftCoord) / 2;
  36325. break;
  36326. }
  36327. if (i === 1) {
  36328. // Here we assume the step of category axes is
  36329. // the same
  36330. stepTickValue = tickValue - tickCoords[0].tickValue;
  36331. }
  36332. }
  36333. if (coord == null) {
  36334. if (!leftCoord) {
  36335. // targetTickId is smaller than all tick ids in the
  36336. // visible area, use the leftmost tick coord
  36337. coord = tickCoords[0].coord;
  36338. } else if (leftCoord) {
  36339. // targetTickId is larger than all tick ids in the
  36340. // visible area, use the rightmost tick coord
  36341. coord = tickCoords[tickCoords.length - 1].coord;
  36342. }
  36343. }
  36344. pt_1[idx] = axis.toGlobalCoord(coord);
  36345. }
  36346. });
  36347. } else {
  36348. var data = this.getData();
  36349. var offset = data.getLayout('offset');
  36350. var size = data.getLayout('size');
  36351. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  36352. pt_1[offsetIndex] += offset + size / 2;
  36353. }
  36354. return pt_1;
  36355. }
  36356. return [NaN, NaN];
  36357. };
  36358. BaseBarSeriesModel.type = 'series.__base_bar__';
  36359. BaseBarSeriesModel.defaultOption = {
  36360. // zlevel: 0,
  36361. z: 2,
  36362. coordinateSystem: 'cartesian2d',
  36363. legendHoverLink: true,
  36364. // stack: null
  36365. // Cartesian coordinate system
  36366. // xAxisIndex: 0,
  36367. // yAxisIndex: 0,
  36368. barMinHeight: 0,
  36369. barMinAngle: 0,
  36370. // cursor: null,
  36371. large: false,
  36372. largeThreshold: 400,
  36373. progressive: 3e3,
  36374. progressiveChunkMode: 'mod'
  36375. };
  36376. return BaseBarSeriesModel;
  36377. }(SeriesModel);
  36378. SeriesModel.registerClass(BaseBarSeriesModel);
  36379. var BarSeriesModel = /** @class */function (_super) {
  36380. __extends(BarSeriesModel, _super);
  36381. function BarSeriesModel() {
  36382. var _this = _super !== null && _super.apply(this, arguments) || this;
  36383. _this.type = BarSeriesModel.type;
  36384. return _this;
  36385. }
  36386. BarSeriesModel.prototype.getInitialData = function () {
  36387. return createSeriesData(null, this, {
  36388. useEncodeDefaulter: true,
  36389. createInvertedIndices: !!this.get('realtimeSort', true) || null
  36390. });
  36391. };
  36392. /**
  36393. * @override
  36394. */
  36395. BarSeriesModel.prototype.getProgressive = function () {
  36396. // Do not support progressive in normal mode.
  36397. return this.get('large') ? this.get('progressive') : false;
  36398. };
  36399. /**
  36400. * @override
  36401. */
  36402. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  36403. // Do not support progressive in normal mode.
  36404. var progressiveThreshold = this.get('progressiveThreshold');
  36405. var largeThreshold = this.get('largeThreshold');
  36406. if (largeThreshold > progressiveThreshold) {
  36407. progressiveThreshold = largeThreshold;
  36408. }
  36409. return progressiveThreshold;
  36410. };
  36411. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  36412. return selectors.rect(data.getItemLayout(dataIndex));
  36413. };
  36414. BarSeriesModel.type = 'series.bar';
  36415. BarSeriesModel.dependencies = ['grid', 'polar'];
  36416. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  36417. // If clipped
  36418. // Only available on cartesian2d
  36419. clip: true,
  36420. roundCap: false,
  36421. showBackground: false,
  36422. backgroundStyle: {
  36423. color: 'rgba(180, 180, 180, 0.2)',
  36424. borderColor: null,
  36425. borderWidth: 0,
  36426. borderType: 'solid',
  36427. borderRadius: 0,
  36428. shadowBlur: 0,
  36429. shadowColor: null,
  36430. shadowOffsetX: 0,
  36431. shadowOffsetY: 0,
  36432. opacity: 1
  36433. },
  36434. select: {
  36435. itemStyle: {
  36436. borderColor: '#212121'
  36437. }
  36438. },
  36439. realtimeSort: false
  36440. });
  36441. return BarSeriesModel;
  36442. }(BaseBarSeriesModel);
  36443. /**
  36444. * Sausage: similar to sector, but have half circle on both sides
  36445. */
  36446. var SausageShape = /** @class */function () {
  36447. function SausageShape() {
  36448. this.cx = 0;
  36449. this.cy = 0;
  36450. this.r0 = 0;
  36451. this.r = 0;
  36452. this.startAngle = 0;
  36453. this.endAngle = Math.PI * 2;
  36454. this.clockwise = true;
  36455. }
  36456. return SausageShape;
  36457. }();
  36458. var SausagePath = /** @class */function (_super) {
  36459. __extends(SausagePath, _super);
  36460. function SausagePath(opts) {
  36461. var _this = _super.call(this, opts) || this;
  36462. _this.type = 'sausage';
  36463. return _this;
  36464. }
  36465. SausagePath.prototype.getDefaultShape = function () {
  36466. return new SausageShape();
  36467. };
  36468. SausagePath.prototype.buildPath = function (ctx, shape) {
  36469. var cx = shape.cx;
  36470. var cy = shape.cy;
  36471. var r0 = Math.max(shape.r0 || 0, 0);
  36472. var r = Math.max(shape.r, 0);
  36473. var dr = (r - r0) * 0.5;
  36474. var rCenter = r0 + dr;
  36475. var startAngle = shape.startAngle;
  36476. var endAngle = shape.endAngle;
  36477. var clockwise = shape.clockwise;
  36478. var PI2 = Math.PI * 2;
  36479. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  36480. if (!lessThanCircle) {
  36481. // Normalize angles
  36482. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  36483. }
  36484. var unitStartX = Math.cos(startAngle);
  36485. var unitStartY = Math.sin(startAngle);
  36486. var unitEndX = Math.cos(endAngle);
  36487. var unitEndY = Math.sin(endAngle);
  36488. if (lessThanCircle) {
  36489. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  36490. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  36491. } else {
  36492. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  36493. }
  36494. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  36495. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  36496. if (r0 !== 0) {
  36497. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  36498. }
  36499. // ctx.closePath();
  36500. };
  36501. return SausagePath;
  36502. }(Path);
  36503. function createSectorCalculateTextPosition(positionMapping, opts) {
  36504. opts = opts || {};
  36505. var isRoundCap = opts.isRoundCap;
  36506. return function (out, opts, boundingRect) {
  36507. var textPosition = opts.position;
  36508. if (!textPosition || textPosition instanceof Array) {
  36509. return calculateTextPosition(out, opts, boundingRect);
  36510. }
  36511. var mappedSectorPosition = positionMapping(textPosition);
  36512. var distance = opts.distance != null ? opts.distance : 5;
  36513. var sector = this.shape;
  36514. var cx = sector.cx;
  36515. var cy = sector.cy;
  36516. var r = sector.r;
  36517. var r0 = sector.r0;
  36518. var middleR = (r + r0) / 2;
  36519. var startAngle = sector.startAngle;
  36520. var endAngle = sector.endAngle;
  36521. var middleAngle = (startAngle + endAngle) / 2;
  36522. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  36523. var mathCos = Math.cos;
  36524. var mathSin = Math.sin;
  36525. // base position: top-left
  36526. var x = cx + r * mathCos(startAngle);
  36527. var y = cy + r * mathSin(startAngle);
  36528. var textAlign = 'left';
  36529. var textVerticalAlign = 'top';
  36530. switch (mappedSectorPosition) {
  36531. case 'startArc':
  36532. x = cx + (r0 - distance) * mathCos(middleAngle);
  36533. y = cy + (r0 - distance) * mathSin(middleAngle);
  36534. textAlign = 'center';
  36535. textVerticalAlign = 'top';
  36536. break;
  36537. case 'insideStartArc':
  36538. x = cx + (r0 + distance) * mathCos(middleAngle);
  36539. y = cy + (r0 + distance) * mathSin(middleAngle);
  36540. textAlign = 'center';
  36541. textVerticalAlign = 'bottom';
  36542. break;
  36543. case 'startAngle':
  36544. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  36545. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  36546. textAlign = 'right';
  36547. textVerticalAlign = 'middle';
  36548. break;
  36549. case 'insideStartAngle':
  36550. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  36551. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  36552. textAlign = 'left';
  36553. textVerticalAlign = 'middle';
  36554. break;
  36555. case 'middle':
  36556. x = cx + middleR * mathCos(middleAngle);
  36557. y = cy + middleR * mathSin(middleAngle);
  36558. textAlign = 'center';
  36559. textVerticalAlign = 'middle';
  36560. break;
  36561. case 'endArc':
  36562. x = cx + (r + distance) * mathCos(middleAngle);
  36563. y = cy + (r + distance) * mathSin(middleAngle);
  36564. textAlign = 'center';
  36565. textVerticalAlign = 'bottom';
  36566. break;
  36567. case 'insideEndArc':
  36568. x = cx + (r - distance) * mathCos(middleAngle);
  36569. y = cy + (r - distance) * mathSin(middleAngle);
  36570. textAlign = 'center';
  36571. textVerticalAlign = 'top';
  36572. break;
  36573. case 'endAngle':
  36574. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  36575. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  36576. textAlign = 'left';
  36577. textVerticalAlign = 'middle';
  36578. break;
  36579. case 'insideEndAngle':
  36580. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  36581. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  36582. textAlign = 'right';
  36583. textVerticalAlign = 'middle';
  36584. break;
  36585. default:
  36586. return calculateTextPosition(out, opts, boundingRect);
  36587. }
  36588. out = out || {};
  36589. out.x = x;
  36590. out.y = y;
  36591. out.align = textAlign;
  36592. out.verticalAlign = textVerticalAlign;
  36593. return out;
  36594. };
  36595. }
  36596. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  36597. if (isNumber(rotateType)) {
  36598. // user-set rotation
  36599. sector.setTextConfig({
  36600. rotation: rotateType
  36601. });
  36602. return;
  36603. } else if (isArray(textPosition)) {
  36604. // user-set position, use 0 as auto rotation
  36605. sector.setTextConfig({
  36606. rotation: 0
  36607. });
  36608. return;
  36609. }
  36610. var shape = sector.shape;
  36611. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  36612. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  36613. var middleAngle = (startAngle + endAngle) / 2;
  36614. var anchorAngle;
  36615. var mappedSectorPosition = positionMapping(textPosition);
  36616. switch (mappedSectorPosition) {
  36617. case 'startArc':
  36618. case 'insideStartArc':
  36619. case 'middle':
  36620. case 'insideEndArc':
  36621. case 'endArc':
  36622. anchorAngle = middleAngle;
  36623. break;
  36624. case 'startAngle':
  36625. case 'insideStartAngle':
  36626. anchorAngle = startAngle;
  36627. break;
  36628. case 'endAngle':
  36629. case 'insideEndAngle':
  36630. anchorAngle = endAngle;
  36631. break;
  36632. default:
  36633. sector.setTextConfig({
  36634. rotation: 0
  36635. });
  36636. return;
  36637. }
  36638. var rotate = Math.PI * 1.5 - anchorAngle;
  36639. /**
  36640. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  36641. * half round flipped to increase readability. However, only middle
  36642. * position supports this for now, because in other positions, the
  36643. * anchor point is not at the center of the text, so the positions
  36644. * after rotating is not as expected.
  36645. */
  36646. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  36647. rotate -= Math.PI;
  36648. }
  36649. sector.setTextConfig({
  36650. rotation: rotate
  36651. });
  36652. }
  36653. function adjustAngleDistanceX(angle, distance, isEnd) {
  36654. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  36655. }
  36656. function adjustAngleDistanceY(angle, distance, isEnd) {
  36657. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  36658. }
  36659. function getSectorCornerRadius(model, shape, zeroIfNull) {
  36660. var cornerRadius = model.get('borderRadius');
  36661. if (cornerRadius == null) {
  36662. return zeroIfNull ? {
  36663. cornerRadius: 0
  36664. } : null;
  36665. }
  36666. if (!isArray(cornerRadius)) {
  36667. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  36668. }
  36669. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  36670. return {
  36671. cornerRadius: map(cornerRadius, function (cr) {
  36672. return parsePercent(cr, dr);
  36673. })
  36674. };
  36675. }
  36676. var mathMax$6 = Math.max;
  36677. var mathMin$6 = Math.min;
  36678. function getClipArea(coord, data) {
  36679. var coordSysClipArea = coord.getArea && coord.getArea();
  36680. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  36681. var baseAxis = coord.getBaseAxis();
  36682. // When boundaryGap is false or using time axis. bar may exceed the grid.
  36683. // We should not clip this part.
  36684. // See test/bar2.html
  36685. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  36686. var expandWidth = data.getLayout('bandWidth');
  36687. if (baseAxis.isHorizontal()) {
  36688. coordSysClipArea.x -= expandWidth;
  36689. coordSysClipArea.width += expandWidth * 2;
  36690. } else {
  36691. coordSysClipArea.y -= expandWidth;
  36692. coordSysClipArea.height += expandWidth * 2;
  36693. }
  36694. }
  36695. }
  36696. return coordSysClipArea;
  36697. }
  36698. var BarView = /** @class */function (_super) {
  36699. __extends(BarView, _super);
  36700. function BarView() {
  36701. var _this = _super.call(this) || this;
  36702. _this.type = BarView.type;
  36703. _this._isFirstFrame = true;
  36704. return _this;
  36705. }
  36706. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  36707. this._model = seriesModel;
  36708. this._removeOnRenderedListener(api);
  36709. this._updateDrawMode(seriesModel);
  36710. var coordinateSystemType = seriesModel.get('coordinateSystem');
  36711. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  36712. // Clear previously rendered progressive elements.
  36713. this._progressiveEls = null;
  36714. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  36715. } else if ("development" !== 'production') {
  36716. warn('Only cartesian2d and polar supported for bar.');
  36717. }
  36718. };
  36719. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  36720. this._clear();
  36721. this._updateDrawMode(seriesModel);
  36722. // incremental also need to clip, otherwise might be overlow.
  36723. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  36724. this._updateLargeClip(seriesModel);
  36725. };
  36726. BarView.prototype.incrementalRender = function (params, seriesModel) {
  36727. // Reset
  36728. this._progressiveEls = [];
  36729. // Do not support progressive in normal mode.
  36730. this._incrementalRenderLarge(params, seriesModel);
  36731. };
  36732. BarView.prototype.eachRendered = function (cb) {
  36733. traverseElements(this._progressiveEls || this.group, cb);
  36734. };
  36735. BarView.prototype._updateDrawMode = function (seriesModel) {
  36736. var isLargeDraw = seriesModel.pipelineContext.large;
  36737. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  36738. this._isLargeDraw = isLargeDraw;
  36739. this._clear();
  36740. }
  36741. };
  36742. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  36743. var group = this.group;
  36744. var data = seriesModel.getData();
  36745. var oldData = this._data;
  36746. var coord = seriesModel.coordinateSystem;
  36747. var baseAxis = coord.getBaseAxis();
  36748. var isHorizontalOrRadial;
  36749. if (coord.type === 'cartesian2d') {
  36750. isHorizontalOrRadial = baseAxis.isHorizontal();
  36751. } else if (coord.type === 'polar') {
  36752. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36753. }
  36754. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  36755. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  36756. if (realtimeSortCfg) {
  36757. this._enableRealtimeSort(realtimeSortCfg, data, api);
  36758. }
  36759. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  36760. var coordSysClipArea = getClipArea(coord, data);
  36761. // If there is clipPath created in large mode. Remove it.
  36762. group.removeClipPath();
  36763. // We don't use clipPath in normal mode because we needs a perfect animation
  36764. // And don't want the label are clipped.
  36765. var roundCap = seriesModel.get('roundCap', true);
  36766. var drawBackground = seriesModel.get('showBackground', true);
  36767. var backgroundModel = seriesModel.getModel('backgroundStyle');
  36768. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  36769. var bgEls = [];
  36770. var oldBgEls = this._backgroundEls;
  36771. var isInitSort = payload && payload.isInitSort;
  36772. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  36773. function createBackground(dataIndex) {
  36774. var bgLayout = getLayout[coord.type](data, dataIndex);
  36775. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  36776. bgEl.useStyle(backgroundModel.getItemStyle());
  36777. // Only cartesian2d support borderRadius.
  36778. if (coord.type === 'cartesian2d') {
  36779. bgEl.setShape('r', barBorderRadius);
  36780. } else {
  36781. bgEl.setShape('cornerRadius', barBorderRadius);
  36782. }
  36783. bgEls[dataIndex] = bgEl;
  36784. return bgEl;
  36785. }
  36786. data.diff(oldData).add(function (dataIndex) {
  36787. var itemModel = data.getItemModel(dataIndex);
  36788. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36789. if (drawBackground) {
  36790. createBackground(dataIndex);
  36791. }
  36792. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  36793. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  36794. return;
  36795. }
  36796. var isClipped = false;
  36797. if (needsClip) {
  36798. // Clip will modify the layout params.
  36799. // And return a boolean to determine if the shape are fully clipped.
  36800. isClipped = clip[coord.type](coordSysClipArea, layout);
  36801. }
  36802. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  36803. if (realtimeSortCfg) {
  36804. /**
  36805. * Force label animation because even if the element is
  36806. * ignored because it's clipped, it may not be clipped after
  36807. * changing order. Then, if not using forceLabelAnimation,
  36808. * the label animation was never started, in which case,
  36809. * the label will be the final value and doesn't have label
  36810. * animation.
  36811. */
  36812. el.forceLabelAnimation = true;
  36813. }
  36814. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  36815. if (isInitSort) {
  36816. el.attr({
  36817. shape: layout
  36818. });
  36819. } else if (realtimeSortCfg) {
  36820. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  36821. } else {
  36822. initProps(el, {
  36823. shape: layout
  36824. }, seriesModel, dataIndex);
  36825. }
  36826. data.setItemGraphicEl(dataIndex, el);
  36827. group.add(el);
  36828. el.ignore = isClipped;
  36829. }).update(function (newIndex, oldIndex) {
  36830. var itemModel = data.getItemModel(newIndex);
  36831. var layout = getLayout[coord.type](data, newIndex, itemModel);
  36832. if (drawBackground) {
  36833. var bgEl = void 0;
  36834. if (oldBgEls.length === 0) {
  36835. bgEl = createBackground(oldIndex);
  36836. } else {
  36837. bgEl = oldBgEls[oldIndex];
  36838. bgEl.useStyle(backgroundModel.getItemStyle());
  36839. // Only cartesian2d support borderRadius.
  36840. if (coord.type === 'cartesian2d') {
  36841. bgEl.setShape('r', barBorderRadius);
  36842. } else {
  36843. bgEl.setShape('cornerRadius', barBorderRadius);
  36844. }
  36845. bgEls[newIndex] = bgEl;
  36846. }
  36847. var bgLayout = getLayout[coord.type](data, newIndex);
  36848. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  36849. updateProps(bgEl, {
  36850. shape: shape
  36851. }, animationModel, newIndex);
  36852. }
  36853. var el = oldData.getItemGraphicEl(oldIndex);
  36854. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  36855. group.remove(el);
  36856. return;
  36857. }
  36858. var isClipped = false;
  36859. if (needsClip) {
  36860. isClipped = clip[coord.type](coordSysClipArea, layout);
  36861. if (isClipped) {
  36862. group.remove(el);
  36863. }
  36864. }
  36865. if (!el) {
  36866. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  36867. } else {
  36868. saveOldStyle(el);
  36869. }
  36870. if (realtimeSortCfg) {
  36871. el.forceLabelAnimation = true;
  36872. }
  36873. if (isChangeOrder) {
  36874. var textEl = el.getTextContent();
  36875. if (textEl) {
  36876. var labelInnerStore = labelInner(textEl);
  36877. if (labelInnerStore.prevValue != null) {
  36878. /**
  36879. * Set preValue to be value so that no new label
  36880. * should be started, otherwise, it will take a full
  36881. * `animationDurationUpdate` time to finish the
  36882. * animation, which is not expected.
  36883. */
  36884. labelInnerStore.prevValue = labelInnerStore.value;
  36885. }
  36886. }
  36887. }
  36888. // Not change anything if only order changed.
  36889. // Especially not change label.
  36890. else {
  36891. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  36892. }
  36893. if (isInitSort) {
  36894. el.attr({
  36895. shape: layout
  36896. });
  36897. } else if (realtimeSortCfg) {
  36898. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  36899. } else {
  36900. updateProps(el, {
  36901. shape: layout
  36902. }, seriesModel, newIndex, null);
  36903. }
  36904. data.setItemGraphicEl(newIndex, el);
  36905. el.ignore = isClipped;
  36906. group.add(el);
  36907. }).remove(function (dataIndex) {
  36908. var el = oldData.getItemGraphicEl(dataIndex);
  36909. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  36910. }).execute();
  36911. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  36912. bgGroup.removeAll();
  36913. for (var i = 0; i < bgEls.length; ++i) {
  36914. bgGroup.add(bgEls[i]);
  36915. }
  36916. group.add(bgGroup);
  36917. this._backgroundEls = bgEls;
  36918. this._data = data;
  36919. };
  36920. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  36921. this._clear();
  36922. createLarge(seriesModel, this.group);
  36923. this._updateLargeClip(seriesModel);
  36924. };
  36925. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  36926. this._removeBackground();
  36927. createLarge(seriesModel, this.group, this._progressiveEls, true);
  36928. };
  36929. BarView.prototype._updateLargeClip = function (seriesModel) {
  36930. // Use clipPath in large mode.
  36931. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  36932. var group = this.group;
  36933. if (clipPath) {
  36934. group.setClipPath(clipPath);
  36935. } else {
  36936. group.removeClipPath();
  36937. }
  36938. };
  36939. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  36940. var _this = this;
  36941. // If no data in the first frame, wait for data to initSort
  36942. if (!data.count()) {
  36943. return;
  36944. }
  36945. var baseAxis = realtimeSortCfg.baseAxis;
  36946. if (this._isFirstFrame) {
  36947. this._dispatchInitSort(data, realtimeSortCfg, api);
  36948. this._isFirstFrame = false;
  36949. } else {
  36950. var orderMapping_1 = function (idx) {
  36951. var el = data.getItemGraphicEl(idx);
  36952. var shape = el && el.shape;
  36953. return shape &&
  36954. // The result should be consistent with the initial sort by data value.
  36955. // Do not support the case that both positive and negative exist.
  36956. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width)
  36957. // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  36958. || 0;
  36959. };
  36960. this._onRendered = function () {
  36961. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  36962. };
  36963. api.getZr().on('rendered', this._onRendered);
  36964. }
  36965. };
  36966. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  36967. var info = [];
  36968. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  36969. var mappedValue = orderMapping(dataIdx);
  36970. mappedValue = mappedValue == null ? NaN : mappedValue;
  36971. info.push({
  36972. dataIndex: dataIdx,
  36973. mappedValue: mappedValue,
  36974. ordinalNumber: ordinalNumber
  36975. });
  36976. });
  36977. info.sort(function (a, b) {
  36978. // If NaN, it will be treated as min val.
  36979. return b.mappedValue - a.mappedValue;
  36980. });
  36981. return {
  36982. ordinalNumbers: map(info, function (item) {
  36983. return item.ordinalNumber;
  36984. })
  36985. };
  36986. };
  36987. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  36988. var scale = baseAxis.scale;
  36989. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  36990. var lastValue = Number.MAX_VALUE;
  36991. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  36992. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  36993. var value = rawIdx < 0
  36994. // If some tick have no bar, the tick will be treated as min.
  36995. ? Number.MIN_VALUE
  36996. // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  36997. : orderMapping(data.indexOfRawIndex(rawIdx));
  36998. if (value > lastValue) {
  36999. return true;
  37000. }
  37001. lastValue = value;
  37002. }
  37003. return false;
  37004. };
  37005. /*
  37006. * Consider the case when A and B changed order, whose representing
  37007. * bars are both out of sight, we don't wish to trigger reorder action
  37008. * as long as the order in the view doesn't change.
  37009. */
  37010. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  37011. var scale = baseAxis.scale;
  37012. var extent = scale.getExtent();
  37013. var tickNum = Math.max(0, extent[0]);
  37014. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  37015. for (; tickNum <= tickMax; ++tickNum) {
  37016. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  37017. return true;
  37018. }
  37019. }
  37020. };
  37021. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  37022. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  37023. return;
  37024. }
  37025. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  37026. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  37027. this._removeOnRenderedListener(api);
  37028. api.dispatchAction({
  37029. type: 'changeAxisOrder',
  37030. componentType: baseAxis.dim + 'Axis',
  37031. axisId: baseAxis.index,
  37032. sortInfo: sortInfo
  37033. });
  37034. }
  37035. };
  37036. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  37037. var baseAxis = realtimeSortCfg.baseAxis;
  37038. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  37039. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  37040. });
  37041. api.dispatchAction({
  37042. type: 'changeAxisOrder',
  37043. componentType: baseAxis.dim + 'Axis',
  37044. isInitSort: true,
  37045. axisId: baseAxis.index,
  37046. sortInfo: sortResult
  37047. });
  37048. };
  37049. BarView.prototype.remove = function (ecModel, api) {
  37050. this._clear(this._model);
  37051. this._removeOnRenderedListener(api);
  37052. };
  37053. BarView.prototype.dispose = function (ecModel, api) {
  37054. this._removeOnRenderedListener(api);
  37055. };
  37056. BarView.prototype._removeOnRenderedListener = function (api) {
  37057. if (this._onRendered) {
  37058. api.getZr().off('rendered', this._onRendered);
  37059. this._onRendered = null;
  37060. }
  37061. };
  37062. BarView.prototype._clear = function (model) {
  37063. var group = this.group;
  37064. var data = this._data;
  37065. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  37066. this._removeBackground();
  37067. this._backgroundEls = [];
  37068. data.eachItemGraphicEl(function (el) {
  37069. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  37070. });
  37071. } else {
  37072. group.removeAll();
  37073. }
  37074. this._data = null;
  37075. this._isFirstFrame = true;
  37076. };
  37077. BarView.prototype._removeBackground = function () {
  37078. this.group.remove(this._backgroundGroup);
  37079. this._backgroundGroup = null;
  37080. };
  37081. BarView.type = 'bar';
  37082. return BarView;
  37083. }(ChartView);
  37084. var clip = {
  37085. cartesian2d: function (coordSysBoundingRect, layout) {
  37086. var signWidth = layout.width < 0 ? -1 : 1;
  37087. var signHeight = layout.height < 0 ? -1 : 1;
  37088. // Needs positive width and height
  37089. if (signWidth < 0) {
  37090. layout.x += layout.width;
  37091. layout.width = -layout.width;
  37092. }
  37093. if (signHeight < 0) {
  37094. layout.y += layout.height;
  37095. layout.height = -layout.height;
  37096. }
  37097. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  37098. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  37099. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  37100. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  37101. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  37102. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  37103. var xClipped = x2 < x;
  37104. var yClipped = y2 < y;
  37105. // When xClipped or yClipped, the element will be marked as `ignore`.
  37106. // But we should also place the element at the edge of the coord sys bounding rect.
  37107. // Because if data changed and the bar shows again, its transition animation
  37108. // will begin at this place.
  37109. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  37110. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  37111. layout.width = xClipped ? 0 : x2 - x;
  37112. layout.height = yClipped ? 0 : y2 - y;
  37113. // Reverse back
  37114. if (signWidth < 0) {
  37115. layout.x += layout.width;
  37116. layout.width = -layout.width;
  37117. }
  37118. if (signHeight < 0) {
  37119. layout.y += layout.height;
  37120. layout.height = -layout.height;
  37121. }
  37122. return xClipped || yClipped;
  37123. },
  37124. polar: function (coordSysClipArea, layout) {
  37125. var signR = layout.r0 <= layout.r ? 1 : -1;
  37126. // Make sure r is larger than r0
  37127. if (signR < 0) {
  37128. var tmp = layout.r;
  37129. layout.r = layout.r0;
  37130. layout.r0 = tmp;
  37131. }
  37132. var r = mathMin$6(layout.r, coordSysClipArea.r);
  37133. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  37134. layout.r = r;
  37135. layout.r0 = r0;
  37136. var clipped = r - r0 < 0;
  37137. // Reverse back
  37138. if (signR < 0) {
  37139. var tmp = layout.r;
  37140. layout.r = layout.r0;
  37141. layout.r0 = tmp;
  37142. }
  37143. return clipped;
  37144. }
  37145. };
  37146. var elementCreator = {
  37147. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  37148. var rect = new Rect({
  37149. shape: extend({}, layout),
  37150. z2: 1
  37151. });
  37152. rect.__dataIndex = newIndex;
  37153. rect.name = 'item';
  37154. if (animationModel) {
  37155. var rectShape = rect.shape;
  37156. var animateProperty = isHorizontal ? 'height' : 'width';
  37157. rectShape[animateProperty] = 0;
  37158. }
  37159. return rect;
  37160. },
  37161. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  37162. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  37163. var sector = new ShapeClass({
  37164. shape: layout,
  37165. z2: 1
  37166. });
  37167. sector.name = 'item';
  37168. var positionMap = createPolarPositionMapping(isRadial);
  37169. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  37170. isRoundCap: ShapeClass === SausagePath
  37171. });
  37172. // Animation
  37173. if (animationModel) {
  37174. var sectorShape = sector.shape;
  37175. var animateProperty = isRadial ? 'r' : 'endAngle';
  37176. var animateTarget = {};
  37177. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  37178. animateTarget[animateProperty] = layout[animateProperty];
  37179. (isUpdate ? updateProps : initProps)(sector, {
  37180. shape: animateTarget
  37181. // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  37182. }, animationModel);
  37183. }
  37184. return sector;
  37185. }
  37186. };
  37187. function shouldRealtimeSort(seriesModel, coordSys) {
  37188. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  37189. var baseAxis = coordSys.getBaseAxis();
  37190. if ("development" !== 'production') {
  37191. if (realtimeSortOption) {
  37192. if (baseAxis.type !== 'category') {
  37193. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  37194. }
  37195. if (coordSys.type !== 'cartesian2d') {
  37196. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  37197. }
  37198. }
  37199. }
  37200. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  37201. return {
  37202. baseAxis: baseAxis,
  37203. otherAxis: coordSys.getOtherAxis(baseAxis)
  37204. };
  37205. }
  37206. }
  37207. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  37208. var seriesTarget;
  37209. var axisTarget;
  37210. if (isHorizontal) {
  37211. axisTarget = {
  37212. x: layout.x,
  37213. width: layout.width
  37214. };
  37215. seriesTarget = {
  37216. y: layout.y,
  37217. height: layout.height
  37218. };
  37219. } else {
  37220. axisTarget = {
  37221. y: layout.y,
  37222. height: layout.height
  37223. };
  37224. seriesTarget = {
  37225. x: layout.x,
  37226. width: layout.width
  37227. };
  37228. }
  37229. if (!isChangeOrder) {
  37230. // Keep the original growth animation if only axis order changed.
  37231. // Not start a new animation.
  37232. (isUpdate ? updateProps : initProps)(el, {
  37233. shape: seriesTarget
  37234. }, seriesAnimationModel, newIndex, null);
  37235. }
  37236. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  37237. (isUpdate ? updateProps : initProps)(el, {
  37238. shape: axisTarget
  37239. }, axisAnimationModel, newIndex);
  37240. }
  37241. function checkPropertiesNotValid(obj, props) {
  37242. for (var i = 0; i < props.length; i++) {
  37243. if (!isFinite(obj[props[i]])) {
  37244. return true;
  37245. }
  37246. }
  37247. return false;
  37248. }
  37249. var rectPropties = ['x', 'y', 'width', 'height'];
  37250. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  37251. var isValidLayout = {
  37252. cartesian2d: function (layout) {
  37253. return !checkPropertiesNotValid(layout, rectPropties);
  37254. },
  37255. polar: function (layout) {
  37256. return !checkPropertiesNotValid(layout, polarPropties);
  37257. }
  37258. };
  37259. var getLayout = {
  37260. // itemModel is only used to get borderWidth, which is not needed
  37261. // when calculating bar background layout.
  37262. cartesian2d: function (data, dataIndex, itemModel) {
  37263. var layout = data.getItemLayout(dataIndex);
  37264. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
  37265. // fix layout with lineWidth
  37266. var signX = layout.width > 0 ? 1 : -1;
  37267. var signY = layout.height > 0 ? 1 : -1;
  37268. return {
  37269. x: layout.x + signX * fixedLineWidth / 2,
  37270. y: layout.y + signY * fixedLineWidth / 2,
  37271. width: layout.width - signX * fixedLineWidth,
  37272. height: layout.height - signY * fixedLineWidth
  37273. };
  37274. },
  37275. polar: function (data, dataIndex, itemModel) {
  37276. var layout = data.getItemLayout(dataIndex);
  37277. return {
  37278. cx: layout.cx,
  37279. cy: layout.cy,
  37280. r0: layout.r0,
  37281. r: layout.r,
  37282. startAngle: layout.startAngle,
  37283. endAngle: layout.endAngle,
  37284. clockwise: layout.clockwise
  37285. };
  37286. }
  37287. };
  37288. function isZeroOnPolar(layout) {
  37289. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  37290. }
  37291. function createPolarPositionMapping(isRadial) {
  37292. return function (isRadial) {
  37293. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  37294. return function (position) {
  37295. switch (position) {
  37296. case 'start':
  37297. case 'insideStart':
  37298. case 'end':
  37299. case 'insideEnd':
  37300. return position + arcOrAngle;
  37301. default:
  37302. return position;
  37303. }
  37304. };
  37305. }(isRadial);
  37306. }
  37307. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  37308. var style = data.getItemVisual(dataIndex, 'style');
  37309. if (!isPolar) {
  37310. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  37311. el.setShape('r', borderRadius);
  37312. } else if (!seriesModel.get('roundCap')) {
  37313. var sectorShape = el.shape;
  37314. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  37315. extend(sectorShape, cornerRadius);
  37316. el.setShape(sectorShape);
  37317. }
  37318. el.useStyle(style);
  37319. var cursorStyle = itemModel.getShallow('cursor');
  37320. cursorStyle && el.attr('cursor', cursorStyle);
  37321. var labelPositionOutside = isPolar ? isHorizontalOrRadial ? layout.r >= layout.r0 ? 'endArc' : 'startArc' : layout.endAngle >= layout.startAngle ? 'endAngle' : 'startAngle' : isHorizontalOrRadial ? layout.height >= 0 ? 'bottom' : 'top' : layout.width >= 0 ? 'right' : 'left';
  37322. var labelStatesModels = getLabelStatesModels(itemModel);
  37323. setLabelStyle(el, labelStatesModels, {
  37324. labelFetcher: seriesModel,
  37325. labelDataIndex: dataIndex,
  37326. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37327. inheritColor: style.fill,
  37328. defaultOpacity: style.opacity,
  37329. defaultOutsidePosition: labelPositionOutside
  37330. });
  37331. var label = el.getTextContent();
  37332. if (isPolar && label) {
  37333. var position = itemModel.get(['label', 'position']);
  37334. el.textConfig.inside = position === 'middle' ? true : null;
  37335. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  37336. }
  37337. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  37338. return getDefaultInterpolatedLabel(data, value);
  37339. });
  37340. var emphasisModel = itemModel.getModel(['emphasis']);
  37341. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  37342. setStatesStylesFromModel(el, itemModel);
  37343. if (isZeroOnPolar(layout)) {
  37344. el.style.fill = 'none';
  37345. el.style.stroke = 'none';
  37346. each(el.states, function (state) {
  37347. if (state.style) {
  37348. state.style.fill = state.style.stroke = 'none';
  37349. }
  37350. });
  37351. }
  37352. }
  37353. // In case width or height are too small.
  37354. function getLineWidth(itemModel, rawLayout) {
  37355. // Has no border.
  37356. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  37357. if (!borderColor || borderColor === 'none') {
  37358. return 0;
  37359. }
  37360. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0;
  37361. // width or height may be NaN for empty data
  37362. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  37363. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  37364. return Math.min(lineWidth, width, height);
  37365. }
  37366. var LagePathShape = /** @class */function () {
  37367. function LagePathShape() {}
  37368. return LagePathShape;
  37369. }();
  37370. var LargePath = /** @class */function (_super) {
  37371. __extends(LargePath, _super);
  37372. function LargePath(opts) {
  37373. var _this = _super.call(this, opts) || this;
  37374. _this.type = 'largeBar';
  37375. return _this;
  37376. }
  37377. LargePath.prototype.getDefaultShape = function () {
  37378. return new LagePathShape();
  37379. };
  37380. LargePath.prototype.buildPath = function (ctx, shape) {
  37381. // Drawing lines is more efficient than drawing
  37382. // a whole line or drawing rects.
  37383. var points = shape.points;
  37384. var baseDimIdx = this.baseDimIdx;
  37385. var valueDimIdx = 1 - this.baseDimIdx;
  37386. var startPoint = [];
  37387. var size = [];
  37388. var barWidth = this.barWidth;
  37389. for (var i = 0; i < points.length; i += 3) {
  37390. size[baseDimIdx] = barWidth;
  37391. size[valueDimIdx] = points[i + 2];
  37392. startPoint[baseDimIdx] = points[i + baseDimIdx];
  37393. startPoint[valueDimIdx] = points[i + valueDimIdx];
  37394. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  37395. }
  37396. };
  37397. return LargePath;
  37398. }(Path);
  37399. function createLarge(seriesModel, group, progressiveEls, incremental) {
  37400. // TODO support polar
  37401. var data = seriesModel.getData();
  37402. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  37403. var largeDataIndices = data.getLayout('largeDataIndices');
  37404. var barWidth = data.getLayout('size');
  37405. var backgroundModel = seriesModel.getModel('backgroundStyle');
  37406. var bgPoints = data.getLayout('largeBackgroundPoints');
  37407. if (bgPoints) {
  37408. var bgEl = new LargePath({
  37409. shape: {
  37410. points: bgPoints
  37411. },
  37412. incremental: !!incremental,
  37413. silent: true,
  37414. z2: 0
  37415. });
  37416. bgEl.baseDimIdx = baseDimIdx;
  37417. bgEl.largeDataIndices = largeDataIndices;
  37418. bgEl.barWidth = barWidth;
  37419. bgEl.useStyle(backgroundModel.getItemStyle());
  37420. group.add(bgEl);
  37421. progressiveEls && progressiveEls.push(bgEl);
  37422. }
  37423. var el = new LargePath({
  37424. shape: {
  37425. points: data.getLayout('largePoints')
  37426. },
  37427. incremental: !!incremental,
  37428. ignoreCoarsePointer: true,
  37429. z2: 1
  37430. });
  37431. el.baseDimIdx = baseDimIdx;
  37432. el.largeDataIndices = largeDataIndices;
  37433. el.barWidth = barWidth;
  37434. group.add(el);
  37435. el.useStyle(data.getVisual('style'));
  37436. // Enable tooltip and user mouse/touch event handlers.
  37437. getECData(el).seriesIndex = seriesModel.seriesIndex;
  37438. if (!seriesModel.get('silent')) {
  37439. el.on('mousedown', largePathUpdateDataIndex);
  37440. el.on('mousemove', largePathUpdateDataIndex);
  37441. }
  37442. progressiveEls && progressiveEls.push(el);
  37443. }
  37444. // Use throttle to avoid frequently traverse to find dataIndex.
  37445. var largePathUpdateDataIndex = throttle(function (event) {
  37446. var largePath = this;
  37447. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  37448. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  37449. }, 30, false);
  37450. function largePathFindDataIndex(largePath, x, y) {
  37451. var baseDimIdx = largePath.baseDimIdx;
  37452. var valueDimIdx = 1 - baseDimIdx;
  37453. var points = largePath.shape.points;
  37454. var largeDataIndices = largePath.largeDataIndices;
  37455. var startPoint = [];
  37456. var size = [];
  37457. var barWidth = largePath.barWidth;
  37458. for (var i = 0, len = points.length / 3; i < len; i++) {
  37459. var ii = i * 3;
  37460. size[baseDimIdx] = barWidth;
  37461. size[valueDimIdx] = points[ii + 2];
  37462. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  37463. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  37464. if (size[valueDimIdx] < 0) {
  37465. startPoint[valueDimIdx] += size[valueDimIdx];
  37466. size[valueDimIdx] = -size[valueDimIdx];
  37467. }
  37468. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  37469. return largeDataIndices[i];
  37470. }
  37471. }
  37472. return -1;
  37473. }
  37474. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  37475. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  37476. var rectShape = layout;
  37477. var coordLayout = coord.getArea();
  37478. return {
  37479. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  37480. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  37481. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  37482. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  37483. };
  37484. } else {
  37485. var coordLayout = coord.getArea();
  37486. var sectorShape = layout;
  37487. return {
  37488. cx: coordLayout.cx,
  37489. cy: coordLayout.cy,
  37490. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  37491. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  37492. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  37493. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  37494. };
  37495. }
  37496. }
  37497. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  37498. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  37499. return new ElementClz({
  37500. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  37501. silent: true,
  37502. z2: 0
  37503. });
  37504. }
  37505. function install$2(registers) {
  37506. registers.registerChartView(BarView);
  37507. registers.registerSeriesModel(BarSeriesModel);
  37508. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  37509. // Do layout after other overall layout, which can prepare some information.
  37510. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar'));
  37511. // Down sample after filter
  37512. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  37513. /**
  37514. * @payload
  37515. * @property {string} [componentType=series]
  37516. * @property {number} [dx]
  37517. * @property {number} [dy]
  37518. * @property {number} [zoom]
  37519. * @property {number} [originX]
  37520. * @property {number} [originY]
  37521. */
  37522. registers.registerAction({
  37523. type: 'changeAxisOrder',
  37524. event: 'changeAxisOrder',
  37525. update: 'update'
  37526. }, function (payload, ecModel) {
  37527. var componentType = payload.componentType || 'series';
  37528. ecModel.eachComponent({
  37529. mainType: componentType,
  37530. query: payload
  37531. }, function (componentModel) {
  37532. if (payload.sortInfo) {
  37533. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  37534. }
  37535. });
  37536. });
  37537. }
  37538. var PI2$6 = Math.PI * 2;
  37539. var RADIAN = Math.PI / 180;
  37540. function getViewRect(seriesModel, api) {
  37541. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  37542. width: api.getWidth(),
  37543. height: api.getHeight()
  37544. });
  37545. }
  37546. function getBasicPieLayout(seriesModel, api) {
  37547. var viewRect = getViewRect(seriesModel, api);
  37548. // center can be string or number when coordinateSystem is specified
  37549. var center = seriesModel.get('center');
  37550. var radius = seriesModel.get('radius');
  37551. if (!isArray(radius)) {
  37552. radius = [0, radius];
  37553. }
  37554. var width = parsePercent$1(viewRect.width, api.getWidth());
  37555. var height = parsePercent$1(viewRect.height, api.getHeight());
  37556. var size = Math.min(width, height);
  37557. var r0 = parsePercent$1(radius[0], size / 2);
  37558. var r = parsePercent$1(radius[1], size / 2);
  37559. var cx;
  37560. var cy;
  37561. var coordSys = seriesModel.coordinateSystem;
  37562. if (coordSys) {
  37563. // percentage is not allowed when coordinate system is specified
  37564. var point = coordSys.dataToPoint(center);
  37565. cx = point[0] || 0;
  37566. cy = point[1] || 0;
  37567. } else {
  37568. if (!isArray(center)) {
  37569. center = [center, center];
  37570. }
  37571. cx = parsePercent$1(center[0], width) + viewRect.x;
  37572. cy = parsePercent$1(center[1], height) + viewRect.y;
  37573. }
  37574. return {
  37575. cx: cx,
  37576. cy: cy,
  37577. r0: r0,
  37578. r: r
  37579. };
  37580. }
  37581. function pieLayout(seriesType, ecModel, api) {
  37582. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37583. var data = seriesModel.getData();
  37584. var valueDim = data.mapDimension('value');
  37585. var viewRect = getViewRect(seriesModel, api);
  37586. var _a = getBasicPieLayout(seriesModel, api),
  37587. cx = _a.cx,
  37588. cy = _a.cy,
  37589. r = _a.r,
  37590. r0 = _a.r0;
  37591. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  37592. var endAngle = seriesModel.get('endAngle');
  37593. var padAngle = seriesModel.get('padAngle') * RADIAN;
  37594. endAngle = endAngle === 'auto' ? startAngle - PI2$6 : -endAngle * RADIAN;
  37595. var minAngle = seriesModel.get('minAngle') * RADIAN;
  37596. var minAndPadAngle = minAngle + padAngle;
  37597. var validDataCount = 0;
  37598. data.each(valueDim, function (value) {
  37599. !isNaN(value) && validDataCount++;
  37600. });
  37601. var sum = data.getSum(valueDim);
  37602. // Sum may be 0
  37603. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  37604. var clockwise = seriesModel.get('clockwise');
  37605. var roseType = seriesModel.get('roseType');
  37606. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  37607. // [0...max]
  37608. var extent = data.getDataExtent(valueDim);
  37609. extent[0] = 0;
  37610. var dir = clockwise ? 1 : -1;
  37611. var angles = [startAngle, endAngle];
  37612. var halfPadAngle = dir * padAngle / 2;
  37613. normalizeArcAngles(angles, !clockwise);
  37614. startAngle = angles[0], endAngle = angles[1];
  37615. var layoutData = getSeriesLayoutData(seriesModel);
  37616. layoutData.startAngle = startAngle;
  37617. layoutData.endAngle = endAngle;
  37618. layoutData.clockwise = clockwise;
  37619. var angleRange = Math.abs(endAngle - startAngle);
  37620. // In the case some sector angle is smaller than minAngle
  37621. var restAngle = angleRange;
  37622. var valueSumLargerThanMinAngle = 0;
  37623. var currentAngle = startAngle;
  37624. data.setLayout({
  37625. viewRect: viewRect,
  37626. r: r
  37627. });
  37628. data.each(valueDim, function (value, idx) {
  37629. var angle;
  37630. if (isNaN(value)) {
  37631. data.setItemLayout(idx, {
  37632. angle: NaN,
  37633. startAngle: NaN,
  37634. endAngle: NaN,
  37635. clockwise: clockwise,
  37636. cx: cx,
  37637. cy: cy,
  37638. r0: r0,
  37639. r: roseType ? NaN : r
  37640. });
  37641. return;
  37642. }
  37643. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  37644. if (roseType !== 'area') {
  37645. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  37646. } else {
  37647. angle = angleRange / validDataCount;
  37648. }
  37649. if (angle < minAndPadAngle) {
  37650. angle = minAndPadAngle;
  37651. restAngle -= minAndPadAngle;
  37652. } else {
  37653. valueSumLargerThanMinAngle += value;
  37654. }
  37655. var endAngle = currentAngle + dir * angle;
  37656. // calculate display angle
  37657. var actualStartAngle = 0;
  37658. var actualEndAngle = 0;
  37659. if (padAngle > angle) {
  37660. actualStartAngle = currentAngle + dir * angle / 2;
  37661. actualEndAngle = actualStartAngle;
  37662. } else {
  37663. actualStartAngle = currentAngle + halfPadAngle;
  37664. actualEndAngle = endAngle - halfPadAngle;
  37665. }
  37666. data.setItemLayout(idx, {
  37667. angle: angle,
  37668. startAngle: actualStartAngle,
  37669. endAngle: actualEndAngle,
  37670. clockwise: clockwise,
  37671. cx: cx,
  37672. cy: cy,
  37673. r0: r0,
  37674. r: roseType ? linearMap(value, extent, [r0, r]) : r
  37675. });
  37676. currentAngle = endAngle;
  37677. });
  37678. // Some sector is constrained by minAngle and padAngle
  37679. // Rest sectors needs recalculate angle
  37680. if (restAngle < PI2$6 && validDataCount) {
  37681. // Average the angle if rest angle is not enough after all angles is
  37682. // Constrained by minAngle and padAngle
  37683. if (restAngle <= 1e-3) {
  37684. var angle_1 = angleRange / validDataCount;
  37685. data.each(valueDim, function (value, idx) {
  37686. if (!isNaN(value)) {
  37687. var layout_1 = data.getItemLayout(idx);
  37688. layout_1.angle = angle_1;
  37689. var actualStartAngle = 0;
  37690. var actualEndAngle = 0;
  37691. if (angle_1 < padAngle) {
  37692. actualStartAngle = startAngle + dir * (idx + 1 / 2) * angle_1;
  37693. actualEndAngle = actualStartAngle;
  37694. } else {
  37695. actualStartAngle = startAngle + dir * idx * angle_1 + halfPadAngle;
  37696. actualEndAngle = startAngle + dir * (idx + 1) * angle_1 - halfPadAngle;
  37697. }
  37698. layout_1.startAngle = actualStartAngle;
  37699. layout_1.endAngle = actualEndAngle;
  37700. }
  37701. });
  37702. } else {
  37703. unitRadian = restAngle / valueSumLargerThanMinAngle;
  37704. currentAngle = startAngle;
  37705. data.each(valueDim, function (value, idx) {
  37706. if (!isNaN(value)) {
  37707. var layout_2 = data.getItemLayout(idx);
  37708. var angle = layout_2.angle === minAndPadAngle ? minAndPadAngle : value * unitRadian;
  37709. var actualStartAngle = 0;
  37710. var actualEndAngle = 0;
  37711. if (angle < padAngle) {
  37712. actualStartAngle = currentAngle + dir * angle / 2;
  37713. actualEndAngle = actualStartAngle;
  37714. } else {
  37715. actualStartAngle = currentAngle + halfPadAngle;
  37716. actualEndAngle = currentAngle + dir * angle - halfPadAngle;
  37717. }
  37718. layout_2.startAngle = actualStartAngle;
  37719. layout_2.endAngle = actualEndAngle;
  37720. currentAngle += dir * angle;
  37721. }
  37722. });
  37723. }
  37724. }
  37725. });
  37726. }
  37727. var getSeriesLayoutData = makeInner();
  37728. /*
  37729. * Licensed to the Apache Software Foundation (ASF) under one
  37730. * or more contributor license agreements. See the NOTICE file
  37731. * distributed with this work for additional information
  37732. * regarding copyright ownership. The ASF licenses this file
  37733. * to you under the Apache License, Version 2.0 (the
  37734. * "License"); you may not use this file except in compliance
  37735. * with the License. You may obtain a copy of the License at
  37736. *
  37737. * http://www.apache.org/licenses/LICENSE-2.0
  37738. *
  37739. * Unless required by applicable law or agreed to in writing,
  37740. * software distributed under the License is distributed on an
  37741. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37742. * KIND, either express or implied. See the License for the
  37743. * specific language governing permissions and limitations
  37744. * under the License.
  37745. */
  37746. /**
  37747. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37748. */
  37749. /*
  37750. * Licensed to the Apache Software Foundation (ASF) under one
  37751. * or more contributor license agreements. See the NOTICE file
  37752. * distributed with this work for additional information
  37753. * regarding copyright ownership. The ASF licenses this file
  37754. * to you under the Apache License, Version 2.0 (the
  37755. * "License"); you may not use this file except in compliance
  37756. * with the License. You may obtain a copy of the License at
  37757. *
  37758. * http://www.apache.org/licenses/LICENSE-2.0
  37759. *
  37760. * Unless required by applicable law or agreed to in writing,
  37761. * software distributed under the License is distributed on an
  37762. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37763. * KIND, either express or implied. See the License for the
  37764. * specific language governing permissions and limitations
  37765. * under the License.
  37766. */
  37767. function dataFilter(seriesType) {
  37768. return {
  37769. seriesType: seriesType,
  37770. reset: function (seriesModel, ecModel) {
  37771. var legendModels = ecModel.findComponents({
  37772. mainType: 'legend'
  37773. });
  37774. if (!legendModels || !legendModels.length) {
  37775. return;
  37776. }
  37777. var data = seriesModel.getData();
  37778. data.filterSelf(function (idx) {
  37779. var name = data.getName(idx);
  37780. // If in any legend component the status is not selected.
  37781. for (var i = 0; i < legendModels.length; i++) {
  37782. // @ts-ignore FIXME: LegendModel
  37783. if (!legendModels[i].isSelected(name)) {
  37784. return false;
  37785. }
  37786. }
  37787. return true;
  37788. });
  37789. }
  37790. };
  37791. }
  37792. var RADIAN$1 = Math.PI / 180;
  37793. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  37794. if (list.length < 2) {
  37795. return;
  37796. }
  37797. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  37798. var rB = semi.rB;
  37799. var rB2 = rB * rB;
  37800. for (var i = 0; i < semi.list.length; i++) {
  37801. var item = semi.list[i];
  37802. var dy = Math.abs(item.label.y - cy);
  37803. // horizontal r is always same with original r because x is not changed.
  37804. var rA = r + item.len;
  37805. var rA2 = rA * rA;
  37806. // Use ellipse implicit function to calculate x
  37807. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  37808. var newX = cx + (dx + item.len2) * dir;
  37809. var deltaX = newX - item.label.x;
  37810. var newTargetWidth = item.targetTextWidth - deltaX * dir;
  37811. // text x is changed, so need to recalculate width.
  37812. constrainTextWidth(item, newTargetWidth, true);
  37813. item.label.x = newX;
  37814. }
  37815. }
  37816. // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  37817. function recalculateX(items) {
  37818. // Extremes of
  37819. var topSemi = {
  37820. list: [],
  37821. maxY: 0
  37822. };
  37823. var bottomSemi = {
  37824. list: [],
  37825. maxY: 0
  37826. };
  37827. for (var i = 0; i < items.length; i++) {
  37828. if (items[i].labelAlignTo !== 'none') {
  37829. continue;
  37830. }
  37831. var item = items[i];
  37832. var semi = item.label.y > cy ? bottomSemi : topSemi;
  37833. var dy = Math.abs(item.label.y - cy);
  37834. if (dy >= semi.maxY) {
  37835. var dx = item.label.x - cx - item.len2 * dir;
  37836. // horizontal r is always same with original r because x is not changed.
  37837. var rA = r + item.len;
  37838. // Canculate rB based on the topest / bottemest label.
  37839. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  37840. semi.rB = rB;
  37841. semi.maxY = dy;
  37842. }
  37843. semi.list.push(item);
  37844. }
  37845. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  37846. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  37847. }
  37848. var len = list.length;
  37849. for (var i = 0; i < len; i++) {
  37850. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  37851. var dx = list[i].label.x - farthestX;
  37852. list[i].linePoints[1][0] += dx;
  37853. list[i].label.x = farthestX;
  37854. }
  37855. }
  37856. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  37857. recalculateX(list);
  37858. }
  37859. }
  37860. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  37861. var leftList = [];
  37862. var rightList = [];
  37863. var leftmostX = Number.MAX_VALUE;
  37864. var rightmostX = -Number.MAX_VALUE;
  37865. for (var i = 0; i < labelLayoutList.length; i++) {
  37866. var label = labelLayoutList[i].label;
  37867. if (isPositionCenter(labelLayoutList[i])) {
  37868. continue;
  37869. }
  37870. if (label.x < cx) {
  37871. leftmostX = Math.min(leftmostX, label.x);
  37872. leftList.push(labelLayoutList[i]);
  37873. } else {
  37874. rightmostX = Math.max(rightmostX, label.x);
  37875. rightList.push(labelLayoutList[i]);
  37876. }
  37877. }
  37878. for (var i = 0; i < labelLayoutList.length; i++) {
  37879. var layout = labelLayoutList[i];
  37880. if (!isPositionCenter(layout) && layout.linePoints) {
  37881. if (layout.labelStyleWidth != null) {
  37882. continue;
  37883. }
  37884. var label = layout.label;
  37885. var linePoints = layout.linePoints;
  37886. var targetTextWidth = void 0;
  37887. if (layout.labelAlignTo === 'edge') {
  37888. if (label.x < cx) {
  37889. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  37890. } else {
  37891. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  37892. }
  37893. } else if (layout.labelAlignTo === 'labelLine') {
  37894. if (label.x < cx) {
  37895. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  37896. } else {
  37897. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  37898. }
  37899. } else {
  37900. if (label.x < cx) {
  37901. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  37902. } else {
  37903. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  37904. }
  37905. }
  37906. layout.targetTextWidth = targetTextWidth;
  37907. constrainTextWidth(layout, targetTextWidth);
  37908. }
  37909. }
  37910. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  37911. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  37912. for (var i = 0; i < labelLayoutList.length; i++) {
  37913. var layout = labelLayoutList[i];
  37914. if (!isPositionCenter(layout) && layout.linePoints) {
  37915. var label = layout.label;
  37916. var linePoints = layout.linePoints;
  37917. var isAlignToEdge = layout.labelAlignTo === 'edge';
  37918. var padding = label.style.padding;
  37919. var paddingH = padding ? padding[1] + padding[3] : 0;
  37920. // textRect.width already contains paddingH if bgColor is set
  37921. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  37922. var realTextWidth = layout.rect.width + extraPaddingH;
  37923. var dist = linePoints[1][0] - linePoints[2][0];
  37924. if (isAlignToEdge) {
  37925. if (label.x < cx) {
  37926. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  37927. } else {
  37928. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  37929. }
  37930. } else {
  37931. if (label.x < cx) {
  37932. linePoints[2][0] = label.x + layout.labelDistance;
  37933. } else {
  37934. linePoints[2][0] = label.x - layout.labelDistance;
  37935. }
  37936. linePoints[1][0] = linePoints[2][0] + dist;
  37937. }
  37938. linePoints[1][1] = linePoints[2][1] = label.y;
  37939. }
  37940. }
  37941. }
  37942. /**
  37943. * Set max width of each label, and then wrap each label to the max width.
  37944. *
  37945. * @param layout label layout
  37946. * @param availableWidth max width for the label to display
  37947. * @param forceRecalculate recaculate the text layout even if the current width
  37948. * is smaller than `availableWidth`. This is useful when the text was previously
  37949. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  37950. * which case, previous wrapping should be redo.
  37951. */
  37952. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  37953. if (forceRecalculate === void 0) {
  37954. forceRecalculate = false;
  37955. }
  37956. if (layout.labelStyleWidth != null) {
  37957. // User-defined style.width has the highest priority.
  37958. return;
  37959. }
  37960. var label = layout.label;
  37961. var style = label.style;
  37962. var textRect = layout.rect;
  37963. var bgColor = style.backgroundColor;
  37964. var padding = style.padding;
  37965. var paddingH = padding ? padding[1] + padding[3] : 0;
  37966. var overflow = style.overflow;
  37967. // textRect.width already contains paddingH if bgColor is set
  37968. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  37969. if (availableWidth < oldOuterWidth || forceRecalculate) {
  37970. var oldHeight = textRect.height;
  37971. if (overflow && overflow.match('break')) {
  37972. // Temporarily set background to be null to calculate
  37973. // the bounding box without background.
  37974. label.setStyle('backgroundColor', null);
  37975. // Set constraining width
  37976. label.setStyle('width', availableWidth - paddingH);
  37977. // This is the real bounding box of the text without padding.
  37978. var innerRect = label.getBoundingRect();
  37979. label.setStyle('width', Math.ceil(innerRect.width));
  37980. label.setStyle('backgroundColor', bgColor);
  37981. } else {
  37982. var availableInnerWidth = availableWidth - paddingH;
  37983. var newWidth = availableWidth < oldOuterWidth
  37984. // Current text is too wide, use `availableWidth` as max width.
  37985. ? availableInnerWidth :
  37986. // Current available width is enough, but the text may have
  37987. // already been wrapped with a smaller available width.
  37988. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth
  37989. // Current available is larger than text width,
  37990. // so don't constrain width (otherwise it may have
  37991. // empty space in the background).
  37992. ? null
  37993. // Current available is smaller than text width, so
  37994. // use the current available width as constraining
  37995. // width.
  37996. : availableInnerWidth
  37997. // Current available width is enough, so no need to
  37998. // constrain.
  37999. : null;
  38000. label.setStyle('width', newWidth);
  38001. }
  38002. var newRect = label.getBoundingRect();
  38003. textRect.width = newRect.width;
  38004. var margin = (label.style.margin || 0) + 2.1;
  38005. textRect.height = newRect.height + margin;
  38006. textRect.y -= (textRect.height - oldHeight) / 2;
  38007. }
  38008. }
  38009. function isPositionCenter(sectorShape) {
  38010. // Not change x for center label
  38011. return sectorShape.position === 'center';
  38012. }
  38013. function pieLabelLayout(seriesModel) {
  38014. var data = seriesModel.getData();
  38015. var labelLayoutList = [];
  38016. var cx;
  38017. var cy;
  38018. var hasLabelRotate = false;
  38019. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  38020. var viewRect = data.getLayout('viewRect');
  38021. var r = data.getLayout('r');
  38022. var viewWidth = viewRect.width;
  38023. var viewLeft = viewRect.x;
  38024. var viewTop = viewRect.y;
  38025. var viewHeight = viewRect.height;
  38026. function setNotShow(el) {
  38027. el.ignore = true;
  38028. }
  38029. function isLabelShown(label) {
  38030. if (!label.ignore) {
  38031. return true;
  38032. }
  38033. for (var key in label.states) {
  38034. if (label.states[key].ignore === false) {
  38035. return true;
  38036. }
  38037. }
  38038. return false;
  38039. }
  38040. data.each(function (idx) {
  38041. var sector = data.getItemGraphicEl(idx);
  38042. var sectorShape = sector.shape;
  38043. var label = sector.getTextContent();
  38044. var labelLine = sector.getTextGuideLine();
  38045. var itemModel = data.getItemModel(idx);
  38046. var labelModel = itemModel.getModel('label');
  38047. // Use position in normal or emphasis
  38048. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  38049. var labelDistance = labelModel.get('distanceToLabelLine');
  38050. var labelAlignTo = labelModel.get('alignTo');
  38051. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  38052. var bleedMargin = labelModel.get('bleedMargin');
  38053. var labelLineModel = itemModel.getModel('labelLine');
  38054. var labelLineLen = labelLineModel.get('length');
  38055. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  38056. var labelLineLen2 = labelLineModel.get('length2');
  38057. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  38058. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  38059. each(label.states, setNotShow);
  38060. label.ignore = true;
  38061. if (labelLine) {
  38062. each(labelLine.states, setNotShow);
  38063. labelLine.ignore = true;
  38064. }
  38065. return;
  38066. }
  38067. if (!isLabelShown(label)) {
  38068. return;
  38069. }
  38070. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  38071. var nx = Math.cos(midAngle);
  38072. var ny = Math.sin(midAngle);
  38073. var textX;
  38074. var textY;
  38075. var linePoints;
  38076. var textAlign;
  38077. cx = sectorShape.cx;
  38078. cy = sectorShape.cy;
  38079. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  38080. if (labelPosition === 'center') {
  38081. textX = sectorShape.cx;
  38082. textY = sectorShape.cy;
  38083. textAlign = 'center';
  38084. } else {
  38085. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  38086. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  38087. textX = x1 + nx * 3;
  38088. textY = y1 + ny * 3;
  38089. if (!isLabelInside) {
  38090. // For roseType
  38091. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  38092. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  38093. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  38094. var y3 = y2;
  38095. if (labelAlignTo === 'edge') {
  38096. // Adjust textX because text align of edge is opposite
  38097. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  38098. } else {
  38099. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  38100. }
  38101. textY = y3;
  38102. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  38103. }
  38104. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  38105. }
  38106. var PI = Math.PI;
  38107. var labelRotate = 0;
  38108. var rotate = labelModel.get('rotate');
  38109. if (isNumber(rotate)) {
  38110. labelRotate = rotate * (PI / 180);
  38111. } else if (labelPosition === 'center') {
  38112. labelRotate = 0;
  38113. } else if (rotate === 'radial' || rotate === true) {
  38114. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  38115. labelRotate = radialAngle;
  38116. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  38117. var rad = Math.atan2(nx, ny);
  38118. if (rad < 0) {
  38119. rad = PI * 2 + rad;
  38120. }
  38121. var isDown = ny > 0;
  38122. if (isDown) {
  38123. rad = PI + rad;
  38124. }
  38125. labelRotate = rad - PI;
  38126. }
  38127. hasLabelRotate = !!labelRotate;
  38128. label.x = textX;
  38129. label.y = textY;
  38130. label.rotation = labelRotate;
  38131. label.setStyle({
  38132. verticalAlign: 'middle'
  38133. });
  38134. // Not sectorShape the inside label
  38135. if (!isLabelInside) {
  38136. var textRect = label.getBoundingRect().clone();
  38137. textRect.applyTransform(label.getComputedTransform());
  38138. // Text has a default 1px stroke. Exclude this.
  38139. var margin = (label.style.margin || 0) + 2.1;
  38140. textRect.y -= margin / 2;
  38141. textRect.height += margin;
  38142. labelLayoutList.push({
  38143. label: label,
  38144. labelLine: labelLine,
  38145. position: labelPosition,
  38146. len: labelLineLen,
  38147. len2: labelLineLen2,
  38148. minTurnAngle: labelLineModel.get('minTurnAngle'),
  38149. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  38150. surfaceNormal: new Point(nx, ny),
  38151. linePoints: linePoints,
  38152. textAlign: textAlign,
  38153. labelDistance: labelDistance,
  38154. labelAlignTo: labelAlignTo,
  38155. edgeDistance: edgeDistance,
  38156. bleedMargin: bleedMargin,
  38157. rect: textRect,
  38158. unconstrainedWidth: textRect.width,
  38159. labelStyleWidth: label.style.width
  38160. });
  38161. } else {
  38162. label.setStyle({
  38163. align: textAlign
  38164. });
  38165. var selectState = label.states.select;
  38166. if (selectState) {
  38167. selectState.x += label.x;
  38168. selectState.y += label.y;
  38169. }
  38170. }
  38171. sector.setTextConfig({
  38172. inside: isLabelInside
  38173. });
  38174. });
  38175. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  38176. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  38177. }
  38178. for (var i = 0; i < labelLayoutList.length; i++) {
  38179. var layout = labelLayoutList[i];
  38180. var label = layout.label;
  38181. var labelLine = layout.labelLine;
  38182. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  38183. if (label) {
  38184. label.setStyle({
  38185. align: layout.textAlign
  38186. });
  38187. if (notShowLabel) {
  38188. each(label.states, setNotShow);
  38189. label.ignore = true;
  38190. }
  38191. var selectState = label.states.select;
  38192. if (selectState) {
  38193. selectState.x += label.x;
  38194. selectState.y += label.y;
  38195. }
  38196. }
  38197. if (labelLine) {
  38198. var linePoints = layout.linePoints;
  38199. if (notShowLabel || !linePoints) {
  38200. each(labelLine.states, setNotShow);
  38201. labelLine.ignore = true;
  38202. } else {
  38203. limitTurnAngle(linePoints, layout.minTurnAngle);
  38204. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  38205. labelLine.setShape({
  38206. points: linePoints
  38207. });
  38208. // Set the anchor to the midpoint of sector
  38209. label.__hostTarget.textGuideLineConfig = {
  38210. anchor: new Point(linePoints[0][0], linePoints[0][1])
  38211. };
  38212. }
  38213. }
  38214. }
  38215. }
  38216. /**
  38217. * Piece of pie including Sector, Label, LabelLine
  38218. */
  38219. var PiePiece = /** @class */function (_super) {
  38220. __extends(PiePiece, _super);
  38221. function PiePiece(data, idx, startAngle) {
  38222. var _this = _super.call(this) || this;
  38223. _this.z2 = 2;
  38224. var text = new ZRText();
  38225. _this.setTextContent(text);
  38226. _this.updateData(data, idx, startAngle, true);
  38227. return _this;
  38228. }
  38229. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  38230. var sector = this;
  38231. var seriesModel = data.hostModel;
  38232. var itemModel = data.getItemModel(idx);
  38233. var emphasisModel = itemModel.getModel('emphasis');
  38234. var layout = data.getItemLayout(idx);
  38235. // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  38236. // see `setItemLayout` in `pieLayout.ts`.
  38237. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout);
  38238. // Ignore NaN data.
  38239. if (isNaN(sectorShape.startAngle)) {
  38240. // Use NaN shape to avoid drawing shape.
  38241. sector.setShape(sectorShape);
  38242. return;
  38243. }
  38244. if (firstCreate) {
  38245. sector.setShape(sectorShape);
  38246. var animationType = seriesModel.getShallow('animationType');
  38247. if (seriesModel.ecModel.ssr) {
  38248. // Use scale animation in SSR mode(opacity?)
  38249. // Because CSS SVG animation doesn't support very customized shape animation.
  38250. initProps(sector, {
  38251. scaleX: 0,
  38252. scaleY: 0
  38253. }, seriesModel, {
  38254. dataIndex: idx,
  38255. isFrom: true
  38256. });
  38257. sector.originX = sectorShape.cx;
  38258. sector.originY = sectorShape.cy;
  38259. } else if (animationType === 'scale') {
  38260. sector.shape.r = layout.r0;
  38261. initProps(sector, {
  38262. shape: {
  38263. r: layout.r
  38264. }
  38265. }, seriesModel, idx);
  38266. }
  38267. // Expansion
  38268. else {
  38269. if (startAngle != null) {
  38270. sector.setShape({
  38271. startAngle: startAngle,
  38272. endAngle: startAngle
  38273. });
  38274. initProps(sector, {
  38275. shape: {
  38276. startAngle: layout.startAngle,
  38277. endAngle: layout.endAngle
  38278. }
  38279. }, seriesModel, idx);
  38280. } else {
  38281. sector.shape.endAngle = layout.startAngle;
  38282. updateProps(sector, {
  38283. shape: {
  38284. endAngle: layout.endAngle
  38285. }
  38286. }, seriesModel, idx);
  38287. }
  38288. }
  38289. } else {
  38290. saveOldStyle(sector);
  38291. // Transition animation from the old shape
  38292. updateProps(sector, {
  38293. shape: sectorShape
  38294. }, seriesModel, idx);
  38295. }
  38296. sector.useStyle(data.getItemVisual(idx, 'style'));
  38297. setStatesStylesFromModel(sector, itemModel);
  38298. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38299. var offset = seriesModel.get('selectedOffset');
  38300. var dx = Math.cos(midAngle) * offset;
  38301. var dy = Math.sin(midAngle) * offset;
  38302. var cursorStyle = itemModel.getShallow('cursor');
  38303. cursorStyle && sector.attr('cursor', cursorStyle);
  38304. this._updateLabel(seriesModel, data, idx);
  38305. sector.ensureState('emphasis').shape = extend({
  38306. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  38307. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  38308. extend(sector.ensureState('select'), {
  38309. x: dx,
  38310. y: dy,
  38311. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  38312. });
  38313. extend(sector.ensureState('blur'), {
  38314. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  38315. });
  38316. var labelLine = sector.getTextGuideLine();
  38317. var labelText = sector.getTextContent();
  38318. labelLine && extend(labelLine.ensureState('select'), {
  38319. x: dx,
  38320. y: dy
  38321. });
  38322. // TODO: needs dx, dy in zrender?
  38323. extend(labelText.ensureState('select'), {
  38324. x: dx,
  38325. y: dy
  38326. });
  38327. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  38328. };
  38329. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  38330. var sector = this;
  38331. var itemModel = data.getItemModel(idx);
  38332. var labelLineModel = itemModel.getModel('labelLine');
  38333. var style = data.getItemVisual(idx, 'style');
  38334. var visualColor = style && style.fill;
  38335. var visualOpacity = style && style.opacity;
  38336. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  38337. labelFetcher: data.hostModel,
  38338. labelDataIndex: idx,
  38339. inheritColor: visualColor,
  38340. defaultOpacity: visualOpacity,
  38341. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  38342. });
  38343. var labelText = sector.getTextContent();
  38344. // Set textConfig on sector.
  38345. sector.setTextConfig({
  38346. // reset position, rotation
  38347. position: null,
  38348. rotation: null
  38349. });
  38350. // Make sure update style on labelText after setLabelStyle.
  38351. // Because setLabelStyle will replace a new style on it.
  38352. labelText.attr({
  38353. z2: 10
  38354. });
  38355. var labelPosition = seriesModel.get(['label', 'position']);
  38356. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  38357. sector.removeTextGuideLine();
  38358. } else {
  38359. var polyline = this.getTextGuideLine();
  38360. if (!polyline) {
  38361. polyline = new Polyline();
  38362. this.setTextGuideLine(polyline);
  38363. }
  38364. // Default use item visual color
  38365. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  38366. stroke: visualColor,
  38367. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  38368. });
  38369. }
  38370. };
  38371. return PiePiece;
  38372. }(Sector);
  38373. // Pie view
  38374. var PieView = /** @class */function (_super) {
  38375. __extends(PieView, _super);
  38376. function PieView() {
  38377. var _this = _super !== null && _super.apply(this, arguments) || this;
  38378. _this.ignoreLabelLineUpdate = true;
  38379. return _this;
  38380. }
  38381. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  38382. var data = seriesModel.getData();
  38383. var oldData = this._data;
  38384. var group = this.group;
  38385. var startAngle;
  38386. // First render
  38387. if (!oldData && data.count() > 0) {
  38388. var shape = data.getItemLayout(0);
  38389. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  38390. shape = data.getItemLayout(s);
  38391. }
  38392. if (shape) {
  38393. startAngle = shape.startAngle;
  38394. }
  38395. }
  38396. // remove empty-circle if it exists
  38397. if (this._emptyCircleSector) {
  38398. group.remove(this._emptyCircleSector);
  38399. }
  38400. // when all data are filtered, show lightgray empty circle
  38401. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  38402. var layoutData = getSeriesLayoutData(seriesModel);
  38403. var sector = new Sector({
  38404. shape: extend(getBasicPieLayout(seriesModel, api), layoutData)
  38405. });
  38406. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  38407. this._emptyCircleSector = sector;
  38408. group.add(sector);
  38409. }
  38410. data.diff(oldData).add(function (idx) {
  38411. var piePiece = new PiePiece(data, idx, startAngle);
  38412. data.setItemGraphicEl(idx, piePiece);
  38413. group.add(piePiece);
  38414. }).update(function (newIdx, oldIdx) {
  38415. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38416. piePiece.updateData(data, newIdx, startAngle);
  38417. piePiece.off('click');
  38418. group.add(piePiece);
  38419. data.setItemGraphicEl(newIdx, piePiece);
  38420. }).remove(function (idx) {
  38421. var piePiece = oldData.getItemGraphicEl(idx);
  38422. removeElementWithFadeOut(piePiece, seriesModel, idx);
  38423. }).execute();
  38424. pieLabelLayout(seriesModel);
  38425. // Always use initial animation.
  38426. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  38427. this._data = data;
  38428. }
  38429. };
  38430. PieView.prototype.dispose = function () {};
  38431. PieView.prototype.containPoint = function (point, seriesModel) {
  38432. var data = seriesModel.getData();
  38433. var itemLayout = data.getItemLayout(0);
  38434. if (itemLayout) {
  38435. var dx = point[0] - itemLayout.cx;
  38436. var dy = point[1] - itemLayout.cy;
  38437. var radius = Math.sqrt(dx * dx + dy * dy);
  38438. return radius <= itemLayout.r && radius >= itemLayout.r0;
  38439. }
  38440. };
  38441. PieView.type = 'pie';
  38442. return PieView;
  38443. }(ChartView);
  38444. /**
  38445. * [Usage]:
  38446. * (1)
  38447. * createListSimply(seriesModel, ['value']);
  38448. * (2)
  38449. * createListSimply(seriesModel, {
  38450. * coordDimensions: ['value'],
  38451. * dimensionsCount: 5
  38452. * });
  38453. */
  38454. function createSeriesDataSimply(seriesModel, opt, nameList) {
  38455. opt = isArray(opt) && {
  38456. coordDimensions: opt
  38457. } || extend({
  38458. encodeDefine: seriesModel.getEncode()
  38459. }, opt);
  38460. var source = seriesModel.getSource();
  38461. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  38462. var list = new SeriesData(dimensions, seriesModel);
  38463. list.initData(source, nameList);
  38464. return list;
  38465. }
  38466. /*
  38467. * Licensed to the Apache Software Foundation (ASF) under one
  38468. * or more contributor license agreements. See the NOTICE file
  38469. * distributed with this work for additional information
  38470. * regarding copyright ownership. The ASF licenses this file
  38471. * to you under the Apache License, Version 2.0 (the
  38472. * "License"); you may not use this file except in compliance
  38473. * with the License. You may obtain a copy of the License at
  38474. *
  38475. * http://www.apache.org/licenses/LICENSE-2.0
  38476. *
  38477. * Unless required by applicable law or agreed to in writing,
  38478. * software distributed under the License is distributed on an
  38479. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38480. * KIND, either express or implied. See the License for the
  38481. * specific language governing permissions and limitations
  38482. * under the License.
  38483. */
  38484. /**
  38485. * AUTO-GENERATED FILE. DO NOT MODIFY.
  38486. */
  38487. /*
  38488. * Licensed to the Apache Software Foundation (ASF) under one
  38489. * or more contributor license agreements. See the NOTICE file
  38490. * distributed with this work for additional information
  38491. * regarding copyright ownership. The ASF licenses this file
  38492. * to you under the Apache License, Version 2.0 (the
  38493. * "License"); you may not use this file except in compliance
  38494. * with the License. You may obtain a copy of the License at
  38495. *
  38496. * http://www.apache.org/licenses/LICENSE-2.0
  38497. *
  38498. * Unless required by applicable law or agreed to in writing,
  38499. * software distributed under the License is distributed on an
  38500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38501. * KIND, either express or implied. See the License for the
  38502. * specific language governing permissions and limitations
  38503. * under the License.
  38504. */
  38505. /**
  38506. * LegendVisualProvider is an bridge that pick encoded color from data and
  38507. * provide to the legend component.
  38508. */
  38509. var LegendVisualProvider = /** @class */function () {
  38510. function LegendVisualProvider(
  38511. // Function to get data after filtered. It stores all the encoding info
  38512. getDataWithEncodedVisual,
  38513. // Function to get raw data before filtered.
  38514. getRawData) {
  38515. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  38516. this._getRawData = getRawData;
  38517. }
  38518. LegendVisualProvider.prototype.getAllNames = function () {
  38519. var rawData = this._getRawData();
  38520. // We find the name from the raw data. In case it's filtered by the legend component.
  38521. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38522. return rawData.mapArray(rawData.getName);
  38523. };
  38524. LegendVisualProvider.prototype.containName = function (name) {
  38525. var rawData = this._getRawData();
  38526. return rawData.indexOfName(name) >= 0;
  38527. };
  38528. LegendVisualProvider.prototype.indexOfName = function (name) {
  38529. // Only get data when necessary.
  38530. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38531. // Invoking Series#getData immediately will throw an error.
  38532. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  38533. return dataWithEncodedVisual.indexOfName(name);
  38534. };
  38535. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  38536. // Get encoded visual properties from final filtered data.
  38537. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  38538. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38539. };
  38540. return LegendVisualProvider;
  38541. }();
  38542. var innerData = makeInner();
  38543. var PieSeriesModel = /** @class */function (_super) {
  38544. __extends(PieSeriesModel, _super);
  38545. function PieSeriesModel() {
  38546. return _super !== null && _super.apply(this, arguments) || this;
  38547. }
  38548. /**
  38549. * @overwrite
  38550. */
  38551. PieSeriesModel.prototype.init = function (option) {
  38552. _super.prototype.init.apply(this, arguments);
  38553. // Enable legend selection for each data item
  38554. // Use a function instead of direct access because data reference may changed
  38555. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  38556. this._defaultLabelLine(option);
  38557. };
  38558. /**
  38559. * @overwrite
  38560. */
  38561. PieSeriesModel.prototype.mergeOption = function () {
  38562. _super.prototype.mergeOption.apply(this, arguments);
  38563. };
  38564. /**
  38565. * @overwrite
  38566. */
  38567. PieSeriesModel.prototype.getInitialData = function () {
  38568. return createSeriesDataSimply(this, {
  38569. coordDimensions: ['value'],
  38570. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38571. });
  38572. };
  38573. /**
  38574. * @overwrite
  38575. */
  38576. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  38577. var data = this.getData();
  38578. // update seats when data is changed
  38579. var dataInner = innerData(data);
  38580. var seats = dataInner.seats;
  38581. if (!seats) {
  38582. var valueList_1 = [];
  38583. data.each(data.mapDimension('value'), function (value) {
  38584. valueList_1.push(value);
  38585. });
  38586. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  38587. }
  38588. var params = _super.prototype.getDataParams.call(this, dataIndex);
  38589. // seats may be empty when sum is 0
  38590. params.percent = seats[dataIndex] || 0;
  38591. params.$vars.push('percent');
  38592. return params;
  38593. };
  38594. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  38595. // Extend labelLine emphasis
  38596. defaultEmphasis(option, 'labelLine', ['show']);
  38597. var labelLineNormalOpt = option.labelLine;
  38598. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38599. // Not show label line if `label.normal.show = false`
  38600. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  38601. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  38602. };
  38603. PieSeriesModel.type = 'series.pie';
  38604. PieSeriesModel.defaultOption = {
  38605. // zlevel: 0,
  38606. z: 2,
  38607. legendHoverLink: true,
  38608. colorBy: 'data',
  38609. // 默认全局居中
  38610. center: ['50%', '50%'],
  38611. radius: [0, '75%'],
  38612. // 默认顺时针
  38613. clockwise: true,
  38614. startAngle: 90,
  38615. endAngle: 'auto',
  38616. padAngle: 0,
  38617. // 最小角度改为0
  38618. minAngle: 0,
  38619. // If the angle of a sector less than `minShowLabelAngle`,
  38620. // the label will not be displayed.
  38621. minShowLabelAngle: 0,
  38622. // 选中时扇区偏移量
  38623. selectedOffset: 10,
  38624. // 选择模式,默认关闭,可选single,multiple
  38625. // selectedMode: false,
  38626. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38627. // roseType: null,
  38628. percentPrecision: 2,
  38629. // If still show when all data zero.
  38630. stillShowZeroSum: true,
  38631. // cursor: null,
  38632. left: 0,
  38633. top: 0,
  38634. right: 0,
  38635. bottom: 0,
  38636. width: null,
  38637. height: null,
  38638. label: {
  38639. // color: 'inherit',
  38640. // If rotate around circle
  38641. rotate: 0,
  38642. show: true,
  38643. overflow: 'truncate',
  38644. // 'outer', 'inside', 'center'
  38645. position: 'outer',
  38646. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38647. alignTo: 'none',
  38648. // Closest distance between label and chart edge.
  38649. // Works only position is 'outer' and alignTo is 'edge'.
  38650. edgeDistance: '25%',
  38651. // Works only position is 'outer' and alignTo is not 'edge'.
  38652. bleedMargin: 10,
  38653. // Distance between text and label line.
  38654. distanceToLabelLine: 5
  38655. // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  38656. // 默认使用全局文本样式,详见 textStyle
  38657. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38658. },
  38659. // Enabled when label.normal.position is 'outer'
  38660. labelLine: {
  38661. show: true,
  38662. // 引导线两段中的第一段长度
  38663. length: 15,
  38664. // 引导线两段中的第二段长度
  38665. length2: 15,
  38666. smooth: false,
  38667. minTurnAngle: 90,
  38668. maxSurfaceAngle: 90,
  38669. lineStyle: {
  38670. // color: 各异,
  38671. width: 1,
  38672. type: 'solid'
  38673. }
  38674. },
  38675. itemStyle: {
  38676. borderWidth: 1,
  38677. borderJoin: 'round'
  38678. },
  38679. showEmptyCircle: true,
  38680. emptyCircleStyle: {
  38681. color: 'lightgray',
  38682. opacity: 1
  38683. },
  38684. labelLayout: {
  38685. // Hide the overlapped label.
  38686. hideOverlap: true
  38687. },
  38688. emphasis: {
  38689. scale: true,
  38690. scaleSize: 5
  38691. },
  38692. // If use strategy to avoid label overlapping
  38693. avoidLabelOverlap: true,
  38694. // Animation type. Valid values: expansion, scale
  38695. animationType: 'expansion',
  38696. animationDuration: 1000,
  38697. // Animation type when update. Valid values: transition, expansion
  38698. animationTypeUpdate: 'transition',
  38699. animationEasingUpdate: 'cubicInOut',
  38700. animationDurationUpdate: 500,
  38701. animationEasing: 'cubicInOut'
  38702. };
  38703. return PieSeriesModel;
  38704. }(SeriesModel);
  38705. function negativeDataFilter(seriesType) {
  38706. return {
  38707. seriesType: seriesType,
  38708. reset: function (seriesModel, ecModel) {
  38709. var data = seriesModel.getData();
  38710. data.filterSelf(function (idx) {
  38711. // handle negative value condition
  38712. var valueDim = data.mapDimension('value');
  38713. var curValue = data.get(valueDim, idx);
  38714. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  38715. return false;
  38716. }
  38717. return true;
  38718. });
  38719. }
  38720. };
  38721. }
  38722. function install$3(registers) {
  38723. registers.registerChartView(PieView);
  38724. registers.registerSeriesModel(PieSeriesModel);
  38725. createLegacyDataSelectAction('pie', registers.registerAction);
  38726. registers.registerLayout(curry(pieLayout, 'pie'));
  38727. registers.registerProcessor(dataFilter('pie'));
  38728. registers.registerProcessor(negativeDataFilter('pie'));
  38729. }
  38730. var GridModel = /** @class */function (_super) {
  38731. __extends(GridModel, _super);
  38732. function GridModel() {
  38733. return _super !== null && _super.apply(this, arguments) || this;
  38734. }
  38735. GridModel.type = 'grid';
  38736. GridModel.dependencies = ['xAxis', 'yAxis'];
  38737. GridModel.layoutMode = 'box';
  38738. GridModel.defaultOption = {
  38739. show: false,
  38740. // zlevel: 0,
  38741. z: 0,
  38742. left: '10%',
  38743. top: 60,
  38744. right: '10%',
  38745. bottom: 70,
  38746. // If grid size contain label
  38747. containLabel: false,
  38748. // width: {totalWidth} - left - right,
  38749. // height: {totalHeight} - top - bottom,
  38750. backgroundColor: 'rgba(0,0,0,0)',
  38751. borderWidth: 1,
  38752. borderColor: '#ccc'
  38753. };
  38754. return GridModel;
  38755. }(ComponentModel);
  38756. var CartesianAxisModel = /** @class */function (_super) {
  38757. __extends(CartesianAxisModel, _super);
  38758. function CartesianAxisModel() {
  38759. return _super !== null && _super.apply(this, arguments) || this;
  38760. }
  38761. CartesianAxisModel.prototype.getCoordSysModel = function () {
  38762. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  38763. };
  38764. CartesianAxisModel.type = 'cartesian2dAxis';
  38765. return CartesianAxisModel;
  38766. }(ComponentModel);
  38767. mixin(CartesianAxisModel, AxisModelCommonMixin);
  38768. var defaultOption = {
  38769. show: true,
  38770. // zlevel: 0,
  38771. z: 0,
  38772. // Inverse the axis.
  38773. inverse: false,
  38774. // Axis name displayed.
  38775. name: '',
  38776. // 'start' | 'middle' | 'end'
  38777. nameLocation: 'end',
  38778. // By degree. By default auto rotate by nameLocation.
  38779. nameRotate: null,
  38780. nameTruncate: {
  38781. maxWidth: null,
  38782. ellipsis: '...',
  38783. placeholder: '.'
  38784. },
  38785. // Use global text style by default.
  38786. nameTextStyle: {},
  38787. // The gap between axisName and axisLine.
  38788. nameGap: 15,
  38789. // Default `false` to support tooltip.
  38790. silent: false,
  38791. // Default `false` to avoid legacy user event listener fail.
  38792. triggerEvent: false,
  38793. tooltip: {
  38794. show: false
  38795. },
  38796. axisPointer: {},
  38797. axisLine: {
  38798. show: true,
  38799. onZero: true,
  38800. onZeroAxisIndex: null,
  38801. lineStyle: {
  38802. color: '#6E7079',
  38803. width: 1,
  38804. type: 'solid'
  38805. },
  38806. // The arrow at both ends the the axis.
  38807. symbol: ['none', 'none'],
  38808. symbolSize: [10, 15]
  38809. },
  38810. axisTick: {
  38811. show: true,
  38812. // Whether axisTick is inside the grid or outside the grid.
  38813. inside: false,
  38814. // The length of axisTick.
  38815. length: 5,
  38816. lineStyle: {
  38817. width: 1
  38818. }
  38819. },
  38820. axisLabel: {
  38821. show: true,
  38822. // Whether axisLabel is inside the grid or outside the grid.
  38823. inside: false,
  38824. rotate: 0,
  38825. // true | false | null/undefined (auto)
  38826. showMinLabel: null,
  38827. // true | false | null/undefined (auto)
  38828. showMaxLabel: null,
  38829. margin: 8,
  38830. // formatter: null,
  38831. fontSize: 12
  38832. },
  38833. splitLine: {
  38834. show: true,
  38835. lineStyle: {
  38836. color: ['#E0E6F1'],
  38837. width: 1,
  38838. type: 'solid'
  38839. }
  38840. },
  38841. splitArea: {
  38842. show: false,
  38843. areaStyle: {
  38844. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  38845. }
  38846. }
  38847. };
  38848. var categoryAxis = merge({
  38849. // The gap at both ends of the axis. For categoryAxis, boolean.
  38850. boundaryGap: true,
  38851. // Set false to faster category collection.
  38852. deduplication: null,
  38853. // splitArea: {
  38854. // show: false
  38855. // },
  38856. splitLine: {
  38857. show: false
  38858. },
  38859. axisTick: {
  38860. // If tick is align with label when boundaryGap is true
  38861. alignWithLabel: false,
  38862. interval: 'auto'
  38863. },
  38864. axisLabel: {
  38865. interval: 'auto'
  38866. }
  38867. }, defaultOption);
  38868. var valueAxis = merge({
  38869. boundaryGap: [0, 0],
  38870. axisLine: {
  38871. // Not shown when other axis is categoryAxis in cartesian
  38872. show: 'auto'
  38873. },
  38874. axisTick: {
  38875. // Not shown when other axis is categoryAxis in cartesian
  38876. show: 'auto'
  38877. },
  38878. // TODO
  38879. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  38880. splitNumber: 5,
  38881. minorTick: {
  38882. // Minor tick, not available for cateogry axis.
  38883. show: false,
  38884. // Split number of minor ticks. The value should be in range of (0, 100)
  38885. splitNumber: 5,
  38886. // Length of minor tick
  38887. length: 3,
  38888. // Line style
  38889. lineStyle: {
  38890. // Default to be same with axisTick
  38891. }
  38892. },
  38893. minorSplitLine: {
  38894. show: false,
  38895. lineStyle: {
  38896. color: '#F4F7FD',
  38897. width: 1
  38898. }
  38899. }
  38900. }, defaultOption);
  38901. var timeAxis = merge({
  38902. splitNumber: 6,
  38903. axisLabel: {
  38904. // To eliminate labels that are not nice
  38905. showMinLabel: false,
  38906. showMaxLabel: false,
  38907. rich: {
  38908. primary: {
  38909. fontWeight: 'bold'
  38910. }
  38911. }
  38912. },
  38913. splitLine: {
  38914. show: false
  38915. }
  38916. }, valueAxis);
  38917. var logAxis = defaults({
  38918. logBase: 10
  38919. }, valueAxis);
  38920. var axisDefault = {
  38921. category: categoryAxis,
  38922. value: valueAxis,
  38923. time: timeAxis,
  38924. log: logAxis
  38925. };
  38926. /*
  38927. * Licensed to the Apache Software Foundation (ASF) under one
  38928. * or more contributor license agreements. See the NOTICE file
  38929. * distributed with this work for additional information
  38930. * regarding copyright ownership. The ASF licenses this file
  38931. * to you under the Apache License, Version 2.0 (the
  38932. * "License"); you may not use this file except in compliance
  38933. * with the License. You may obtain a copy of the License at
  38934. *
  38935. * http://www.apache.org/licenses/LICENSE-2.0
  38936. *
  38937. * Unless required by applicable law or agreed to in writing,
  38938. * software distributed under the License is distributed on an
  38939. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38940. * KIND, either express or implied. See the License for the
  38941. * specific language governing permissions and limitations
  38942. * under the License.
  38943. */
  38944. /**
  38945. * AUTO-GENERATED FILE. DO NOT MODIFY.
  38946. */
  38947. /*
  38948. * Licensed to the Apache Software Foundation (ASF) under one
  38949. * or more contributor license agreements. See the NOTICE file
  38950. * distributed with this work for additional information
  38951. * regarding copyright ownership. The ASF licenses this file
  38952. * to you under the Apache License, Version 2.0 (the
  38953. * "License"); you may not use this file except in compliance
  38954. * with the License. You may obtain a copy of the License at
  38955. *
  38956. * http://www.apache.org/licenses/LICENSE-2.0
  38957. *
  38958. * Unless required by applicable law or agreed to in writing,
  38959. * software distributed under the License is distributed on an
  38960. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38961. * KIND, either express or implied. See the License for the
  38962. * specific language governing permissions and limitations
  38963. * under the License.
  38964. */
  38965. var AXIS_TYPES = {
  38966. value: 1,
  38967. category: 1,
  38968. time: 1,
  38969. log: 1
  38970. };
  38971. /**
  38972. * Generate sub axis model class
  38973. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  38974. */
  38975. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  38976. each(AXIS_TYPES, function (v, axisType) {
  38977. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  38978. var AxisModel = /** @class */function (_super) {
  38979. __extends(AxisModel, _super);
  38980. function AxisModel() {
  38981. var _this = _super !== null && _super.apply(this, arguments) || this;
  38982. _this.type = axisName + 'Axis.' + axisType;
  38983. return _this;
  38984. }
  38985. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  38986. var layoutMode = fetchLayoutMode(this);
  38987. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  38988. var themeModel = ecModel.getTheme();
  38989. merge(option, themeModel.get(axisType + 'Axis'));
  38990. merge(option, this.getDefaultOption());
  38991. option.type = getAxisType(option);
  38992. if (layoutMode) {
  38993. mergeLayoutParam(option, inputPositionParams, layoutMode);
  38994. }
  38995. };
  38996. AxisModel.prototype.optionUpdated = function () {
  38997. var thisOption = this.option;
  38998. if (thisOption.type === 'category') {
  38999. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  39000. }
  39001. };
  39002. /**
  39003. * Should not be called before all of 'getInitailData' finished.
  39004. * Because categories are collected during initializing data.
  39005. */
  39006. AxisModel.prototype.getCategories = function (rawData) {
  39007. var option = this.option;
  39008. // FIXME
  39009. // warning if called before all of 'getInitailData' finished.
  39010. if (option.type === 'category') {
  39011. if (rawData) {
  39012. return option.data;
  39013. }
  39014. return this.__ordinalMeta.categories;
  39015. }
  39016. };
  39017. AxisModel.prototype.getOrdinalMeta = function () {
  39018. return this.__ordinalMeta;
  39019. };
  39020. AxisModel.type = axisName + 'Axis.' + axisType;
  39021. AxisModel.defaultOption = defaultOption;
  39022. return AxisModel;
  39023. }(BaseAxisModelClass);
  39024. registers.registerComponentModel(AxisModel);
  39025. });
  39026. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  39027. }
  39028. function getAxisType(option) {
  39029. // Default axis with data is category axis
  39030. return option.type || (option.data ? 'category' : 'value');
  39031. }
  39032. var Cartesian = /** @class */function () {
  39033. function Cartesian(name) {
  39034. this.type = 'cartesian';
  39035. this._dimList = [];
  39036. this._axes = {};
  39037. this.name = name || '';
  39038. }
  39039. Cartesian.prototype.getAxis = function (dim) {
  39040. return this._axes[dim];
  39041. };
  39042. Cartesian.prototype.getAxes = function () {
  39043. return map(this._dimList, function (dim) {
  39044. return this._axes[dim];
  39045. }, this);
  39046. };
  39047. Cartesian.prototype.getAxesByScale = function (scaleType) {
  39048. scaleType = scaleType.toLowerCase();
  39049. return filter(this.getAxes(), function (axis) {
  39050. return axis.scale.type === scaleType;
  39051. });
  39052. };
  39053. Cartesian.prototype.addAxis = function (axis) {
  39054. var dim = axis.dim;
  39055. this._axes[dim] = axis;
  39056. this._dimList.push(dim);
  39057. };
  39058. return Cartesian;
  39059. }();
  39060. var cartesian2DDimensions = ['x', 'y'];
  39061. function canCalculateAffineTransform(scale) {
  39062. return scale.type === 'interval' || scale.type === 'time';
  39063. }
  39064. var Cartesian2D = /** @class */function (_super) {
  39065. __extends(Cartesian2D, _super);
  39066. function Cartesian2D() {
  39067. var _this = _super !== null && _super.apply(this, arguments) || this;
  39068. _this.type = 'cartesian2d';
  39069. _this.dimensions = cartesian2DDimensions;
  39070. return _this;
  39071. }
  39072. /**
  39073. * Calculate an affine transform matrix if two axes are time or value.
  39074. * It's mainly for accelartion on the large time series data.
  39075. */
  39076. Cartesian2D.prototype.calcAffineTransform = function () {
  39077. this._transform = this._invTransform = null;
  39078. var xAxisScale = this.getAxis('x').scale;
  39079. var yAxisScale = this.getAxis('y').scale;
  39080. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  39081. return;
  39082. }
  39083. var xScaleExtent = xAxisScale.getExtent();
  39084. var yScaleExtent = yAxisScale.getExtent();
  39085. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  39086. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  39087. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  39088. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  39089. if (!xScaleSpan || !yScaleSpan) {
  39090. return;
  39091. }
  39092. // Accelerate data to point calculation on the special large time series data.
  39093. var scaleX = (end[0] - start[0]) / xScaleSpan;
  39094. var scaleY = (end[1] - start[1]) / yScaleSpan;
  39095. var translateX = start[0] - xScaleExtent[0] * scaleX;
  39096. var translateY = start[1] - yScaleExtent[0] * scaleY;
  39097. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  39098. this._invTransform = invert([], m);
  39099. };
  39100. /**
  39101. * Base axis will be used on stacking.
  39102. */
  39103. Cartesian2D.prototype.getBaseAxis = function () {
  39104. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  39105. };
  39106. Cartesian2D.prototype.containPoint = function (point) {
  39107. var axisX = this.getAxis('x');
  39108. var axisY = this.getAxis('y');
  39109. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  39110. };
  39111. Cartesian2D.prototype.containData = function (data) {
  39112. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  39113. };
  39114. Cartesian2D.prototype.containZone = function (data1, data2) {
  39115. var zoneDiag1 = this.dataToPoint(data1);
  39116. var zoneDiag2 = this.dataToPoint(data2);
  39117. var area = this.getArea();
  39118. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  39119. return area.intersect(zone);
  39120. };
  39121. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  39122. out = out || [];
  39123. var xVal = data[0];
  39124. var yVal = data[1];
  39125. // Fast path
  39126. if (this._transform
  39127. // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  39128. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  39129. return applyTransform(out, data, this._transform);
  39130. }
  39131. var xAxis = this.getAxis('x');
  39132. var yAxis = this.getAxis('y');
  39133. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  39134. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  39135. return out;
  39136. };
  39137. Cartesian2D.prototype.clampData = function (data, out) {
  39138. var xScale = this.getAxis('x').scale;
  39139. var yScale = this.getAxis('y').scale;
  39140. var xAxisExtent = xScale.getExtent();
  39141. var yAxisExtent = yScale.getExtent();
  39142. var x = xScale.parse(data[0]);
  39143. var y = yScale.parse(data[1]);
  39144. out = out || [];
  39145. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  39146. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  39147. return out;
  39148. };
  39149. Cartesian2D.prototype.pointToData = function (point, clamp) {
  39150. var out = [];
  39151. if (this._invTransform) {
  39152. return applyTransform(out, point, this._invTransform);
  39153. }
  39154. var xAxis = this.getAxis('x');
  39155. var yAxis = this.getAxis('y');
  39156. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  39157. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  39158. return out;
  39159. };
  39160. Cartesian2D.prototype.getOtherAxis = function (axis) {
  39161. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  39162. };
  39163. /**
  39164. * Get rect area of cartesian.
  39165. * Area will have a contain function to determine if a point is in the coordinate system.
  39166. */
  39167. Cartesian2D.prototype.getArea = function (tolerance) {
  39168. tolerance = tolerance || 0;
  39169. var xExtent = this.getAxis('x').getGlobalExtent();
  39170. var yExtent = this.getAxis('y').getGlobalExtent();
  39171. var x = Math.min(xExtent[0], xExtent[1]) - tolerance;
  39172. var y = Math.min(yExtent[0], yExtent[1]) - tolerance;
  39173. var width = Math.max(xExtent[0], xExtent[1]) - x + tolerance;
  39174. var height = Math.max(yExtent[0], yExtent[1]) - y + tolerance;
  39175. return new BoundingRect(x, y, width, height);
  39176. };
  39177. return Cartesian2D;
  39178. }(Cartesian);
  39179. var Axis2D = /** @class */function (_super) {
  39180. __extends(Axis2D, _super);
  39181. function Axis2D(dim, scale, coordExtent, axisType, position) {
  39182. var _this = _super.call(this, dim, scale, coordExtent) || this;
  39183. /**
  39184. * Index of axis, can be used as key
  39185. * Injected outside.
  39186. */
  39187. _this.index = 0;
  39188. _this.type = axisType || 'value';
  39189. _this.position = position || 'bottom';
  39190. return _this;
  39191. }
  39192. Axis2D.prototype.isHorizontal = function () {
  39193. var position = this.position;
  39194. return position === 'top' || position === 'bottom';
  39195. };
  39196. /**
  39197. * Each item cooresponds to this.getExtent(), which
  39198. * means globalExtent[0] may greater than globalExtent[1],
  39199. * unless `asc` is input.
  39200. *
  39201. * @param {boolean} [asc]
  39202. * @return {Array.<number>}
  39203. */
  39204. Axis2D.prototype.getGlobalExtent = function (asc) {
  39205. var ret = this.getExtent();
  39206. ret[0] = this.toGlobalCoord(ret[0]);
  39207. ret[1] = this.toGlobalCoord(ret[1]);
  39208. asc && ret[0] > ret[1] && ret.reverse();
  39209. return ret;
  39210. };
  39211. Axis2D.prototype.pointToData = function (point, clamp) {
  39212. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  39213. };
  39214. /**
  39215. * Set ordinalSortInfo
  39216. * @param info new OrdinalSortInfo
  39217. */
  39218. Axis2D.prototype.setCategorySortInfo = function (info) {
  39219. if (this.type !== 'category') {
  39220. return false;
  39221. }
  39222. this.model.option.categorySortInfo = info;
  39223. this.scale.setSortInfo(info);
  39224. };
  39225. return Axis2D;
  39226. }(Axis);
  39227. /**
  39228. * Can only be called after coordinate system creation stage.
  39229. * (Can be called before coordinate system update stage).
  39230. */
  39231. function layout$1(gridModel, axisModel, opt) {
  39232. opt = opt || {};
  39233. var grid = gridModel.coordinateSystem;
  39234. var axis = axisModel.axis;
  39235. var layout = {};
  39236. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  39237. var rawAxisPosition = axis.position;
  39238. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  39239. var axisDim = axis.dim;
  39240. var rect = grid.getRect();
  39241. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  39242. var idx = {
  39243. left: 0,
  39244. right: 1,
  39245. top: 0,
  39246. bottom: 1,
  39247. onZero: 2
  39248. };
  39249. var axisOffset = axisModel.get('offset') || 0;
  39250. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  39251. if (otherAxisOnZeroOf) {
  39252. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  39253. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  39254. }
  39255. // Axis position
  39256. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]];
  39257. // Axis rotation
  39258. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  39259. // Tick and label direction, x y is axisDim
  39260. var dirMap = {
  39261. top: -1,
  39262. bottom: 1,
  39263. left: -1,
  39264. right: 1
  39265. };
  39266. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  39267. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  39268. if (axisModel.get(['axisTick', 'inside'])) {
  39269. layout.tickDirection = -layout.tickDirection;
  39270. }
  39271. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  39272. layout.labelDirection = -layout.labelDirection;
  39273. }
  39274. // Special label rotation
  39275. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  39276. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  39277. // Over splitLine and splitArea
  39278. layout.z2 = 1;
  39279. return layout;
  39280. }
  39281. function isCartesian2DSeries(seriesModel) {
  39282. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  39283. }
  39284. function findAxisModels(seriesModel) {
  39285. var axisModelMap = {
  39286. xAxisModel: null,
  39287. yAxisModel: null
  39288. };
  39289. each(axisModelMap, function (v, key) {
  39290. var axisType = key.replace(/Model$/, '');
  39291. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  39292. if ("development" !== 'production') {
  39293. if (!axisModel) {
  39294. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  39295. }
  39296. }
  39297. axisModelMap[key] = axisModel;
  39298. });
  39299. return axisModelMap;
  39300. }
  39301. var mathLog$1 = Math.log;
  39302. function alignScaleTicks(scale, axisModel, alignToScale) {
  39303. var intervalScaleProto = IntervalScale.prototype;
  39304. // NOTE: There is a precondition for log scale here:
  39305. // In log scale we store _interval and _extent of exponent value.
  39306. // So if we use the method of InternalScale to set/get these data.
  39307. // It process the exponent value, which is linear and what we want here.
  39308. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  39309. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  39310. var alignToSplitNumber = alignToTicks.length - 1;
  39311. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  39312. var scaleExtent = getScaleExtent(scale, axisModel);
  39313. var rawExtent = scaleExtent.extent;
  39314. var isMinFixed = scaleExtent.fixMin;
  39315. var isMaxFixed = scaleExtent.fixMax;
  39316. if (scale.type === 'log') {
  39317. var logBase = mathLog$1(scale.base);
  39318. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  39319. }
  39320. scale.setExtent(rawExtent[0], rawExtent[1]);
  39321. scale.calcNiceExtent({
  39322. splitNumber: alignToSplitNumber,
  39323. fixMin: isMinFixed,
  39324. fixMax: isMaxFixed
  39325. });
  39326. var extent = intervalScaleProto.getExtent.call(scale);
  39327. // Need to update the rawExtent.
  39328. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  39329. if (isMinFixed) {
  39330. rawExtent[0] = extent[0];
  39331. }
  39332. if (isMaxFixed) {
  39333. rawExtent[1] = extent[1];
  39334. }
  39335. var interval = intervalScaleProto.getInterval.call(scale);
  39336. var min = rawExtent[0];
  39337. var max = rawExtent[1];
  39338. if (isMinFixed && isMaxFixed) {
  39339. // User set min, max, divide to get new interval
  39340. interval = (max - min) / alignToSplitNumber;
  39341. } else if (isMinFixed) {
  39342. max = rawExtent[0] + interval * alignToSplitNumber;
  39343. // User set min, expand extent on the other side
  39344. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  39345. interval = increaseInterval(interval);
  39346. max = rawExtent[0] + interval * alignToSplitNumber;
  39347. }
  39348. } else if (isMaxFixed) {
  39349. // User set max, expand extent on the other side
  39350. min = rawExtent[1] - interval * alignToSplitNumber;
  39351. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  39352. interval = increaseInterval(interval);
  39353. min = rawExtent[1] - interval * alignToSplitNumber;
  39354. }
  39355. } else {
  39356. var nicedSplitNumber = scale.getTicks().length - 1;
  39357. if (nicedSplitNumber > alignToSplitNumber) {
  39358. interval = increaseInterval(interval);
  39359. }
  39360. var range = interval * alignToSplitNumber;
  39361. max = Math.ceil(rawExtent[1] / interval) * interval;
  39362. min = round(max - range);
  39363. // Not change the result that crossing zero.
  39364. if (min < 0 && rawExtent[0] >= 0) {
  39365. min = 0;
  39366. max = round(range);
  39367. } else if (max > 0 && rawExtent[1] <= 0) {
  39368. max = 0;
  39369. min = -round(range);
  39370. }
  39371. }
  39372. // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  39373. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  39374. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval;
  39375. // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  39376. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  39377. intervalScaleProto.setInterval.call(scale, interval);
  39378. if (t0 || t1) {
  39379. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  39380. }
  39381. if ("development" !== 'production') {
  39382. var ticks = intervalScaleProto.getTicks.call(scale);
  39383. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  39384. warn(
  39385. // eslint-disable-next-line
  39386. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  39387. }
  39388. }
  39389. }
  39390. var Grid = /** @class */function () {
  39391. function Grid(gridModel, ecModel, api) {
  39392. // FIXME:TS where used (different from registered type 'cartesian2d')?
  39393. this.type = 'grid';
  39394. this._coordsMap = {};
  39395. this._coordsList = [];
  39396. this._axesMap = {};
  39397. this._axesList = [];
  39398. this.axisPointerEnabled = true;
  39399. this.dimensions = cartesian2DDimensions;
  39400. this._initCartesian(gridModel, ecModel, api);
  39401. this.model = gridModel;
  39402. }
  39403. Grid.prototype.getRect = function () {
  39404. return this._rect;
  39405. };
  39406. Grid.prototype.update = function (ecModel, api) {
  39407. var axesMap = this._axesMap;
  39408. this._updateScale(ecModel, this.model);
  39409. function updateAxisTicks(axes) {
  39410. var alignTo;
  39411. // Axis is added in order of axisIndex.
  39412. var axesIndices = keys(axes);
  39413. var len = axesIndices.length;
  39414. if (!len) {
  39415. return;
  39416. }
  39417. var axisNeedsAlign = [];
  39418. // Process once and calculate the ticks for those don't use alignTicks.
  39419. for (var i = len - 1; i >= 0; i--) {
  39420. var idx = +axesIndices[i]; // Convert to number.
  39421. var axis = axes[idx];
  39422. var model = axis.model;
  39423. var scale = axis.scale;
  39424. if (
  39425. // Only value and log axis without interval support alignTicks.
  39426. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  39427. axisNeedsAlign.push(axis);
  39428. } else {
  39429. niceScaleExtent(scale, model);
  39430. if (isIntervalOrLogScale(scale)) {
  39431. // Can only align to interval or log axis.
  39432. alignTo = axis;
  39433. }
  39434. }
  39435. }
  39436. // All axes has set alignTicks. Pick the first one.
  39437. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  39438. if (axisNeedsAlign.length) {
  39439. if (!alignTo) {
  39440. alignTo = axisNeedsAlign.pop();
  39441. niceScaleExtent(alignTo.scale, alignTo.model);
  39442. }
  39443. each(axisNeedsAlign, function (axis) {
  39444. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  39445. });
  39446. }
  39447. }
  39448. updateAxisTicks(axesMap.x);
  39449. updateAxisTicks(axesMap.y);
  39450. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  39451. var onZeroRecords = {};
  39452. each(axesMap.x, function (xAxis) {
  39453. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  39454. });
  39455. each(axesMap.y, function (yAxis) {
  39456. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  39457. });
  39458. // Resize again if containLabel is enabled
  39459. // FIXME It may cause getting wrong grid size in data processing stage
  39460. this.resize(this.model, api);
  39461. };
  39462. /**
  39463. * Resize the grid
  39464. */
  39465. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  39466. var boxLayoutParams = gridModel.getBoxLayoutParams();
  39467. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  39468. var gridRect = getLayoutRect(boxLayoutParams, {
  39469. width: api.getWidth(),
  39470. height: api.getHeight()
  39471. });
  39472. this._rect = gridRect;
  39473. var axesList = this._axesList;
  39474. adjustAxes();
  39475. // Minus label size
  39476. if (isContainLabel) {
  39477. each(axesList, function (axis) {
  39478. if (!axis.model.get(['axisLabel', 'inside'])) {
  39479. var labelUnionRect = estimateLabelUnionRect(axis);
  39480. if (labelUnionRect) {
  39481. var dim = axis.isHorizontal() ? 'height' : 'width';
  39482. var margin = axis.model.get(['axisLabel', 'margin']);
  39483. gridRect[dim] -= labelUnionRect[dim] + margin;
  39484. if (axis.position === 'top') {
  39485. gridRect.y += labelUnionRect.height + margin;
  39486. } else if (axis.position === 'left') {
  39487. gridRect.x += labelUnionRect.width + margin;
  39488. }
  39489. }
  39490. }
  39491. });
  39492. adjustAxes();
  39493. }
  39494. each(this._coordsList, function (coord) {
  39495. // Calculate affine matrix to accelerate the data to point transform.
  39496. // If all the axes scales are time or value.
  39497. coord.calcAffineTransform();
  39498. });
  39499. function adjustAxes() {
  39500. each(axesList, function (axis) {
  39501. var isHorizontal = axis.isHorizontal();
  39502. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  39503. var idx = axis.inverse ? 1 : 0;
  39504. axis.setExtent(extent[idx], extent[1 - idx]);
  39505. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  39506. });
  39507. }
  39508. };
  39509. Grid.prototype.getAxis = function (dim, axisIndex) {
  39510. var axesMapOnDim = this._axesMap[dim];
  39511. if (axesMapOnDim != null) {
  39512. return axesMapOnDim[axisIndex || 0];
  39513. }
  39514. };
  39515. Grid.prototype.getAxes = function () {
  39516. return this._axesList.slice();
  39517. };
  39518. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  39519. if (xAxisIndex != null && yAxisIndex != null) {
  39520. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  39521. return this._coordsMap[key];
  39522. }
  39523. if (isObject(xAxisIndex)) {
  39524. yAxisIndex = xAxisIndex.yAxisIndex;
  39525. xAxisIndex = xAxisIndex.xAxisIndex;
  39526. }
  39527. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  39528. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  39529. return coordList[i];
  39530. }
  39531. }
  39532. };
  39533. Grid.prototype.getCartesians = function () {
  39534. return this._coordsList.slice();
  39535. };
  39536. /**
  39537. * @implements
  39538. */
  39539. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  39540. var target = this._findConvertTarget(finder);
  39541. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  39542. };
  39543. /**
  39544. * @implements
  39545. */
  39546. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  39547. var target = this._findConvertTarget(finder);
  39548. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  39549. };
  39550. Grid.prototype._findConvertTarget = function (finder) {
  39551. var seriesModel = finder.seriesModel;
  39552. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  39553. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  39554. var gridModel = finder.gridModel;
  39555. var coordsList = this._coordsList;
  39556. var cartesian;
  39557. var axis;
  39558. if (seriesModel) {
  39559. cartesian = seriesModel.coordinateSystem;
  39560. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  39561. } else if (xAxisModel && yAxisModel) {
  39562. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  39563. } else if (xAxisModel) {
  39564. axis = this.getAxis('x', xAxisModel.componentIndex);
  39565. } else if (yAxisModel) {
  39566. axis = this.getAxis('y', yAxisModel.componentIndex);
  39567. }
  39568. // Lowest priority.
  39569. else if (gridModel) {
  39570. var grid = gridModel.coordinateSystem;
  39571. if (grid === this) {
  39572. cartesian = this._coordsList[0];
  39573. }
  39574. }
  39575. return {
  39576. cartesian: cartesian,
  39577. axis: axis
  39578. };
  39579. };
  39580. /**
  39581. * @implements
  39582. */
  39583. Grid.prototype.containPoint = function (point) {
  39584. var coord = this._coordsList[0];
  39585. if (coord) {
  39586. return coord.containPoint(point);
  39587. }
  39588. };
  39589. /**
  39590. * Initialize cartesian coordinate systems
  39591. */
  39592. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  39593. var _this = this;
  39594. var grid = this;
  39595. var axisPositionUsed = {
  39596. left: false,
  39597. right: false,
  39598. top: false,
  39599. bottom: false
  39600. };
  39601. var axesMap = {
  39602. x: {},
  39603. y: {}
  39604. };
  39605. var axesCount = {
  39606. x: 0,
  39607. y: 0
  39608. };
  39609. // Create axis
  39610. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  39611. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  39612. if (!axesCount.x || !axesCount.y) {
  39613. // Roll back when there no either x or y axis
  39614. this._axesMap = {};
  39615. this._axesList = [];
  39616. return;
  39617. }
  39618. this._axesMap = axesMap;
  39619. // Create cartesian2d
  39620. each(axesMap.x, function (xAxis, xAxisIndex) {
  39621. each(axesMap.y, function (yAxis, yAxisIndex) {
  39622. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  39623. var cartesian = new Cartesian2D(key);
  39624. cartesian.master = _this;
  39625. cartesian.model = gridModel;
  39626. _this._coordsMap[key] = cartesian;
  39627. _this._coordsList.push(cartesian);
  39628. cartesian.addAxis(xAxis);
  39629. cartesian.addAxis(yAxis);
  39630. });
  39631. });
  39632. function createAxisCreator(dimName) {
  39633. return function (axisModel, idx) {
  39634. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  39635. return;
  39636. }
  39637. var axisPosition = axisModel.get('position');
  39638. if (dimName === 'x') {
  39639. // Fix position
  39640. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  39641. // Default bottom of X
  39642. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  39643. }
  39644. } else {
  39645. // Fix position
  39646. if (axisPosition !== 'left' && axisPosition !== 'right') {
  39647. // Default left of Y
  39648. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  39649. }
  39650. }
  39651. axisPositionUsed[axisPosition] = true;
  39652. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  39653. var isCategory = axis.type === 'category';
  39654. axis.onBand = isCategory && axisModel.get('boundaryGap');
  39655. axis.inverse = axisModel.get('inverse');
  39656. // Inject axis into axisModel
  39657. axisModel.axis = axis;
  39658. // Inject axisModel into axis
  39659. axis.model = axisModel;
  39660. // Inject grid info axis
  39661. axis.grid = grid;
  39662. // Index of axis, can be used as key
  39663. axis.index = idx;
  39664. grid._axesList.push(axis);
  39665. axesMap[dimName][idx] = axis;
  39666. axesCount[dimName]++;
  39667. };
  39668. }
  39669. };
  39670. /**
  39671. * Update cartesian properties from series.
  39672. */
  39673. Grid.prototype._updateScale = function (ecModel, gridModel) {
  39674. // Reset scale
  39675. each(this._axesList, function (axis) {
  39676. axis.scale.setExtent(Infinity, -Infinity);
  39677. if (axis.type === 'category') {
  39678. var categorySortInfo = axis.model.get('categorySortInfo');
  39679. axis.scale.setSortInfo(categorySortInfo);
  39680. }
  39681. });
  39682. ecModel.eachSeries(function (seriesModel) {
  39683. if (isCartesian2DSeries(seriesModel)) {
  39684. var axesModelMap = findAxisModels(seriesModel);
  39685. var xAxisModel = axesModelMap.xAxisModel;
  39686. var yAxisModel = axesModelMap.yAxisModel;
  39687. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  39688. return;
  39689. }
  39690. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  39691. var data = seriesModel.getData();
  39692. var xAxis = cartesian.getAxis('x');
  39693. var yAxis = cartesian.getAxis('y');
  39694. unionExtent(data, xAxis);
  39695. unionExtent(data, yAxis);
  39696. }
  39697. }, this);
  39698. function unionExtent(data, axis) {
  39699. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  39700. axis.scale.unionExtentFromData(data, dim);
  39701. });
  39702. }
  39703. };
  39704. /**
  39705. * @param dim 'x' or 'y' or 'auto' or null/undefined
  39706. */
  39707. Grid.prototype.getTooltipAxes = function (dim) {
  39708. var baseAxes = [];
  39709. var otherAxes = [];
  39710. each(this.getCartesians(), function (cartesian) {
  39711. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  39712. var otherAxis = cartesian.getOtherAxis(baseAxis);
  39713. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  39714. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  39715. });
  39716. return {
  39717. baseAxes: baseAxes,
  39718. otherAxes: otherAxes
  39719. };
  39720. };
  39721. Grid.create = function (ecModel, api) {
  39722. var grids = [];
  39723. ecModel.eachComponent('grid', function (gridModel, idx) {
  39724. var grid = new Grid(gridModel, ecModel, api);
  39725. grid.name = 'grid_' + idx;
  39726. // dataSampling requires axis extent, so resize
  39727. // should be performed in create stage.
  39728. grid.resize(gridModel, api, true);
  39729. gridModel.coordinateSystem = grid;
  39730. grids.push(grid);
  39731. });
  39732. // Inject the coordinateSystems into seriesModel
  39733. ecModel.eachSeries(function (seriesModel) {
  39734. if (!isCartesian2DSeries(seriesModel)) {
  39735. return;
  39736. }
  39737. var axesModelMap = findAxisModels(seriesModel);
  39738. var xAxisModel = axesModelMap.xAxisModel;
  39739. var yAxisModel = axesModelMap.yAxisModel;
  39740. var gridModel = xAxisModel.getCoordSysModel();
  39741. if ("development" !== 'production') {
  39742. if (!gridModel) {
  39743. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  39744. }
  39745. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  39746. throw new Error('xAxis and yAxis must use the same grid');
  39747. }
  39748. }
  39749. var grid = gridModel.coordinateSystem;
  39750. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  39751. });
  39752. return grids;
  39753. };
  39754. // For deciding which dimensions to use when creating list data
  39755. Grid.dimensions = cartesian2DDimensions;
  39756. return Grid;
  39757. }();
  39758. /**
  39759. * Check if the axis is used in the specified grid.
  39760. */
  39761. function isAxisUsedInTheGrid(axisModel, gridModel) {
  39762. return axisModel.getCoordSysModel() === gridModel;
  39763. }
  39764. function fixAxisOnZero(axesMap, otherAxisDim, axis,
  39765. // Key: see `getOnZeroRecordKey`
  39766. onZeroRecords) {
  39767. axis.getAxesOnZeroOf = function () {
  39768. // TODO: onZero of multiple axes.
  39769. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  39770. };
  39771. // onZero can not be enabled in these two situations:
  39772. // 1. When any other axis is a category axis.
  39773. // 2. When no axis is cross 0 point.
  39774. var otherAxes = axesMap[otherAxisDim];
  39775. var otherAxisOnZeroOf;
  39776. var axisModel = axis.model;
  39777. var onZero = axisModel.get(['axisLine', 'onZero']);
  39778. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  39779. if (!onZero) {
  39780. return;
  39781. }
  39782. // If target axis is specified.
  39783. if (onZeroAxisIndex != null) {
  39784. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  39785. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  39786. }
  39787. } else {
  39788. // Find the first available other axis.
  39789. for (var idx in otherAxes) {
  39790. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx])
  39791. // Consider that two Y axes on one value axis,
  39792. // if both onZero, the two Y axes overlap.
  39793. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  39794. otherAxisOnZeroOf = otherAxes[idx];
  39795. break;
  39796. }
  39797. }
  39798. }
  39799. if (otherAxisOnZeroOf) {
  39800. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  39801. }
  39802. function getOnZeroRecordKey(axis) {
  39803. return axis.dim + '_' + axis.index;
  39804. }
  39805. }
  39806. function canOnZeroToAxis(axis) {
  39807. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  39808. }
  39809. function updateAxisTransform(axis, coordBase) {
  39810. var axisExtent = axis.getExtent();
  39811. var axisExtentSum = axisExtent[0] + axisExtent[1];
  39812. // Fast transform
  39813. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  39814. return coord + coordBase;
  39815. } : function (coord) {
  39816. return axisExtentSum - coord + coordBase;
  39817. };
  39818. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  39819. return coord - coordBase;
  39820. } : function (coord) {
  39821. return axisExtentSum - coord + coordBase;
  39822. };
  39823. }
  39824. var PI$4 = Math.PI;
  39825. /**
  39826. * A final axis is translated and rotated from a "standard axis".
  39827. * So opt.position and opt.rotation is required.
  39828. *
  39829. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  39830. * for example: (0, 0) ------------> (0, 50)
  39831. *
  39832. * nameDirection or tickDirection or labelDirection is 1 means tick
  39833. * or label is below the standard axis, whereas is -1 means above
  39834. * the standard axis. labelOffset means offset between label and axis,
  39835. * which is useful when 'onZero', where axisLabel is in the grid and
  39836. * label in outside grid.
  39837. *
  39838. * Tips: like always,
  39839. * positive rotation represents anticlockwise, and negative rotation
  39840. * represents clockwise.
  39841. * The direction of position coordinate is the same as the direction
  39842. * of screen coordinate.
  39843. *
  39844. * Do not need to consider axis 'inverse', which is auto processed by
  39845. * axis extent.
  39846. */
  39847. var AxisBuilder = /** @class */function () {
  39848. function AxisBuilder(axisModel, opt) {
  39849. this.group = new Group();
  39850. this.opt = opt;
  39851. this.axisModel = axisModel;
  39852. // Default value
  39853. defaults(opt, {
  39854. labelOffset: 0,
  39855. nameDirection: 1,
  39856. tickDirection: 1,
  39857. labelDirection: 1,
  39858. silent: true,
  39859. handleAutoShown: function () {
  39860. return true;
  39861. }
  39862. });
  39863. // FIXME Not use a separate text group?
  39864. var transformGroup = new Group({
  39865. x: opt.position[0],
  39866. y: opt.position[1],
  39867. rotation: opt.rotation
  39868. });
  39869. // this.group.add(transformGroup);
  39870. // this._transformGroup = transformGroup;
  39871. transformGroup.updateTransform();
  39872. this._transformGroup = transformGroup;
  39873. }
  39874. AxisBuilder.prototype.hasBuilder = function (name) {
  39875. return !!builders[name];
  39876. };
  39877. AxisBuilder.prototype.add = function (name) {
  39878. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  39879. };
  39880. AxisBuilder.prototype.getGroup = function () {
  39881. return this.group;
  39882. };
  39883. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  39884. var rotationDiff = remRadian(textRotation - axisRotation);
  39885. var textAlign;
  39886. var textVerticalAlign;
  39887. if (isRadianAroundZero(rotationDiff)) {
  39888. // Label is parallel with axis line.
  39889. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  39890. textAlign = 'center';
  39891. } else if (isRadianAroundZero(rotationDiff - PI$4)) {
  39892. // Label is inverse parallel with axis line.
  39893. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  39894. textAlign = 'center';
  39895. } else {
  39896. textVerticalAlign = 'middle';
  39897. if (rotationDiff > 0 && rotationDiff < PI$4) {
  39898. textAlign = direction > 0 ? 'right' : 'left';
  39899. } else {
  39900. textAlign = direction > 0 ? 'left' : 'right';
  39901. }
  39902. }
  39903. return {
  39904. rotation: rotationDiff,
  39905. textAlign: textAlign,
  39906. textVerticalAlign: textVerticalAlign
  39907. };
  39908. };
  39909. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  39910. var eventData = {
  39911. componentType: axisModel.mainType,
  39912. componentIndex: axisModel.componentIndex
  39913. };
  39914. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  39915. return eventData;
  39916. };
  39917. AxisBuilder.isLabelSilent = function (axisModel) {
  39918. var tooltipOpt = axisModel.get('tooltip');
  39919. return axisModel.get('silent')
  39920. // Consider mouse cursor, add these restrictions.
  39921. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  39922. };
  39923. return AxisBuilder;
  39924. }();
  39925. var builders = {
  39926. axisLine: function (opt, axisModel, group, transformGroup) {
  39927. var shown = axisModel.get(['axisLine', 'show']);
  39928. if (shown === 'auto' && opt.handleAutoShown) {
  39929. shown = opt.handleAutoShown('axisLine');
  39930. }
  39931. if (!shown) {
  39932. return;
  39933. }
  39934. var extent = axisModel.axis.getExtent();
  39935. var matrix = transformGroup.transform;
  39936. var pt1 = [extent[0], 0];
  39937. var pt2 = [extent[1], 0];
  39938. var inverse = pt1[0] > pt2[0];
  39939. if (matrix) {
  39940. applyTransform(pt1, pt1, matrix);
  39941. applyTransform(pt2, pt2, matrix);
  39942. }
  39943. var lineStyle = extend({
  39944. lineCap: 'round'
  39945. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  39946. var line = new Line({
  39947. shape: {
  39948. x1: pt1[0],
  39949. y1: pt1[1],
  39950. x2: pt2[0],
  39951. y2: pt2[1]
  39952. },
  39953. style: lineStyle,
  39954. strokeContainThreshold: opt.strokeContainThreshold || 5,
  39955. silent: true,
  39956. z2: 1
  39957. });
  39958. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  39959. line.anid = 'line';
  39960. group.add(line);
  39961. var arrows = axisModel.get(['axisLine', 'symbol']);
  39962. if (arrows != null) {
  39963. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  39964. if (isString(arrows)) {
  39965. // Use the same arrow for start and end point
  39966. arrows = [arrows, arrows];
  39967. }
  39968. if (isString(arrowSize) || isNumber(arrowSize)) {
  39969. // Use the same size for width and height
  39970. arrowSize = [arrowSize, arrowSize];
  39971. }
  39972. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  39973. var symbolWidth_1 = arrowSize[0];
  39974. var symbolHeight_1 = arrowSize[1];
  39975. each([{
  39976. rotate: opt.rotation + Math.PI / 2,
  39977. offset: arrowOffset[0],
  39978. r: 0
  39979. }, {
  39980. rotate: opt.rotation - Math.PI / 2,
  39981. offset: arrowOffset[1],
  39982. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  39983. }], function (point, index) {
  39984. if (arrows[index] !== 'none' && arrows[index] != null) {
  39985. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true);
  39986. // Calculate arrow position with offset
  39987. var r = point.r + point.offset;
  39988. var pt = inverse ? pt2 : pt1;
  39989. symbol.attr({
  39990. rotation: point.rotate,
  39991. x: pt[0] + r * Math.cos(opt.rotation),
  39992. y: pt[1] - r * Math.sin(opt.rotation),
  39993. silent: true,
  39994. z2: 11
  39995. });
  39996. group.add(symbol);
  39997. }
  39998. });
  39999. }
  40000. },
  40001. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  40002. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  40003. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  40004. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  40005. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection);
  40006. // This bit fixes the label overlap issue for the time chart.
  40007. // See https://github.com/apache/echarts/issues/14266 for more.
  40008. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  40009. var labelList = prepareLayoutList(map(labelEls, function (label) {
  40010. return {
  40011. label: label,
  40012. priority: label.z2,
  40013. defaultAttr: {
  40014. ignore: label.ignore
  40015. }
  40016. };
  40017. }));
  40018. hideOverlap(labelList);
  40019. }
  40020. },
  40021. axisName: function (opt, axisModel, group, transformGroup) {
  40022. var name = retrieve(opt.axisName, axisModel.get('name'));
  40023. if (!name) {
  40024. return;
  40025. }
  40026. var nameLocation = axisModel.get('nameLocation');
  40027. var nameDirection = opt.nameDirection;
  40028. var textStyleModel = axisModel.getModel('nameTextStyle');
  40029. var gap = axisModel.get('nameGap') || 0;
  40030. var extent = axisModel.axis.getExtent();
  40031. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  40032. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2,
  40033. // Reuse labelOffset.
  40034. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  40035. var labelLayout;
  40036. var nameRotation = axisModel.get('nameRotate');
  40037. if (nameRotation != null) {
  40038. nameRotation = nameRotation * PI$4 / 180; // To radian.
  40039. }
  40040. var axisNameAvailableWidth;
  40041. if (isNameLocationCenter(nameLocation)) {
  40042. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation,
  40043. // Adapt to axis.
  40044. nameDirection);
  40045. } else {
  40046. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  40047. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  40048. if (axisNameAvailableWidth != null) {
  40049. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  40050. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  40051. }
  40052. }
  40053. var textFont = textStyleModel.getFont();
  40054. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  40055. var ellipsis = truncateOpt.ellipsis;
  40056. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  40057. var textEl = new ZRText({
  40058. x: pos[0],
  40059. y: pos[1],
  40060. rotation: labelLayout.rotation,
  40061. silent: AxisBuilder.isLabelSilent(axisModel),
  40062. style: createTextStyle(textStyleModel, {
  40063. text: name,
  40064. font: textFont,
  40065. overflow: 'truncate',
  40066. width: maxWidth,
  40067. ellipsis: ellipsis,
  40068. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  40069. align: textStyleModel.get('align') || labelLayout.textAlign,
  40070. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  40071. }),
  40072. z2: 1
  40073. });
  40074. setTooltipConfig({
  40075. el: textEl,
  40076. componentModel: axisModel,
  40077. itemName: name
  40078. });
  40079. textEl.__fullText = name;
  40080. // Id for animation
  40081. textEl.anid = 'name';
  40082. if (axisModel.get('triggerEvent')) {
  40083. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  40084. eventData.targetType = 'axisName';
  40085. eventData.name = name;
  40086. getECData(textEl).eventData = eventData;
  40087. }
  40088. // FIXME
  40089. transformGroup.add(textEl);
  40090. textEl.updateTransform();
  40091. group.add(textEl);
  40092. textEl.decomposeTransform();
  40093. }
  40094. };
  40095. function endTextLayout(rotation, textPosition, textRotate, extent) {
  40096. var rotationDiff = remRadian(textRotate - rotation);
  40097. var textAlign;
  40098. var textVerticalAlign;
  40099. var inverse = extent[0] > extent[1];
  40100. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  40101. if (isRadianAroundZero(rotationDiff - PI$4 / 2)) {
  40102. textVerticalAlign = onLeft ? 'bottom' : 'top';
  40103. textAlign = 'center';
  40104. } else if (isRadianAroundZero(rotationDiff - PI$4 * 1.5)) {
  40105. textVerticalAlign = onLeft ? 'top' : 'bottom';
  40106. textAlign = 'center';
  40107. } else {
  40108. textVerticalAlign = 'middle';
  40109. if (rotationDiff < PI$4 * 1.5 && rotationDiff > PI$4 / 2) {
  40110. textAlign = onLeft ? 'left' : 'right';
  40111. } else {
  40112. textAlign = onLeft ? 'right' : 'left';
  40113. }
  40114. }
  40115. return {
  40116. rotation: rotationDiff,
  40117. textAlign: textAlign,
  40118. textVerticalAlign: textVerticalAlign
  40119. };
  40120. }
  40121. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  40122. if (shouldShowAllLabels(axisModel.axis)) {
  40123. return;
  40124. }
  40125. // If min or max are user set, we need to check
  40126. // If the tick on min(max) are overlap on their neighbour tick
  40127. // If they are overlapped, we need to hide the min(max) tick label
  40128. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  40129. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']);
  40130. // FIXME
  40131. // Have not consider onBand yet, where tick els is more than label els.
  40132. labelEls = labelEls || [];
  40133. tickEls = tickEls || [];
  40134. var firstLabel = labelEls[0];
  40135. var nextLabel = labelEls[1];
  40136. var lastLabel = labelEls[labelEls.length - 1];
  40137. var prevLabel = labelEls[labelEls.length - 2];
  40138. var firstTick = tickEls[0];
  40139. var nextTick = tickEls[1];
  40140. var lastTick = tickEls[tickEls.length - 1];
  40141. var prevTick = tickEls[tickEls.length - 2];
  40142. if (showMinLabel === false) {
  40143. ignoreEl(firstLabel);
  40144. ignoreEl(firstTick);
  40145. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  40146. if (showMinLabel) {
  40147. ignoreEl(nextLabel);
  40148. ignoreEl(nextTick);
  40149. } else {
  40150. ignoreEl(firstLabel);
  40151. ignoreEl(firstTick);
  40152. }
  40153. }
  40154. if (showMaxLabel === false) {
  40155. ignoreEl(lastLabel);
  40156. ignoreEl(lastTick);
  40157. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  40158. if (showMaxLabel) {
  40159. ignoreEl(prevLabel);
  40160. ignoreEl(prevTick);
  40161. } else {
  40162. ignoreEl(lastLabel);
  40163. ignoreEl(lastTick);
  40164. }
  40165. }
  40166. }
  40167. function ignoreEl(el) {
  40168. el && (el.ignore = true);
  40169. }
  40170. function isTwoLabelOverlapped(current, next) {
  40171. // current and next has the same rotation.
  40172. var firstRect = current && current.getBoundingRect().clone();
  40173. var nextRect = next && next.getBoundingRect().clone();
  40174. if (!firstRect || !nextRect) {
  40175. return;
  40176. }
  40177. // When checking intersect of two rotated labels, we use mRotationBack
  40178. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  40179. var mRotationBack = identity([]);
  40180. rotate(mRotationBack, mRotationBack, -current.rotation);
  40181. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  40182. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  40183. return firstRect.intersect(nextRect);
  40184. }
  40185. function isNameLocationCenter(nameLocation) {
  40186. return nameLocation === 'middle' || nameLocation === 'center';
  40187. }
  40188. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  40189. var tickEls = [];
  40190. var pt1 = [];
  40191. var pt2 = [];
  40192. for (var i = 0; i < ticksCoords.length; i++) {
  40193. var tickCoord = ticksCoords[i].coord;
  40194. pt1[0] = tickCoord;
  40195. pt1[1] = 0;
  40196. pt2[0] = tickCoord;
  40197. pt2[1] = tickEndCoord;
  40198. if (tickTransform) {
  40199. applyTransform(pt1, pt1, tickTransform);
  40200. applyTransform(pt2, pt2, tickTransform);
  40201. }
  40202. // Tick line, Not use group transform to have better line draw
  40203. var tickEl = new Line({
  40204. shape: {
  40205. x1: pt1[0],
  40206. y1: pt1[1],
  40207. x2: pt2[0],
  40208. y2: pt2[1]
  40209. },
  40210. style: tickLineStyle,
  40211. z2: 2,
  40212. autoBatch: true,
  40213. silent: true
  40214. });
  40215. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  40216. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  40217. tickEls.push(tickEl);
  40218. }
  40219. return tickEls;
  40220. }
  40221. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  40222. var axis = axisModel.axis;
  40223. var tickModel = axisModel.getModel('axisTick');
  40224. var shown = tickModel.get('show');
  40225. if (shown === 'auto' && opt.handleAutoShown) {
  40226. shown = opt.handleAutoShown('axisTick');
  40227. }
  40228. if (!shown || axis.scale.isBlank()) {
  40229. return;
  40230. }
  40231. var lineStyleModel = tickModel.getModel('lineStyle');
  40232. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  40233. var ticksCoords = axis.getTicksCoords();
  40234. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  40235. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  40236. }), 'ticks');
  40237. for (var i = 0; i < ticksEls.length; i++) {
  40238. group.add(ticksEls[i]);
  40239. }
  40240. return ticksEls;
  40241. }
  40242. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  40243. var axis = axisModel.axis;
  40244. var minorTickModel = axisModel.getModel('minorTick');
  40245. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  40246. return;
  40247. }
  40248. var minorTicksCoords = axis.getMinorTicksCoords();
  40249. if (!minorTicksCoords.length) {
  40250. return;
  40251. }
  40252. var lineStyleModel = minorTickModel.getModel('lineStyle');
  40253. var tickEndCoord = tickDirection * minorTickModel.get('length');
  40254. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  40255. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  40256. }));
  40257. for (var i = 0; i < minorTicksCoords.length; i++) {
  40258. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  40259. for (var k = 0; k < minorTicksEls.length; k++) {
  40260. group.add(minorTicksEls[k]);
  40261. }
  40262. }
  40263. }
  40264. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  40265. var axis = axisModel.axis;
  40266. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  40267. if (!show || axis.scale.isBlank()) {
  40268. return;
  40269. }
  40270. var labelModel = axisModel.getModel('axisLabel');
  40271. var labelMargin = labelModel.get('margin');
  40272. var labels = axis.getViewLabels();
  40273. // Special label rotate.
  40274. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$4 / 180;
  40275. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  40276. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  40277. var labelEls = [];
  40278. var silent = AxisBuilder.isLabelSilent(axisModel);
  40279. var triggerEvent = axisModel.get('triggerEvent');
  40280. each(labels, function (labelItem, index) {
  40281. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  40282. var formattedLabel = labelItem.formattedLabel;
  40283. var rawLabel = labelItem.rawLabel;
  40284. var itemLabelModel = labelModel;
  40285. if (rawCategoryData && rawCategoryData[tickValue]) {
  40286. var rawCategoryItem = rawCategoryData[tickValue];
  40287. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  40288. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  40289. }
  40290. }
  40291. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  40292. var tickCoord = axis.dataToCoord(tickValue);
  40293. var align = itemLabelModel.getShallow('align', true) || labelLayout.textAlign;
  40294. var alignMin = retrieve2(itemLabelModel.getShallow('alignMinLabel', true), align);
  40295. var alignMax = retrieve2(itemLabelModel.getShallow('alignMaxLabel', true), align);
  40296. var verticalAlign = itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign;
  40297. var verticalAlignMin = retrieve2(itemLabelModel.getShallow('verticalAlignMinLabel', true), verticalAlign);
  40298. var verticalAlignMax = retrieve2(itemLabelModel.getShallow('verticalAlignMaxLabel', true), verticalAlign);
  40299. var textEl = new ZRText({
  40300. x: tickCoord,
  40301. y: opt.labelOffset + opt.labelDirection * labelMargin,
  40302. rotation: labelLayout.rotation,
  40303. silent: silent,
  40304. z2: 10 + (labelItem.level || 0),
  40305. style: createTextStyle(itemLabelModel, {
  40306. text: formattedLabel,
  40307. align: index === 0 ? alignMin : index === labels.length - 1 ? alignMax : align,
  40308. verticalAlign: index === 0 ? verticalAlignMin : index === labels.length - 1 ? verticalAlignMax : verticalAlign,
  40309. fill: isFunction(textColor) ? textColor(
  40310. // (1) In category axis with data zoom, tick is not the original
  40311. // index of axis.data. So tick should not be exposed to user
  40312. // in category axis.
  40313. // (2) Compatible with previous version, which always use formatted label as
  40314. // input. But in interval scale the formatted label is like '223,445', which
  40315. // maked user replace ','. So we modify it to return original val but remain
  40316. // it as 'string' to avoid error in replacing.
  40317. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  40318. })
  40319. });
  40320. textEl.anid = 'label_' + tickValue;
  40321. // Pack data for mouse event
  40322. if (triggerEvent) {
  40323. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  40324. eventData.targetType = 'axisLabel';
  40325. eventData.value = rawLabel;
  40326. eventData.tickIndex = index;
  40327. if (axis.type === 'category') {
  40328. eventData.dataIndex = tickValue;
  40329. }
  40330. getECData(textEl).eventData = eventData;
  40331. }
  40332. // FIXME
  40333. transformGroup.add(textEl);
  40334. textEl.updateTransform();
  40335. labelEls.push(textEl);
  40336. group.add(textEl);
  40337. textEl.decomposeTransform();
  40338. });
  40339. return labelEls;
  40340. }
  40341. function fixValue(axisModel) {
  40342. var axisInfo = getAxisInfo(axisModel);
  40343. if (!axisInfo) {
  40344. return;
  40345. }
  40346. var axisPointerModel = axisInfo.axisPointerModel;
  40347. var scale = axisInfo.axis.scale;
  40348. var option = axisPointerModel.option;
  40349. var status = axisPointerModel.get('status');
  40350. var value = axisPointerModel.get('value');
  40351. // Parse init value for category and time axis.
  40352. if (value != null) {
  40353. value = scale.parse(value);
  40354. }
  40355. var useHandle = isHandleTrigger(axisPointerModel);
  40356. // If `handle` used, `axisPointer` will always be displayed, so value
  40357. // and status should be initialized.
  40358. if (status == null) {
  40359. option.status = useHandle ? 'show' : 'hide';
  40360. }
  40361. var extent = scale.getExtent().slice();
  40362. extent[0] > extent[1] && extent.reverse();
  40363. if (
  40364. // Pick a value on axis when initializing.
  40365. value == null
  40366. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  40367. // where we should re-pick a value to keep `handle` displaying normally.
  40368. || value > extent[1]) {
  40369. // Make handle displayed on the end of the axis when init, which looks better.
  40370. value = extent[1];
  40371. }
  40372. if (value < extent[0]) {
  40373. value = extent[0];
  40374. }
  40375. option.value = value;
  40376. if (useHandle) {
  40377. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  40378. }
  40379. }
  40380. function getAxisInfo(axisModel) {
  40381. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  40382. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  40383. }
  40384. function getAxisPointerModel(axisModel) {
  40385. var axisInfo = getAxisInfo(axisModel);
  40386. return axisInfo && axisInfo.axisPointerModel;
  40387. }
  40388. function isHandleTrigger(axisPointerModel) {
  40389. return !!axisPointerModel.get(['handle', 'show']);
  40390. }
  40391. /**
  40392. * @param {module:echarts/model/Model} model
  40393. * @return {string} unique key
  40394. */
  40395. function makeKey(model) {
  40396. return model.type + '||' + model.id;
  40397. }
  40398. var axisPointerClazz = {};
  40399. /**
  40400. * Base class of AxisView.
  40401. */
  40402. var AxisView = /** @class */function (_super) {
  40403. __extends(AxisView, _super);
  40404. function AxisView() {
  40405. var _this = _super !== null && _super.apply(this, arguments) || this;
  40406. _this.type = AxisView.type;
  40407. return _this;
  40408. }
  40409. /**
  40410. * @override
  40411. */
  40412. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  40413. // FIXME
  40414. // This process should proformed after coordinate systems updated
  40415. // (axis scale updated), and should be performed each time update.
  40416. // So put it here temporarily, although it is not appropriate to
  40417. // put a model-writing procedure in `view`.
  40418. this.axisPointerClass && fixValue(axisModel);
  40419. _super.prototype.render.apply(this, arguments);
  40420. this._doUpdateAxisPointerClass(axisModel, api, true);
  40421. };
  40422. /**
  40423. * Action handler.
  40424. */
  40425. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  40426. this._doUpdateAxisPointerClass(axisModel, api, false);
  40427. };
  40428. /**
  40429. * @override
  40430. */
  40431. AxisView.prototype.remove = function (ecModel, api) {
  40432. var axisPointer = this._axisPointer;
  40433. axisPointer && axisPointer.remove(api);
  40434. };
  40435. /**
  40436. * @override
  40437. */
  40438. AxisView.prototype.dispose = function (ecModel, api) {
  40439. this._disposeAxisPointer(api);
  40440. _super.prototype.dispose.apply(this, arguments);
  40441. };
  40442. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  40443. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  40444. if (!Clazz) {
  40445. return;
  40446. }
  40447. var axisPointerModel = getAxisPointerModel(axisModel);
  40448. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  40449. };
  40450. AxisView.prototype._disposeAxisPointer = function (api) {
  40451. this._axisPointer && this._axisPointer.dispose(api);
  40452. this._axisPointer = null;
  40453. };
  40454. AxisView.registerAxisPointerClass = function (type, clazz) {
  40455. if ("development" !== 'production') {
  40456. if (axisPointerClazz[type]) {
  40457. throw new Error('axisPointer ' + type + ' exists');
  40458. }
  40459. }
  40460. axisPointerClazz[type] = clazz;
  40461. };
  40462. AxisView.getAxisPointerClass = function (type) {
  40463. return type && axisPointerClazz[type];
  40464. };
  40465. AxisView.type = 'axis';
  40466. return AxisView;
  40467. }(ComponentView);
  40468. var inner$6 = makeInner();
  40469. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  40470. var axis = axisModel.axis;
  40471. if (axis.scale.isBlank()) {
  40472. return;
  40473. }
  40474. // TODO: TYPE
  40475. var splitAreaModel = axisModel.getModel('splitArea');
  40476. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  40477. var areaColors = areaStyleModel.get('color');
  40478. var gridRect = gridModel.coordinateSystem.getRect();
  40479. var ticksCoords = axis.getTicksCoords({
  40480. tickModel: splitAreaModel,
  40481. clamp: true
  40482. });
  40483. if (!ticksCoords.length) {
  40484. return;
  40485. }
  40486. // For Making appropriate splitArea animation, the color and anid
  40487. // should be corresponding to previous one if possible.
  40488. var areaColorsLen = areaColors.length;
  40489. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  40490. var newSplitAreaColors = createHashMap();
  40491. var colorIndex = 0;
  40492. if (lastSplitAreaColors) {
  40493. for (var i = 0; i < ticksCoords.length; i++) {
  40494. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  40495. if (cIndex != null) {
  40496. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  40497. break;
  40498. }
  40499. }
  40500. }
  40501. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  40502. var areaStyle = areaStyleModel.getAreaStyle();
  40503. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  40504. for (var i = 1; i < ticksCoords.length; i++) {
  40505. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  40506. var x = void 0;
  40507. var y = void 0;
  40508. var width = void 0;
  40509. var height = void 0;
  40510. if (axis.isHorizontal()) {
  40511. x = prev;
  40512. y = gridRect.y;
  40513. width = tickCoord - x;
  40514. height = gridRect.height;
  40515. prev = x + width;
  40516. } else {
  40517. x = gridRect.x;
  40518. y = prev;
  40519. width = gridRect.width;
  40520. height = tickCoord - y;
  40521. prev = y + height;
  40522. }
  40523. var tickValue = ticksCoords[i - 1].tickValue;
  40524. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  40525. axisGroup.add(new Rect({
  40526. anid: tickValue != null ? 'area_' + tickValue : null,
  40527. shape: {
  40528. x: x,
  40529. y: y,
  40530. width: width,
  40531. height: height
  40532. },
  40533. style: defaults({
  40534. fill: areaColors[colorIndex]
  40535. }, areaStyle),
  40536. autoBatch: true,
  40537. silent: true
  40538. }));
  40539. colorIndex = (colorIndex + 1) % areaColorsLen;
  40540. }
  40541. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  40542. }
  40543. function rectCoordAxisHandleRemove(axisView) {
  40544. inner$6(axisView).splitAreaColors = null;
  40545. }
  40546. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  40547. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  40548. var CartesianAxisView = /** @class */function (_super) {
  40549. __extends(CartesianAxisView, _super);
  40550. function CartesianAxisView() {
  40551. var _this = _super !== null && _super.apply(this, arguments) || this;
  40552. _this.type = CartesianAxisView.type;
  40553. _this.axisPointerClass = 'CartesianAxisPointer';
  40554. return _this;
  40555. }
  40556. /**
  40557. * @override
  40558. */
  40559. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  40560. this.group.removeAll();
  40561. var oldAxisGroup = this._axisGroup;
  40562. this._axisGroup = new Group();
  40563. this.group.add(this._axisGroup);
  40564. if (!axisModel.get('show')) {
  40565. return;
  40566. }
  40567. var gridModel = axisModel.getCoordSysModel();
  40568. var layout = layout$1(gridModel, axisModel);
  40569. var axisBuilder = new AxisBuilder(axisModel, extend({
  40570. handleAutoShown: function (elementType) {
  40571. var cartesians = gridModel.coordinateSystem.getCartesians();
  40572. for (var i = 0; i < cartesians.length; i++) {
  40573. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  40574. // Still show axis tick or axisLine if other axis is value / log
  40575. return true;
  40576. }
  40577. }
  40578. // Not show axisTick or axisLine if other axis is category / time
  40579. return false;
  40580. }
  40581. }, layout));
  40582. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  40583. this._axisGroup.add(axisBuilder.getGroup());
  40584. each(selfBuilderAttrs, function (name) {
  40585. if (axisModel.get([name, 'show'])) {
  40586. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  40587. }
  40588. }, this);
  40589. // THIS is a special case for bar racing chart.
  40590. // Update the axis label from the natural initial layout to
  40591. // sorted layout should has no animation.
  40592. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  40593. if (!isInitialSortFromBarRacing) {
  40594. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  40595. }
  40596. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  40597. };
  40598. CartesianAxisView.prototype.remove = function () {
  40599. rectCoordAxisHandleRemove(this);
  40600. };
  40601. CartesianAxisView.type = 'cartesianAxis';
  40602. return CartesianAxisView;
  40603. }(AxisView);
  40604. var axisElementBuilders = {
  40605. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  40606. var axis = axisModel.axis;
  40607. if (axis.scale.isBlank()) {
  40608. return;
  40609. }
  40610. var splitLineModel = axisModel.getModel('splitLine');
  40611. var lineStyleModel = splitLineModel.getModel('lineStyle');
  40612. var lineColors = lineStyleModel.get('color');
  40613. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  40614. var gridRect = gridModel.coordinateSystem.getRect();
  40615. var isHorizontal = axis.isHorizontal();
  40616. var lineCount = 0;
  40617. var ticksCoords = axis.getTicksCoords({
  40618. tickModel: splitLineModel
  40619. });
  40620. var p1 = [];
  40621. var p2 = [];
  40622. var lineStyle = lineStyleModel.getLineStyle();
  40623. for (var i = 0; i < ticksCoords.length; i++) {
  40624. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  40625. if (isHorizontal) {
  40626. p1[0] = tickCoord;
  40627. p1[1] = gridRect.y;
  40628. p2[0] = tickCoord;
  40629. p2[1] = gridRect.y + gridRect.height;
  40630. } else {
  40631. p1[0] = gridRect.x;
  40632. p1[1] = tickCoord;
  40633. p2[0] = gridRect.x + gridRect.width;
  40634. p2[1] = tickCoord;
  40635. }
  40636. var colorIndex = lineCount++ % lineColors.length;
  40637. var tickValue = ticksCoords[i].tickValue;
  40638. var line = new Line({
  40639. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  40640. autoBatch: true,
  40641. shape: {
  40642. x1: p1[0],
  40643. y1: p1[1],
  40644. x2: p2[0],
  40645. y2: p2[1]
  40646. },
  40647. style: defaults({
  40648. stroke: lineColors[colorIndex]
  40649. }, lineStyle),
  40650. silent: true
  40651. });
  40652. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  40653. axisGroup.add(line);
  40654. }
  40655. },
  40656. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  40657. var axis = axisModel.axis;
  40658. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  40659. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  40660. var gridRect = gridModel.coordinateSystem.getRect();
  40661. var isHorizontal = axis.isHorizontal();
  40662. var minorTicksCoords = axis.getMinorTicksCoords();
  40663. if (!minorTicksCoords.length) {
  40664. return;
  40665. }
  40666. var p1 = [];
  40667. var p2 = [];
  40668. var lineStyle = lineStyleModel.getLineStyle();
  40669. for (var i = 0; i < minorTicksCoords.length; i++) {
  40670. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  40671. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  40672. if (isHorizontal) {
  40673. p1[0] = tickCoord;
  40674. p1[1] = gridRect.y;
  40675. p2[0] = tickCoord;
  40676. p2[1] = gridRect.y + gridRect.height;
  40677. } else {
  40678. p1[0] = gridRect.x;
  40679. p1[1] = tickCoord;
  40680. p2[0] = gridRect.x + gridRect.width;
  40681. p2[1] = tickCoord;
  40682. }
  40683. var line = new Line({
  40684. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  40685. autoBatch: true,
  40686. shape: {
  40687. x1: p1[0],
  40688. y1: p1[1],
  40689. x2: p2[0],
  40690. y2: p2[1]
  40691. },
  40692. style: lineStyle,
  40693. silent: true
  40694. });
  40695. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  40696. axisGroup.add(line);
  40697. }
  40698. }
  40699. },
  40700. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  40701. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  40702. }
  40703. };
  40704. var CartesianXAxisView = /** @class */function (_super) {
  40705. __extends(CartesianXAxisView, _super);
  40706. function CartesianXAxisView() {
  40707. var _this = _super !== null && _super.apply(this, arguments) || this;
  40708. _this.type = CartesianXAxisView.type;
  40709. return _this;
  40710. }
  40711. CartesianXAxisView.type = 'xAxis';
  40712. return CartesianXAxisView;
  40713. }(CartesianAxisView);
  40714. var CartesianYAxisView = /** @class */function (_super) {
  40715. __extends(CartesianYAxisView, _super);
  40716. function CartesianYAxisView() {
  40717. var _this = _super !== null && _super.apply(this, arguments) || this;
  40718. _this.type = CartesianXAxisView.type;
  40719. return _this;
  40720. }
  40721. CartesianYAxisView.type = 'yAxis';
  40722. return CartesianYAxisView;
  40723. }(CartesianAxisView);
  40724. // Grid view
  40725. var GridView = /** @class */function (_super) {
  40726. __extends(GridView, _super);
  40727. function GridView() {
  40728. var _this = _super !== null && _super.apply(this, arguments) || this;
  40729. _this.type = 'grid';
  40730. return _this;
  40731. }
  40732. GridView.prototype.render = function (gridModel, ecModel) {
  40733. this.group.removeAll();
  40734. if (gridModel.get('show')) {
  40735. this.group.add(new Rect({
  40736. shape: gridModel.coordinateSystem.getRect(),
  40737. style: defaults({
  40738. fill: gridModel.get('backgroundColor')
  40739. }, gridModel.getItemStyle()),
  40740. silent: true,
  40741. z2: -1
  40742. }));
  40743. }
  40744. };
  40745. GridView.type = 'grid';
  40746. return GridView;
  40747. }(ComponentView);
  40748. var extraOption = {
  40749. // gridIndex: 0,
  40750. // gridId: '',
  40751. offset: 0
  40752. };
  40753. function install$4(registers) {
  40754. registers.registerComponentView(GridView);
  40755. registers.registerComponentModel(GridModel);
  40756. registers.registerCoordinateSystem('cartesian2d', Grid);
  40757. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  40758. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  40759. registers.registerComponentView(CartesianXAxisView);
  40760. registers.registerComponentView(CartesianYAxisView);
  40761. registers.registerPreprocessor(function (option) {
  40762. // Only create grid when need
  40763. if (option.xAxis && option.yAxis && !option.grid) {
  40764. option.grid = {};
  40765. }
  40766. });
  40767. }
  40768. var DEFAULT_OPTION = {
  40769. label: {
  40770. enabled: true
  40771. },
  40772. decal: {
  40773. show: false
  40774. }
  40775. };
  40776. var inner$7 = makeInner();
  40777. var decalPaletteScope = {};
  40778. function ariaVisual(ecModel, api) {
  40779. var ariaModel = ecModel.getModel('aria');
  40780. // See "area enabled" detection code in `GlobalModel.ts`.
  40781. if (!ariaModel.get('enabled')) {
  40782. return;
  40783. }
  40784. var defaultOption = clone(DEFAULT_OPTION);
  40785. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  40786. merge(ariaModel.option, defaultOption, false);
  40787. setDecal();
  40788. setLabel();
  40789. function setDecal() {
  40790. var decalModel = ariaModel.getModel('decal');
  40791. var useDecal = decalModel.get('show');
  40792. if (useDecal) {
  40793. // Each type of series use one scope.
  40794. // Pie and funnel are using different scopes.
  40795. var paletteScopeGroupByType_1 = createHashMap();
  40796. ecModel.eachSeries(function (seriesModel) {
  40797. if (seriesModel.isColorBySeries()) {
  40798. return;
  40799. }
  40800. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  40801. if (!decalScope) {
  40802. decalScope = {};
  40803. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  40804. }
  40805. inner$7(seriesModel).scope = decalScope;
  40806. });
  40807. ecModel.eachRawSeries(function (seriesModel) {
  40808. if (ecModel.isSeriesFiltered(seriesModel)) {
  40809. return;
  40810. }
  40811. if (isFunction(seriesModel.enableAriaDecal)) {
  40812. // Let series define how to use decal palette on data
  40813. seriesModel.enableAriaDecal();
  40814. return;
  40815. }
  40816. var data = seriesModel.getData();
  40817. if (!seriesModel.isColorBySeries()) {
  40818. var dataAll_1 = seriesModel.getRawData();
  40819. var idxMap_1 = {};
  40820. var decalScope_1 = inner$7(seriesModel).scope;
  40821. data.each(function (idx) {
  40822. var rawIdx = data.getRawIndex(idx);
  40823. idxMap_1[rawIdx] = idx;
  40824. });
  40825. var dataCount_1 = dataAll_1.count();
  40826. dataAll_1.each(function (rawIdx) {
  40827. var idx = idxMap_1[rawIdx];
  40828. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  40829. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  40830. var specifiedDecal = data.getItemVisual(idx, 'decal');
  40831. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  40832. });
  40833. } else {
  40834. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  40835. var specifiedDecal = data.getVisual('decal');
  40836. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  40837. }
  40838. function mergeDecal(specifiedDecal, paletteDecal) {
  40839. // Merge decal from palette to decal from itemStyle.
  40840. // User do not need to specify all of the decal props.
  40841. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  40842. resultDecal.dirty = true;
  40843. return resultDecal;
  40844. }
  40845. });
  40846. }
  40847. }
  40848. function setLabel() {
  40849. var dom = api.getZr().dom;
  40850. // TODO: support for SSR
  40851. if (!dom) {
  40852. return;
  40853. }
  40854. var labelLocale = ecModel.getLocaleModel().get('aria');
  40855. var labelModel = ariaModel.getModel('label');
  40856. labelModel.option = defaults(labelModel.option, labelLocale);
  40857. if (!labelModel.get('enabled')) {
  40858. return;
  40859. }
  40860. if (labelModel.get('description')) {
  40861. dom.setAttribute('aria-label', labelModel.get('description'));
  40862. return;
  40863. }
  40864. var seriesCnt = ecModel.getSeriesCount();
  40865. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  40866. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  40867. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  40868. var ariaLabel;
  40869. if (seriesCnt < 1) {
  40870. // No series, no aria label
  40871. return;
  40872. } else {
  40873. var title = getTitle();
  40874. if (title) {
  40875. var withTitle = labelModel.get(['general', 'withTitle']);
  40876. ariaLabel = replace(withTitle, {
  40877. title: title
  40878. });
  40879. } else {
  40880. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  40881. }
  40882. var seriesLabels_1 = [];
  40883. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  40884. ariaLabel += replace(prefix, {
  40885. seriesCount: seriesCnt
  40886. });
  40887. ecModel.eachSeries(function (seriesModel, idx) {
  40888. if (idx < displaySeriesCnt) {
  40889. var seriesLabel = void 0;
  40890. var seriesName = seriesModel.get('name');
  40891. var withName = seriesName ? 'withName' : 'withoutName';
  40892. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  40893. seriesLabel = replace(seriesLabel, {
  40894. seriesId: seriesModel.seriesIndex,
  40895. seriesName: seriesModel.get('name'),
  40896. seriesType: getSeriesTypeName(seriesModel.subType)
  40897. });
  40898. var data = seriesModel.getData();
  40899. if (data.count() > maxDataCnt) {
  40900. // Show part of data
  40901. var partialLabel = labelModel.get(['data', 'partialData']);
  40902. seriesLabel += replace(partialLabel, {
  40903. displayCnt: maxDataCnt
  40904. });
  40905. } else {
  40906. seriesLabel += labelModel.get(['data', 'allData']);
  40907. }
  40908. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  40909. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  40910. var dataLabels = [];
  40911. for (var i = 0; i < data.count(); i++) {
  40912. if (i < maxDataCnt) {
  40913. var name_1 = data.getName(i);
  40914. var value = data.getValues(i);
  40915. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  40916. dataLabels.push(replace(dataLabel, {
  40917. name: name_1,
  40918. value: value.join(middleSeparator_1)
  40919. }));
  40920. }
  40921. }
  40922. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  40923. seriesLabels_1.push(seriesLabel);
  40924. }
  40925. });
  40926. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  40927. var middleSeparator = separatorModel.get('middle');
  40928. var endSeparator = separatorModel.get('end');
  40929. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  40930. dom.setAttribute('aria-label', ariaLabel);
  40931. }
  40932. }
  40933. function replace(str, keyValues) {
  40934. if (!isString(str)) {
  40935. return str;
  40936. }
  40937. var result = str;
  40938. each(keyValues, function (value, key) {
  40939. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  40940. });
  40941. return result;
  40942. }
  40943. function getTitle() {
  40944. var title = ecModel.get('title');
  40945. if (title && title.length) {
  40946. title = title[0];
  40947. }
  40948. return title && title.text;
  40949. }
  40950. function getSeriesTypeName(type) {
  40951. var typeNames = ecModel.getLocaleModel().get(['series', 'typeNames']);
  40952. return typeNames[type] || typeNames.chart;
  40953. }
  40954. }
  40955. function ariaPreprocessor(option) {
  40956. if (!option || !option.aria) {
  40957. return;
  40958. }
  40959. var aria = option.aria;
  40960. // aria.show is deprecated and should use aria.enabled instead
  40961. if (aria.show != null) {
  40962. aria.enabled = aria.show;
  40963. }
  40964. aria.label = aria.label || {};
  40965. // move description, general, series, data to be under aria.label
  40966. each(['description', 'general', 'series', 'data'], function (name) {
  40967. if (aria[name] != null) {
  40968. aria.label[name] = aria[name];
  40969. }
  40970. });
  40971. }
  40972. function install$5(registers) {
  40973. registers.registerPreprocessor(ariaPreprocessor);
  40974. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  40975. }
  40976. var DatasetModel = /** @class */function (_super) {
  40977. __extends(DatasetModel, _super);
  40978. function DatasetModel() {
  40979. var _this = _super !== null && _super.apply(this, arguments) || this;
  40980. _this.type = 'dataset';
  40981. return _this;
  40982. }
  40983. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  40984. _super.prototype.init.call(this, option, parentModel, ecModel);
  40985. this._sourceManager = new SourceManager(this);
  40986. disableTransformOptionMerge(this);
  40987. };
  40988. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  40989. _super.prototype.mergeOption.call(this, newOption, ecModel);
  40990. disableTransformOptionMerge(this);
  40991. };
  40992. DatasetModel.prototype.optionUpdated = function () {
  40993. this._sourceManager.dirty();
  40994. };
  40995. DatasetModel.prototype.getSourceManager = function () {
  40996. return this._sourceManager;
  40997. };
  40998. DatasetModel.type = 'dataset';
  40999. DatasetModel.defaultOption = {
  41000. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  41001. };
  41002. return DatasetModel;
  41003. }(ComponentModel);
  41004. var DatasetView = /** @class */function (_super) {
  41005. __extends(DatasetView, _super);
  41006. function DatasetView() {
  41007. var _this = _super !== null && _super.apply(this, arguments) || this;
  41008. _this.type = 'dataset';
  41009. return _this;
  41010. }
  41011. DatasetView.type = 'dataset';
  41012. return DatasetView;
  41013. }(ComponentView);
  41014. function install$6(registers) {
  41015. registers.registerComponentModel(DatasetModel);
  41016. registers.registerComponentView(DatasetView);
  41017. }
  41018. use([install]);
  41019. use([install$1, install$2, install$3]);
  41020. use([install$4, install$5, install$6]);
  41021. exports.Axis = Axis;
  41022. exports.ChartView = ChartView;
  41023. exports.ComponentModel = ComponentModel;
  41024. exports.ComponentView = ComponentView;
  41025. exports.List = SeriesData;
  41026. exports.Model = Model;
  41027. exports.PRIORITY = PRIORITY;
  41028. exports.SeriesModel = SeriesModel;
  41029. exports.color = color;
  41030. exports.connect = connect;
  41031. exports.dataTool = dataTool;
  41032. exports.dependencies = dependencies;
  41033. exports.disConnect = disConnect;
  41034. exports.disconnect = disconnect;
  41035. exports.dispose = dispose$1;
  41036. exports.env = env;
  41037. exports.extendChartView = extendChartView;
  41038. exports.extendComponentModel = extendComponentModel;
  41039. exports.extendComponentView = extendComponentView;
  41040. exports.extendSeriesModel = extendSeriesModel;
  41041. exports.format = format$1;
  41042. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  41043. exports.getInstanceByDom = getInstanceByDom;
  41044. exports.getInstanceById = getInstanceById;
  41045. exports.getMap = getMap;
  41046. exports.graphic = graphic;
  41047. exports.helper = helper;
  41048. exports.init = init$1;
  41049. exports.innerDrawElementOnCanvas = brushSingle;
  41050. exports.matrix = matrix;
  41051. exports.number = number;
  41052. exports.parseGeoJSON = parseGeoJSON;
  41053. exports.parseGeoJson = parseGeoJSON;
  41054. exports.registerAction = registerAction;
  41055. exports.registerCoordinateSystem = registerCoordinateSystem;
  41056. exports.registerLayout = registerLayout;
  41057. exports.registerLoading = registerLoading;
  41058. exports.registerLocale = registerLocale;
  41059. exports.registerMap = registerMap;
  41060. exports.registerPostInit = registerPostInit;
  41061. exports.registerPostUpdate = registerPostUpdate;
  41062. exports.registerPreprocessor = registerPreprocessor;
  41063. exports.registerProcessor = registerProcessor;
  41064. exports.registerTheme = registerTheme;
  41065. exports.registerTransform = registerTransform;
  41066. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  41067. exports.registerVisual = registerVisual;
  41068. exports.setCanvasCreator = setCanvasCreator;
  41069. exports.setPlatformAPI = setPlatformAPI;
  41070. exports.throttle = throttle;
  41071. exports.time = time;
  41072. exports.use = use;
  41073. exports.util = util$1;
  41074. exports.vector = vector;
  41075. exports.version = version$1;
  41076. exports.zrUtil = util;
  41077. exports.zrender = zrender;
  41078. Object.defineProperty(exports, '__esModule', { value: true });
  41079. })));
  41080. //# sourceMappingURL=echarts.simple.js.map