echarts.simple.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240
  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. env.node = true;
  86. env.svgSupported = true;
  87. }
  88. else {
  89. detect(navigator.userAgent, env);
  90. }
  91. function detect(ua, env) {
  92. var browser = env.browser;
  93. var firefox = ua.match(/Firefox\/([\d.]+)/);
  94. var ie = ua.match(/MSIE\s([\d.]+)/)
  95. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  96. var edge = ua.match(/Edge?\/([\d.]+)/);
  97. var weChat = (/micromessenger/i).test(ua);
  98. if (firefox) {
  99. browser.firefox = true;
  100. browser.version = firefox[1];
  101. }
  102. if (ie) {
  103. browser.ie = true;
  104. browser.version = ie[1];
  105. }
  106. if (edge) {
  107. browser.edge = true;
  108. browser.version = edge[1];
  109. browser.newEdge = +edge[1].split('.')[0] > 18;
  110. }
  111. if (weChat) {
  112. browser.weChat = true;
  113. }
  114. env.svgSupported = typeof SVGRect !== 'undefined';
  115. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  116. env.pointerEventsSupported = 'onpointerdown' in window
  117. && (browser.edge || (browser.ie && +browser.version >= 11));
  118. env.domSupported = typeof document !== 'undefined';
  119. var style = document.documentElement.style;
  120. env.transform3dSupported = ((browser.ie && 'transition' in style)
  121. || browser.edge
  122. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  123. || 'MozPerspective' in style)
  124. && !('OTransition' in style);
  125. env.transformSupported = env.transform3dSupported
  126. || (browser.ie && +browser.version >= 9);
  127. }
  128. var DEFAULT_FONT_SIZE = 12;
  129. var DEFAULT_FONT_FAMILY = 'sans-serif';
  130. var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  131. var OFFSET = 20;
  132. var SCALE = 100;
  133. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  134. function getTextWidthMap(mapStr) {
  135. var map = {};
  136. if (typeof JSON === 'undefined') {
  137. return map;
  138. }
  139. for (var i = 0; i < mapStr.length; i++) {
  140. var char = String.fromCharCode(i + 32);
  141. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  142. map[char] = size;
  143. }
  144. return map;
  145. }
  146. var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  147. var platformApi = {
  148. createCanvas: function () {
  149. return typeof document !== 'undefined'
  150. && document.createElement('canvas');
  151. },
  152. measureText: (function () {
  153. var _ctx;
  154. var _cachedFont;
  155. return function (text, font) {
  156. if (!_ctx) {
  157. var canvas = platformApi.createCanvas();
  158. _ctx = canvas && canvas.getContext('2d');
  159. }
  160. if (_ctx) {
  161. if (_cachedFont !== font) {
  162. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  163. }
  164. return _ctx.measureText(text);
  165. }
  166. else {
  167. text = text || '';
  168. font = font || DEFAULT_FONT;
  169. var res = /^([0-9]*?)px$/.exec(font);
  170. var fontSize = +(res && res[1]) || DEFAULT_FONT_SIZE;
  171. var width = 0;
  172. if (font.indexOf('mono') >= 0) {
  173. width = fontSize * text.length;
  174. }
  175. else {
  176. for (var i = 0; i < text.length; i++) {
  177. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  178. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  179. }
  180. }
  181. return { width: width };
  182. }
  183. };
  184. })(),
  185. loadImage: function (src, onload, onerror) {
  186. var image = new Image();
  187. image.onload = onload;
  188. image.onerror = onerror;
  189. image.src = src;
  190. return image;
  191. }
  192. };
  193. function setPlatformAPI(newPlatformApis) {
  194. for (var key in platformApi) {
  195. if (newPlatformApis[key]) {
  196. platformApi[key] = newPlatformApis[key];
  197. }
  198. }
  199. }
  200. var BUILTIN_OBJECT = reduce([
  201. 'Function',
  202. 'RegExp',
  203. 'Date',
  204. 'Error',
  205. 'CanvasGradient',
  206. 'CanvasPattern',
  207. 'Image',
  208. 'Canvas'
  209. ], function (obj, val) {
  210. obj['[object ' + val + ']'] = true;
  211. return obj;
  212. }, {});
  213. var TYPED_ARRAY = reduce([
  214. 'Int8',
  215. 'Uint8',
  216. 'Uint8Clamped',
  217. 'Int16',
  218. 'Uint16',
  219. 'Int32',
  220. 'Uint32',
  221. 'Float32',
  222. 'Float64'
  223. ], function (obj, val) {
  224. obj['[object ' + val + 'Array]'] = true;
  225. return obj;
  226. }, {});
  227. var objToString = Object.prototype.toString;
  228. var arrayProto = Array.prototype;
  229. var nativeForEach = arrayProto.forEach;
  230. var nativeFilter = arrayProto.filter;
  231. var nativeSlice = arrayProto.slice;
  232. var nativeMap = arrayProto.map;
  233. var ctorFunction = function () { }.constructor;
  234. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  235. var protoKey = '__proto__';
  236. var idStart = 0x0907;
  237. function guid() {
  238. return idStart++;
  239. }
  240. function logError() {
  241. var args = [];
  242. for (var _i = 0; _i < arguments.length; _i++) {
  243. args[_i] = arguments[_i];
  244. }
  245. if (typeof console !== 'undefined') {
  246. console.error.apply(console, args);
  247. }
  248. }
  249. function clone(source) {
  250. if (source == null || typeof source !== 'object') {
  251. return source;
  252. }
  253. var result = source;
  254. var typeStr = objToString.call(source);
  255. if (typeStr === '[object Array]') {
  256. if (!isPrimitive(source)) {
  257. result = [];
  258. for (var i = 0, len = source.length; i < len; i++) {
  259. result[i] = clone(source[i]);
  260. }
  261. }
  262. }
  263. else if (TYPED_ARRAY[typeStr]) {
  264. if (!isPrimitive(source)) {
  265. var Ctor = source.constructor;
  266. if (Ctor.from) {
  267. result = Ctor.from(source);
  268. }
  269. else {
  270. result = new Ctor(source.length);
  271. for (var i = 0, len = source.length; i < len; i++) {
  272. result[i] = source[i];
  273. }
  274. }
  275. }
  276. }
  277. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  278. result = {};
  279. for (var key in source) {
  280. if (source.hasOwnProperty(key) && key !== protoKey) {
  281. result[key] = clone(source[key]);
  282. }
  283. }
  284. }
  285. return result;
  286. }
  287. function merge(target, source, overwrite) {
  288. if (!isObject(source) || !isObject(target)) {
  289. return overwrite ? clone(source) : target;
  290. }
  291. for (var key in source) {
  292. if (source.hasOwnProperty(key) && key !== protoKey) {
  293. var targetProp = target[key];
  294. var sourceProp = source[key];
  295. if (isObject(sourceProp)
  296. && isObject(targetProp)
  297. && !isArray(sourceProp)
  298. && !isArray(targetProp)
  299. && !isDom(sourceProp)
  300. && !isDom(targetProp)
  301. && !isBuiltInObject(sourceProp)
  302. && !isBuiltInObject(targetProp)
  303. && !isPrimitive(sourceProp)
  304. && !isPrimitive(targetProp)) {
  305. merge(targetProp, sourceProp, overwrite);
  306. }
  307. else if (overwrite || !(key in target)) {
  308. target[key] = clone(source[key]);
  309. }
  310. }
  311. }
  312. return target;
  313. }
  314. function mergeAll(targetAndSources, overwrite) {
  315. var result = targetAndSources[0];
  316. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  317. result = merge(result, targetAndSources[i], overwrite);
  318. }
  319. return result;
  320. }
  321. function extend(target, source) {
  322. if (Object.assign) {
  323. Object.assign(target, source);
  324. }
  325. else {
  326. for (var key in source) {
  327. if (source.hasOwnProperty(key) && key !== protoKey) {
  328. target[key] = source[key];
  329. }
  330. }
  331. }
  332. return target;
  333. }
  334. function defaults(target, source, overlay) {
  335. var keysArr = keys(source);
  336. for (var i = 0; i < keysArr.length; i++) {
  337. var key = keysArr[i];
  338. if ((overlay ? source[key] != null : target[key] == null)) {
  339. target[key] = source[key];
  340. }
  341. }
  342. return target;
  343. }
  344. var createCanvas = platformApi.createCanvas;
  345. function indexOf(array, value) {
  346. if (array) {
  347. if (array.indexOf) {
  348. return array.indexOf(value);
  349. }
  350. for (var i = 0, len = array.length; i < len; i++) {
  351. if (array[i] === value) {
  352. return i;
  353. }
  354. }
  355. }
  356. return -1;
  357. }
  358. function inherits(clazz, baseClazz) {
  359. var clazzPrototype = clazz.prototype;
  360. function F() { }
  361. F.prototype = baseClazz.prototype;
  362. clazz.prototype = new F();
  363. for (var prop in clazzPrototype) {
  364. if (clazzPrototype.hasOwnProperty(prop)) {
  365. clazz.prototype[prop] = clazzPrototype[prop];
  366. }
  367. }
  368. clazz.prototype.constructor = clazz;
  369. clazz.superClass = baseClazz;
  370. }
  371. function mixin(target, source, override) {
  372. target = 'prototype' in target ? target.prototype : target;
  373. source = 'prototype' in source ? source.prototype : source;
  374. if (Object.getOwnPropertyNames) {
  375. var keyList = Object.getOwnPropertyNames(source);
  376. for (var i = 0; i < keyList.length; i++) {
  377. var key = keyList[i];
  378. if (key !== 'constructor') {
  379. if ((override ? source[key] != null : target[key] == null)) {
  380. target[key] = source[key];
  381. }
  382. }
  383. }
  384. }
  385. else {
  386. defaults(target, source, override);
  387. }
  388. }
  389. function isArrayLike(data) {
  390. if (!data) {
  391. return false;
  392. }
  393. if (typeof data === 'string') {
  394. return false;
  395. }
  396. return typeof data.length === 'number';
  397. }
  398. function each(arr, cb, context) {
  399. if (!(arr && cb)) {
  400. return;
  401. }
  402. if (arr.forEach && arr.forEach === nativeForEach) {
  403. arr.forEach(cb, context);
  404. }
  405. else if (arr.length === +arr.length) {
  406. for (var i = 0, len = arr.length; i < len; i++) {
  407. cb.call(context, arr[i], i, arr);
  408. }
  409. }
  410. else {
  411. for (var key in arr) {
  412. if (arr.hasOwnProperty(key)) {
  413. cb.call(context, arr[key], key, arr);
  414. }
  415. }
  416. }
  417. }
  418. function map(arr, cb, context) {
  419. if (!arr) {
  420. return [];
  421. }
  422. if (!cb) {
  423. return slice(arr);
  424. }
  425. if (arr.map && arr.map === nativeMap) {
  426. return arr.map(cb, context);
  427. }
  428. else {
  429. var result = [];
  430. for (var i = 0, len = arr.length; i < len; i++) {
  431. result.push(cb.call(context, arr[i], i, arr));
  432. }
  433. return result;
  434. }
  435. }
  436. function reduce(arr, cb, memo, context) {
  437. if (!(arr && cb)) {
  438. return;
  439. }
  440. for (var i = 0, len = arr.length; i < len; i++) {
  441. memo = cb.call(context, memo, arr[i], i, arr);
  442. }
  443. return memo;
  444. }
  445. function filter(arr, cb, context) {
  446. if (!arr) {
  447. return [];
  448. }
  449. if (!cb) {
  450. return slice(arr);
  451. }
  452. if (arr.filter && arr.filter === nativeFilter) {
  453. return arr.filter(cb, context);
  454. }
  455. else {
  456. var result = [];
  457. for (var i = 0, len = arr.length; i < len; i++) {
  458. if (cb.call(context, arr[i], i, arr)) {
  459. result.push(arr[i]);
  460. }
  461. }
  462. return result;
  463. }
  464. }
  465. function find(arr, cb, context) {
  466. if (!(arr && cb)) {
  467. return;
  468. }
  469. for (var i = 0, len = arr.length; i < len; i++) {
  470. if (cb.call(context, arr[i], i, arr)) {
  471. return arr[i];
  472. }
  473. }
  474. }
  475. function keys(obj) {
  476. if (!obj) {
  477. return [];
  478. }
  479. if (Object.keys) {
  480. return Object.keys(obj);
  481. }
  482. var keyList = [];
  483. for (var key in obj) {
  484. if (obj.hasOwnProperty(key)) {
  485. keyList.push(key);
  486. }
  487. }
  488. return keyList;
  489. }
  490. function bindPolyfill(func, context) {
  491. var args = [];
  492. for (var _i = 2; _i < arguments.length; _i++) {
  493. args[_i - 2] = arguments[_i];
  494. }
  495. return function () {
  496. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  497. };
  498. }
  499. var bind = (protoFunction && isFunction(protoFunction.bind))
  500. ? protoFunction.call.bind(protoFunction.bind)
  501. : bindPolyfill;
  502. function curry(func) {
  503. var args = [];
  504. for (var _i = 1; _i < arguments.length; _i++) {
  505. args[_i - 1] = arguments[_i];
  506. }
  507. return function () {
  508. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  509. };
  510. }
  511. function isArray(value) {
  512. if (Array.isArray) {
  513. return Array.isArray(value);
  514. }
  515. return objToString.call(value) === '[object Array]';
  516. }
  517. function isFunction(value) {
  518. return typeof value === 'function';
  519. }
  520. function isString(value) {
  521. return typeof value === 'string';
  522. }
  523. function isStringSafe(value) {
  524. return objToString.call(value) === '[object String]';
  525. }
  526. function isNumber(value) {
  527. return typeof value === 'number';
  528. }
  529. function isObject(value) {
  530. var type = typeof value;
  531. return type === 'function' || (!!value && type === 'object');
  532. }
  533. function isBuiltInObject(value) {
  534. return !!BUILTIN_OBJECT[objToString.call(value)];
  535. }
  536. function isTypedArray(value) {
  537. return !!TYPED_ARRAY[objToString.call(value)];
  538. }
  539. function isDom(value) {
  540. return typeof value === 'object'
  541. && typeof value.nodeType === 'number'
  542. && typeof value.ownerDocument === 'object';
  543. }
  544. function isGradientObject(value) {
  545. return value.colorStops != null;
  546. }
  547. function isImagePatternObject(value) {
  548. return value.image != null;
  549. }
  550. function isRegExp(value) {
  551. return objToString.call(value) === '[object RegExp]';
  552. }
  553. function eqNaN(value) {
  554. return value !== value;
  555. }
  556. function retrieve() {
  557. var args = [];
  558. for (var _i = 0; _i < arguments.length; _i++) {
  559. args[_i] = arguments[_i];
  560. }
  561. for (var i = 0, len = args.length; i < len; i++) {
  562. if (args[i] != null) {
  563. return args[i];
  564. }
  565. }
  566. }
  567. function retrieve2(value0, value1) {
  568. return value0 != null
  569. ? value0
  570. : value1;
  571. }
  572. function retrieve3(value0, value1, value2) {
  573. return value0 != null
  574. ? value0
  575. : value1 != null
  576. ? value1
  577. : value2;
  578. }
  579. function slice(arr) {
  580. var args = [];
  581. for (var _i = 1; _i < arguments.length; _i++) {
  582. args[_i - 1] = arguments[_i];
  583. }
  584. return nativeSlice.apply(arr, args);
  585. }
  586. function normalizeCssArray(val) {
  587. if (typeof (val) === 'number') {
  588. return [val, val, val, val];
  589. }
  590. var len = val.length;
  591. if (len === 2) {
  592. return [val[0], val[1], val[0], val[1]];
  593. }
  594. else if (len === 3) {
  595. return [val[0], val[1], val[2], val[1]];
  596. }
  597. return val;
  598. }
  599. function assert(condition, message) {
  600. if (!condition) {
  601. throw new Error(message);
  602. }
  603. }
  604. function trim(str) {
  605. if (str == null) {
  606. return null;
  607. }
  608. else if (typeof str.trim === 'function') {
  609. return str.trim();
  610. }
  611. else {
  612. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  613. }
  614. }
  615. var primitiveKey = '__ec_primitive__';
  616. function setAsPrimitive(obj) {
  617. obj[primitiveKey] = true;
  618. }
  619. function isPrimitive(obj) {
  620. return obj[primitiveKey];
  621. }
  622. var HashMap = (function () {
  623. function HashMap(obj) {
  624. this.data = {};
  625. var isArr = isArray(obj);
  626. this.data = {};
  627. var thisMap = this;
  628. (obj instanceof HashMap)
  629. ? obj.each(visit)
  630. : (obj && each(obj, visit));
  631. function visit(value, key) {
  632. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  633. }
  634. }
  635. HashMap.prototype.get = function (key) {
  636. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  637. };
  638. HashMap.prototype.set = function (key, value) {
  639. return (this.data[key] = value);
  640. };
  641. HashMap.prototype.each = function (cb, context) {
  642. for (var key in this.data) {
  643. if (this.data.hasOwnProperty(key)) {
  644. cb.call(context, this.data[key], key);
  645. }
  646. }
  647. };
  648. HashMap.prototype.keys = function () {
  649. return keys(this.data);
  650. };
  651. HashMap.prototype.removeKey = function (key) {
  652. delete this.data[key];
  653. };
  654. return HashMap;
  655. }());
  656. function createHashMap(obj) {
  657. return new HashMap(obj);
  658. }
  659. function concatArray(a, b) {
  660. var newArray = new a.constructor(a.length + b.length);
  661. for (var i = 0; i < a.length; i++) {
  662. newArray[i] = a[i];
  663. }
  664. var offset = a.length;
  665. for (var i = 0; i < b.length; i++) {
  666. newArray[i + offset] = b[i];
  667. }
  668. return newArray;
  669. }
  670. function createObject(proto, properties) {
  671. var obj;
  672. if (Object.create) {
  673. obj = Object.create(proto);
  674. }
  675. else {
  676. var StyleCtor = function () { };
  677. StyleCtor.prototype = proto;
  678. obj = new StyleCtor();
  679. }
  680. if (properties) {
  681. extend(obj, properties);
  682. }
  683. return obj;
  684. }
  685. function disableUserSelect(dom) {
  686. var domStyle = dom.style;
  687. domStyle.webkitUserSelect = 'none';
  688. domStyle.userSelect = 'none';
  689. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  690. domStyle['-webkit-touch-callout'] = 'none';
  691. }
  692. function hasOwn(own, prop) {
  693. return own.hasOwnProperty(prop);
  694. }
  695. function noop() { }
  696. var RADIAN_TO_DEGREE = 180 / Math.PI;
  697. var util = /*#__PURE__*/Object.freeze({
  698. __proto__: null,
  699. guid: guid,
  700. logError: logError,
  701. clone: clone,
  702. merge: merge,
  703. mergeAll: mergeAll,
  704. extend: extend,
  705. defaults: defaults,
  706. createCanvas: createCanvas,
  707. indexOf: indexOf,
  708. inherits: inherits,
  709. mixin: mixin,
  710. isArrayLike: isArrayLike,
  711. each: each,
  712. map: map,
  713. reduce: reduce,
  714. filter: filter,
  715. find: find,
  716. keys: keys,
  717. bind: bind,
  718. curry: curry,
  719. isArray: isArray,
  720. isFunction: isFunction,
  721. isString: isString,
  722. isStringSafe: isStringSafe,
  723. isNumber: isNumber,
  724. isObject: isObject,
  725. isBuiltInObject: isBuiltInObject,
  726. isTypedArray: isTypedArray,
  727. isDom: isDom,
  728. isGradientObject: isGradientObject,
  729. isImagePatternObject: isImagePatternObject,
  730. isRegExp: isRegExp,
  731. eqNaN: eqNaN,
  732. retrieve: retrieve,
  733. retrieve2: retrieve2,
  734. retrieve3: retrieve3,
  735. slice: slice,
  736. normalizeCssArray: normalizeCssArray,
  737. assert: assert,
  738. trim: trim,
  739. setAsPrimitive: setAsPrimitive,
  740. isPrimitive: isPrimitive,
  741. HashMap: HashMap,
  742. createHashMap: createHashMap,
  743. concatArray: concatArray,
  744. createObject: createObject,
  745. disableUserSelect: disableUserSelect,
  746. hasOwn: hasOwn,
  747. noop: noop,
  748. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE
  749. });
  750. function create(x, y) {
  751. if (x == null) {
  752. x = 0;
  753. }
  754. if (y == null) {
  755. y = 0;
  756. }
  757. return [x, y];
  758. }
  759. function copy(out, v) {
  760. out[0] = v[0];
  761. out[1] = v[1];
  762. return out;
  763. }
  764. function clone$1(v) {
  765. return [v[0], v[1]];
  766. }
  767. function set(out, a, b) {
  768. out[0] = a;
  769. out[1] = b;
  770. return out;
  771. }
  772. function add(out, v1, v2) {
  773. out[0] = v1[0] + v2[0];
  774. out[1] = v1[1] + v2[1];
  775. return out;
  776. }
  777. function scaleAndAdd(out, v1, v2, a) {
  778. out[0] = v1[0] + v2[0] * a;
  779. out[1] = v1[1] + v2[1] * a;
  780. return out;
  781. }
  782. function sub(out, v1, v2) {
  783. out[0] = v1[0] - v2[0];
  784. out[1] = v1[1] - v2[1];
  785. return out;
  786. }
  787. function len(v) {
  788. return Math.sqrt(lenSquare(v));
  789. }
  790. var length = len;
  791. function lenSquare(v) {
  792. return v[0] * v[0] + v[1] * v[1];
  793. }
  794. var lengthSquare = lenSquare;
  795. function mul(out, v1, v2) {
  796. out[0] = v1[0] * v2[0];
  797. out[1] = v1[1] * v2[1];
  798. return out;
  799. }
  800. function div(out, v1, v2) {
  801. out[0] = v1[0] / v2[0];
  802. out[1] = v1[1] / v2[1];
  803. return out;
  804. }
  805. function dot(v1, v2) {
  806. return v1[0] * v2[0] + v1[1] * v2[1];
  807. }
  808. function scale(out, v, s) {
  809. out[0] = v[0] * s;
  810. out[1] = v[1] * s;
  811. return out;
  812. }
  813. function normalize(out, v) {
  814. var d = len(v);
  815. if (d === 0) {
  816. out[0] = 0;
  817. out[1] = 0;
  818. }
  819. else {
  820. out[0] = v[0] / d;
  821. out[1] = v[1] / d;
  822. }
  823. return out;
  824. }
  825. function distance(v1, v2) {
  826. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  827. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  828. }
  829. var dist = distance;
  830. function distanceSquare(v1, v2) {
  831. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  832. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  833. }
  834. var distSquare = distanceSquare;
  835. function negate(out, v) {
  836. out[0] = -v[0];
  837. out[1] = -v[1];
  838. return out;
  839. }
  840. function lerp(out, v1, v2, t) {
  841. out[0] = v1[0] + t * (v2[0] - v1[0]);
  842. out[1] = v1[1] + t * (v2[1] - v1[1]);
  843. return out;
  844. }
  845. function applyTransform(out, v, m) {
  846. var x = v[0];
  847. var y = v[1];
  848. out[0] = m[0] * x + m[2] * y + m[4];
  849. out[1] = m[1] * x + m[3] * y + m[5];
  850. return out;
  851. }
  852. function min(out, v1, v2) {
  853. out[0] = Math.min(v1[0], v2[0]);
  854. out[1] = Math.min(v1[1], v2[1]);
  855. return out;
  856. }
  857. function max(out, v1, v2) {
  858. out[0] = Math.max(v1[0], v2[0]);
  859. out[1] = Math.max(v1[1], v2[1]);
  860. return out;
  861. }
  862. var vector = /*#__PURE__*/Object.freeze({
  863. __proto__: null,
  864. create: create,
  865. copy: copy,
  866. clone: clone$1,
  867. set: set,
  868. add: add,
  869. scaleAndAdd: scaleAndAdd,
  870. sub: sub,
  871. len: len,
  872. length: length,
  873. lenSquare: lenSquare,
  874. lengthSquare: lengthSquare,
  875. mul: mul,
  876. div: div,
  877. dot: dot,
  878. scale: scale,
  879. normalize: normalize,
  880. distance: distance,
  881. dist: dist,
  882. distanceSquare: distanceSquare,
  883. distSquare: distSquare,
  884. negate: negate,
  885. lerp: lerp,
  886. applyTransform: applyTransform,
  887. min: min,
  888. max: max
  889. });
  890. var Param = (function () {
  891. function Param(target, e) {
  892. this.target = target;
  893. this.topTarget = e && e.topTarget;
  894. }
  895. return Param;
  896. }());
  897. var Draggable = (function () {
  898. function Draggable(handler) {
  899. this.handler = handler;
  900. handler.on('mousedown', this._dragStart, this);
  901. handler.on('mousemove', this._drag, this);
  902. handler.on('mouseup', this._dragEnd, this);
  903. }
  904. Draggable.prototype._dragStart = function (e) {
  905. var draggingTarget = e.target;
  906. while (draggingTarget && !draggingTarget.draggable) {
  907. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  908. }
  909. if (draggingTarget) {
  910. this._draggingTarget = draggingTarget;
  911. draggingTarget.dragging = true;
  912. this._x = e.offsetX;
  913. this._y = e.offsetY;
  914. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  915. }
  916. };
  917. Draggable.prototype._drag = function (e) {
  918. var draggingTarget = this._draggingTarget;
  919. if (draggingTarget) {
  920. var x = e.offsetX;
  921. var y = e.offsetY;
  922. var dx = x - this._x;
  923. var dy = y - this._y;
  924. this._x = x;
  925. this._y = y;
  926. draggingTarget.drift(dx, dy, e);
  927. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  928. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  929. var lastDropTarget = this._dropTarget;
  930. this._dropTarget = dropTarget;
  931. if (draggingTarget !== dropTarget) {
  932. if (lastDropTarget && dropTarget !== lastDropTarget) {
  933. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  934. }
  935. if (dropTarget && dropTarget !== lastDropTarget) {
  936. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  937. }
  938. }
  939. }
  940. };
  941. Draggable.prototype._dragEnd = function (e) {
  942. var draggingTarget = this._draggingTarget;
  943. if (draggingTarget) {
  944. draggingTarget.dragging = false;
  945. }
  946. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  947. if (this._dropTarget) {
  948. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  949. }
  950. this._draggingTarget = null;
  951. this._dropTarget = null;
  952. };
  953. return Draggable;
  954. }());
  955. var Eventful = (function () {
  956. function Eventful(eventProcessors) {
  957. if (eventProcessors) {
  958. this._$eventProcessor = eventProcessors;
  959. }
  960. }
  961. Eventful.prototype.on = function (event, query, handler, context) {
  962. if (!this._$handlers) {
  963. this._$handlers = {};
  964. }
  965. var _h = this._$handlers;
  966. if (typeof query === 'function') {
  967. context = handler;
  968. handler = query;
  969. query = null;
  970. }
  971. if (!handler || !event) {
  972. return this;
  973. }
  974. var eventProcessor = this._$eventProcessor;
  975. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  976. query = eventProcessor.normalizeQuery(query);
  977. }
  978. if (!_h[event]) {
  979. _h[event] = [];
  980. }
  981. for (var i = 0; i < _h[event].length; i++) {
  982. if (_h[event][i].h === handler) {
  983. return this;
  984. }
  985. }
  986. var wrap = {
  987. h: handler,
  988. query: query,
  989. ctx: (context || this),
  990. callAtLast: handler.zrEventfulCallAtLast
  991. };
  992. var lastIndex = _h[event].length - 1;
  993. var lastWrap = _h[event][lastIndex];
  994. (lastWrap && lastWrap.callAtLast)
  995. ? _h[event].splice(lastIndex, 0, wrap)
  996. : _h[event].push(wrap);
  997. return this;
  998. };
  999. Eventful.prototype.isSilent = function (eventName) {
  1000. var _h = this._$handlers;
  1001. return !_h || !_h[eventName] || !_h[eventName].length;
  1002. };
  1003. Eventful.prototype.off = function (eventType, handler) {
  1004. var _h = this._$handlers;
  1005. if (!_h) {
  1006. return this;
  1007. }
  1008. if (!eventType) {
  1009. this._$handlers = {};
  1010. return this;
  1011. }
  1012. if (handler) {
  1013. if (_h[eventType]) {
  1014. var newList = [];
  1015. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1016. if (_h[eventType][i].h !== handler) {
  1017. newList.push(_h[eventType][i]);
  1018. }
  1019. }
  1020. _h[eventType] = newList;
  1021. }
  1022. if (_h[eventType] && _h[eventType].length === 0) {
  1023. delete _h[eventType];
  1024. }
  1025. }
  1026. else {
  1027. delete _h[eventType];
  1028. }
  1029. return this;
  1030. };
  1031. Eventful.prototype.trigger = function (eventType) {
  1032. var args = [];
  1033. for (var _i = 1; _i < arguments.length; _i++) {
  1034. args[_i - 1] = arguments[_i];
  1035. }
  1036. if (!this._$handlers) {
  1037. return this;
  1038. }
  1039. var _h = this._$handlers[eventType];
  1040. var eventProcessor = this._$eventProcessor;
  1041. if (_h) {
  1042. var argLen = args.length;
  1043. var len = _h.length;
  1044. for (var i = 0; i < len; i++) {
  1045. var hItem = _h[i];
  1046. if (eventProcessor
  1047. && eventProcessor.filter
  1048. && hItem.query != null
  1049. && !eventProcessor.filter(eventType, hItem.query)) {
  1050. continue;
  1051. }
  1052. switch (argLen) {
  1053. case 0:
  1054. hItem.h.call(hItem.ctx);
  1055. break;
  1056. case 1:
  1057. hItem.h.call(hItem.ctx, args[0]);
  1058. break;
  1059. case 2:
  1060. hItem.h.call(hItem.ctx, args[0], args[1]);
  1061. break;
  1062. default:
  1063. hItem.h.apply(hItem.ctx, args);
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. eventProcessor && eventProcessor.afterTrigger
  1069. && eventProcessor.afterTrigger(eventType);
  1070. return this;
  1071. };
  1072. Eventful.prototype.triggerWithContext = function (type) {
  1073. var args = [];
  1074. for (var _i = 1; _i < arguments.length; _i++) {
  1075. args[_i - 1] = arguments[_i];
  1076. }
  1077. if (!this._$handlers) {
  1078. return this;
  1079. }
  1080. var _h = this._$handlers[type];
  1081. var eventProcessor = this._$eventProcessor;
  1082. if (_h) {
  1083. var argLen = args.length;
  1084. var ctx = args[argLen - 1];
  1085. var len = _h.length;
  1086. for (var i = 0; i < len; i++) {
  1087. var hItem = _h[i];
  1088. if (eventProcessor
  1089. && eventProcessor.filter
  1090. && hItem.query != null
  1091. && !eventProcessor.filter(type, hItem.query)) {
  1092. continue;
  1093. }
  1094. switch (argLen) {
  1095. case 0:
  1096. hItem.h.call(ctx);
  1097. break;
  1098. case 1:
  1099. hItem.h.call(ctx, args[0]);
  1100. break;
  1101. case 2:
  1102. hItem.h.call(ctx, args[0], args[1]);
  1103. break;
  1104. default:
  1105. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. eventProcessor && eventProcessor.afterTrigger
  1111. && eventProcessor.afterTrigger(type);
  1112. return this;
  1113. };
  1114. return Eventful;
  1115. }());
  1116. var LN2 = Math.log(2);
  1117. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1118. var cacheKey = rowMask + '-' + colMask;
  1119. var fullRank = rows.length;
  1120. if (detCache.hasOwnProperty(cacheKey)) {
  1121. return detCache[cacheKey];
  1122. }
  1123. if (rank === 1) {
  1124. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1125. return rows[rowStart][colStart];
  1126. }
  1127. var subRowMask = rowMask | (1 << rowStart);
  1128. var subRowStart = rowStart + 1;
  1129. while (rowMask & (1 << subRowStart)) {
  1130. subRowStart++;
  1131. }
  1132. var sum = 0;
  1133. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1134. var colTag = 1 << j;
  1135. if (!(colTag & colMask)) {
  1136. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1137. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1138. colLocalIdx++;
  1139. }
  1140. }
  1141. detCache[cacheKey] = sum;
  1142. return sum;
  1143. }
  1144. function buildTransformer(src, dest) {
  1145. var mA = [
  1146. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1147. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1148. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1149. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1150. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1151. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1152. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1153. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1154. ];
  1155. var detCache = {};
  1156. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1157. if (det === 0) {
  1158. return;
  1159. }
  1160. var vh = [];
  1161. for (var i = 0; i < 8; i++) {
  1162. for (var j = 0; j < 8; j++) {
  1163. vh[j] == null && (vh[j] = 0);
  1164. vh[j] += ((i + j) % 2 ? -1 : 1)
  1165. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1166. / det * dest[i];
  1167. }
  1168. }
  1169. return function (out, srcPointX, srcPointY) {
  1170. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1171. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1172. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1173. };
  1174. }
  1175. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1176. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1177. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1178. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1179. var markers = prepareCoordMarkers(el, saved);
  1180. var transformer = preparePointerTransformer(markers, saved, inverse);
  1181. if (transformer) {
  1182. transformer(out, inX, inY);
  1183. return true;
  1184. }
  1185. }
  1186. return false;
  1187. }
  1188. function prepareCoordMarkers(el, saved) {
  1189. var markers = saved.markers;
  1190. if (markers) {
  1191. return markers;
  1192. }
  1193. markers = saved.markers = [];
  1194. var propLR = ['left', 'right'];
  1195. var propTB = ['top', 'bottom'];
  1196. for (var i = 0; i < 4; i++) {
  1197. var marker = document.createElement('div');
  1198. var stl = marker.style;
  1199. var idxLR = i % 2;
  1200. var idxTB = (i >> 1) % 2;
  1201. stl.cssText = [
  1202. 'position: absolute',
  1203. 'visibility: hidden',
  1204. 'padding: 0',
  1205. 'margin: 0',
  1206. 'border-width: 0',
  1207. 'user-select: none',
  1208. 'width:0',
  1209. 'height:0',
  1210. propLR[idxLR] + ':0',
  1211. propTB[idxTB] + ':0',
  1212. propLR[1 - idxLR] + ':auto',
  1213. propTB[1 - idxTB] + ':auto',
  1214. ''
  1215. ].join('!important;');
  1216. el.appendChild(marker);
  1217. markers.push(marker);
  1218. }
  1219. return markers;
  1220. }
  1221. function preparePointerTransformer(markers, saved, inverse) {
  1222. var transformerName = inverse ? 'invTrans' : 'trans';
  1223. var transformer = saved[transformerName];
  1224. var oldSrcCoords = saved.srcCoords;
  1225. var srcCoords = [];
  1226. var destCoords = [];
  1227. var oldCoordTheSame = true;
  1228. for (var i = 0; i < 4; i++) {
  1229. var rect = markers[i].getBoundingClientRect();
  1230. var ii = 2 * i;
  1231. var x = rect.left;
  1232. var y = rect.top;
  1233. srcCoords.push(x, y);
  1234. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1235. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1236. }
  1237. return (oldCoordTheSame && transformer)
  1238. ? transformer
  1239. : (saved.srcCoords = srcCoords,
  1240. saved[transformerName] = inverse
  1241. ? buildTransformer(destCoords, srcCoords)
  1242. : buildTransformer(srcCoords, destCoords));
  1243. }
  1244. function isCanvasEl(el) {
  1245. return el.nodeName.toUpperCase() === 'CANVAS';
  1246. }
  1247. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1248. var _calcOut = [];
  1249. var firefoxNotSupportOffsetXY = env.browser.firefox
  1250. && +env.browser.version.split('.')[0] < 39;
  1251. function clientToLocal(el, e, out, calculate) {
  1252. out = out || {};
  1253. if (calculate) {
  1254. calculateZrXY(el, e, out);
  1255. }
  1256. else if (firefoxNotSupportOffsetXY
  1257. && e.layerX != null
  1258. && e.layerX !== e.offsetX) {
  1259. out.zrX = e.layerX;
  1260. out.zrY = e.layerY;
  1261. }
  1262. else if (e.offsetX != null) {
  1263. out.zrX = e.offsetX;
  1264. out.zrY = e.offsetY;
  1265. }
  1266. else {
  1267. calculateZrXY(el, e, out);
  1268. }
  1269. return out;
  1270. }
  1271. function calculateZrXY(el, e, out) {
  1272. if (env.domSupported && el.getBoundingClientRect) {
  1273. var ex = e.clientX;
  1274. var ey = e.clientY;
  1275. if (isCanvasEl(el)) {
  1276. var box = el.getBoundingClientRect();
  1277. out.zrX = ex - box.left;
  1278. out.zrY = ey - box.top;
  1279. return;
  1280. }
  1281. else {
  1282. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1283. out.zrX = _calcOut[0];
  1284. out.zrY = _calcOut[1];
  1285. return;
  1286. }
  1287. }
  1288. }
  1289. out.zrX = out.zrY = 0;
  1290. }
  1291. function getNativeEvent(e) {
  1292. return e
  1293. || window.event;
  1294. }
  1295. function normalizeEvent(el, e, calculate) {
  1296. e = getNativeEvent(e);
  1297. if (e.zrX != null) {
  1298. return e;
  1299. }
  1300. var eventType = e.type;
  1301. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1302. if (!isTouch) {
  1303. clientToLocal(el, e, e, calculate);
  1304. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1305. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1306. }
  1307. else {
  1308. var touch = eventType !== 'touchend'
  1309. ? e.targetTouches[0]
  1310. : e.changedTouches[0];
  1311. touch && clientToLocal(el, touch, e, calculate);
  1312. }
  1313. var button = e.button;
  1314. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1315. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1316. }
  1317. return e;
  1318. }
  1319. function getWheelDeltaMayPolyfill(e) {
  1320. var rawWheelDelta = e.wheelDelta;
  1321. if (rawWheelDelta) {
  1322. return rawWheelDelta;
  1323. }
  1324. var deltaX = e.deltaX;
  1325. var deltaY = e.deltaY;
  1326. if (deltaX == null || deltaY == null) {
  1327. return rawWheelDelta;
  1328. }
  1329. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1330. var sign = deltaY > 0 ? -1
  1331. : deltaY < 0 ? 1
  1332. : deltaX > 0 ? -1
  1333. : 1;
  1334. return 3 * delta * sign;
  1335. }
  1336. function addEventListener(el, name, handler, opt) {
  1337. el.addEventListener(name, handler, opt);
  1338. }
  1339. function removeEventListener(el, name, handler, opt) {
  1340. el.removeEventListener(name, handler, opt);
  1341. }
  1342. var stop = function (e) {
  1343. e.preventDefault();
  1344. e.stopPropagation();
  1345. e.cancelBubble = true;
  1346. };
  1347. var GestureMgr = (function () {
  1348. function GestureMgr() {
  1349. this._track = [];
  1350. }
  1351. GestureMgr.prototype.recognize = function (event, target, root) {
  1352. this._doTrack(event, target, root);
  1353. return this._recognize(event);
  1354. };
  1355. GestureMgr.prototype.clear = function () {
  1356. this._track.length = 0;
  1357. return this;
  1358. };
  1359. GestureMgr.prototype._doTrack = function (event, target, root) {
  1360. var touches = event.touches;
  1361. if (!touches) {
  1362. return;
  1363. }
  1364. var trackItem = {
  1365. points: [],
  1366. touches: [],
  1367. target: target,
  1368. event: event
  1369. };
  1370. for (var i = 0, len = touches.length; i < len; i++) {
  1371. var touch = touches[i];
  1372. var pos = clientToLocal(root, touch, {});
  1373. trackItem.points.push([pos.zrX, pos.zrY]);
  1374. trackItem.touches.push(touch);
  1375. }
  1376. this._track.push(trackItem);
  1377. };
  1378. GestureMgr.prototype._recognize = function (event) {
  1379. for (var eventName in recognizers) {
  1380. if (recognizers.hasOwnProperty(eventName)) {
  1381. var gestureInfo = recognizers[eventName](this._track, event);
  1382. if (gestureInfo) {
  1383. return gestureInfo;
  1384. }
  1385. }
  1386. }
  1387. };
  1388. return GestureMgr;
  1389. }());
  1390. function dist$1(pointPair) {
  1391. var dx = pointPair[1][0] - pointPair[0][0];
  1392. var dy = pointPair[1][1] - pointPair[0][1];
  1393. return Math.sqrt(dx * dx + dy * dy);
  1394. }
  1395. function center(pointPair) {
  1396. return [
  1397. (pointPair[0][0] + pointPair[1][0]) / 2,
  1398. (pointPair[0][1] + pointPair[1][1]) / 2
  1399. ];
  1400. }
  1401. var recognizers = {
  1402. pinch: function (tracks, event) {
  1403. var trackLen = tracks.length;
  1404. if (!trackLen) {
  1405. return;
  1406. }
  1407. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1408. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1409. if (pinchPre
  1410. && pinchPre.length > 1
  1411. && pinchEnd
  1412. && pinchEnd.length > 1) {
  1413. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1414. !isFinite(pinchScale) && (pinchScale = 1);
  1415. event.pinchScale = pinchScale;
  1416. var pinchCenter = center(pinchEnd);
  1417. event.pinchX = pinchCenter[0];
  1418. event.pinchY = pinchCenter[1];
  1419. return {
  1420. type: 'pinch',
  1421. target: tracks[0].target,
  1422. event: event
  1423. };
  1424. }
  1425. }
  1426. };
  1427. var SILENT = 'silent';
  1428. function makeEventPacket(eveType, targetInfo, event) {
  1429. return {
  1430. type: eveType,
  1431. event: event,
  1432. target: targetInfo.target,
  1433. topTarget: targetInfo.topTarget,
  1434. cancelBubble: false,
  1435. offsetX: event.zrX,
  1436. offsetY: event.zrY,
  1437. gestureEvent: event.gestureEvent,
  1438. pinchX: event.pinchX,
  1439. pinchY: event.pinchY,
  1440. pinchScale: event.pinchScale,
  1441. wheelDelta: event.zrDelta,
  1442. zrByTouch: event.zrByTouch,
  1443. which: event.which,
  1444. stop: stopEvent
  1445. };
  1446. }
  1447. function stopEvent() {
  1448. stop(this.event);
  1449. }
  1450. var EmptyProxy = (function (_super) {
  1451. __extends(EmptyProxy, _super);
  1452. function EmptyProxy() {
  1453. var _this = _super !== null && _super.apply(this, arguments) || this;
  1454. _this.handler = null;
  1455. return _this;
  1456. }
  1457. EmptyProxy.prototype.dispose = function () { };
  1458. EmptyProxy.prototype.setCursor = function () { };
  1459. return EmptyProxy;
  1460. }(Eventful));
  1461. var HoveredResult = (function () {
  1462. function HoveredResult(x, y) {
  1463. this.x = x;
  1464. this.y = y;
  1465. }
  1466. return HoveredResult;
  1467. }());
  1468. var handlerNames = [
  1469. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1470. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1471. ];
  1472. var Handler = (function (_super) {
  1473. __extends(Handler, _super);
  1474. function Handler(storage, painter, proxy, painterRoot) {
  1475. var _this = _super.call(this) || this;
  1476. _this._hovered = new HoveredResult(0, 0);
  1477. _this.storage = storage;
  1478. _this.painter = painter;
  1479. _this.painterRoot = painterRoot;
  1480. proxy = proxy || new EmptyProxy();
  1481. _this.proxy = null;
  1482. _this.setHandlerProxy(proxy);
  1483. _this._draggingMgr = new Draggable(_this);
  1484. return _this;
  1485. }
  1486. Handler.prototype.setHandlerProxy = function (proxy) {
  1487. if (this.proxy) {
  1488. this.proxy.dispose();
  1489. }
  1490. if (proxy) {
  1491. each(handlerNames, function (name) {
  1492. proxy.on && proxy.on(name, this[name], this);
  1493. }, this);
  1494. proxy.handler = this;
  1495. }
  1496. this.proxy = proxy;
  1497. };
  1498. Handler.prototype.mousemove = function (event) {
  1499. var x = event.zrX;
  1500. var y = event.zrY;
  1501. var isOutside = isOutsideBoundary(this, x, y);
  1502. var lastHovered = this._hovered;
  1503. var lastHoveredTarget = lastHovered.target;
  1504. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1505. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1506. lastHoveredTarget = lastHovered.target;
  1507. }
  1508. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  1509. var hoveredTarget = hovered.target;
  1510. var proxy = this.proxy;
  1511. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1512. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1513. this.dispatchToElement(lastHovered, 'mouseout', event);
  1514. }
  1515. this.dispatchToElement(hovered, 'mousemove', event);
  1516. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1517. this.dispatchToElement(hovered, 'mouseover', event);
  1518. }
  1519. };
  1520. Handler.prototype.mouseout = function (event) {
  1521. var eventControl = event.zrEventControl;
  1522. if (eventControl !== 'only_globalout') {
  1523. this.dispatchToElement(this._hovered, 'mouseout', event);
  1524. }
  1525. if (eventControl !== 'no_globalout') {
  1526. this.trigger('globalout', { type: 'globalout', event: event });
  1527. }
  1528. };
  1529. Handler.prototype.resize = function () {
  1530. this._hovered = new HoveredResult(0, 0);
  1531. };
  1532. Handler.prototype.dispatch = function (eventName, eventArgs) {
  1533. var handler = this[eventName];
  1534. handler && handler.call(this, eventArgs);
  1535. };
  1536. Handler.prototype.dispose = function () {
  1537. this.proxy.dispose();
  1538. this.storage = null;
  1539. this.proxy = null;
  1540. this.painter = null;
  1541. };
  1542. Handler.prototype.setCursorStyle = function (cursorStyle) {
  1543. var proxy = this.proxy;
  1544. proxy.setCursor && proxy.setCursor(cursorStyle);
  1545. };
  1546. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  1547. targetInfo = targetInfo || {};
  1548. var el = targetInfo.target;
  1549. if (el && el.silent) {
  1550. return;
  1551. }
  1552. var eventKey = ('on' + eventName);
  1553. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1554. while (el) {
  1555. el[eventKey]
  1556. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  1557. el.trigger(eventName, eventPacket);
  1558. el = el.__hostTarget ? el.__hostTarget : el.parent;
  1559. if (eventPacket.cancelBubble) {
  1560. break;
  1561. }
  1562. }
  1563. if (!eventPacket.cancelBubble) {
  1564. this.trigger(eventName, eventPacket);
  1565. if (this.painter && this.painter.eachOtherLayer) {
  1566. this.painter.eachOtherLayer(function (layer) {
  1567. if (typeof (layer[eventKey]) === 'function') {
  1568. layer[eventKey].call(layer, eventPacket);
  1569. }
  1570. if (layer.trigger) {
  1571. layer.trigger(eventName, eventPacket);
  1572. }
  1573. });
  1574. }
  1575. }
  1576. };
  1577. Handler.prototype.findHover = function (x, y, exclude) {
  1578. var list = this.storage.getDisplayList();
  1579. var out = new HoveredResult(x, y);
  1580. for (var i = list.length - 1; i >= 0; i--) {
  1581. var hoverCheckResult = void 0;
  1582. if (list[i] !== exclude
  1583. && !list[i].ignore
  1584. && (hoverCheckResult = isHover(list[i], x, y))) {
  1585. !out.topTarget && (out.topTarget = list[i]);
  1586. if (hoverCheckResult !== SILENT) {
  1587. out.target = list[i];
  1588. break;
  1589. }
  1590. }
  1591. }
  1592. return out;
  1593. };
  1594. Handler.prototype.processGesture = function (event, stage) {
  1595. if (!this._gestureMgr) {
  1596. this._gestureMgr = new GestureMgr();
  1597. }
  1598. var gestureMgr = this._gestureMgr;
  1599. stage === 'start' && gestureMgr.clear();
  1600. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  1601. stage === 'end' && gestureMgr.clear();
  1602. if (gestureInfo) {
  1603. var type = gestureInfo.type;
  1604. event.gestureEvent = type;
  1605. var res = new HoveredResult();
  1606. res.target = gestureInfo.target;
  1607. this.dispatchToElement(res, type, gestureInfo.event);
  1608. }
  1609. };
  1610. return Handler;
  1611. }(Eventful));
  1612. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1613. Handler.prototype[name] = function (event) {
  1614. var x = event.zrX;
  1615. var y = event.zrY;
  1616. var isOutside = isOutsideBoundary(this, x, y);
  1617. var hovered;
  1618. var hoveredTarget;
  1619. if (name !== 'mouseup' || !isOutside) {
  1620. hovered = this.findHover(x, y);
  1621. hoveredTarget = hovered.target;
  1622. }
  1623. if (name === 'mousedown') {
  1624. this._downEl = hoveredTarget;
  1625. this._downPoint = [event.zrX, event.zrY];
  1626. this._upEl = hoveredTarget;
  1627. }
  1628. else if (name === 'mouseup') {
  1629. this._upEl = hoveredTarget;
  1630. }
  1631. else if (name === 'click') {
  1632. if (this._downEl !== this._upEl
  1633. || !this._downPoint
  1634. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  1635. return;
  1636. }
  1637. this._downPoint = null;
  1638. }
  1639. this.dispatchToElement(hovered, name, event);
  1640. };
  1641. });
  1642. function isHover(displayable, x, y) {
  1643. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1644. var el = displayable;
  1645. var isSilent = void 0;
  1646. var ignoreClip = false;
  1647. while (el) {
  1648. if (el.ignoreClip) {
  1649. ignoreClip = true;
  1650. }
  1651. if (!ignoreClip) {
  1652. var clipPath = el.getClipPath();
  1653. if (clipPath && !clipPath.contain(x, y)) {
  1654. return false;
  1655. }
  1656. if (el.silent) {
  1657. isSilent = true;
  1658. }
  1659. }
  1660. var hostEl = el.__hostTarget;
  1661. el = hostEl ? hostEl : el.parent;
  1662. }
  1663. return isSilent ? SILENT : true;
  1664. }
  1665. return false;
  1666. }
  1667. function isOutsideBoundary(handlerInstance, x, y) {
  1668. var painter = handlerInstance.painter;
  1669. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  1670. }
  1671. var DEFAULT_MIN_MERGE = 32;
  1672. var DEFAULT_MIN_GALLOPING = 7;
  1673. function minRunLength(n) {
  1674. var r = 0;
  1675. while (n >= DEFAULT_MIN_MERGE) {
  1676. r |= n & 1;
  1677. n >>= 1;
  1678. }
  1679. return n + r;
  1680. }
  1681. function makeAscendingRun(array, lo, hi, compare) {
  1682. var runHi = lo + 1;
  1683. if (runHi === hi) {
  1684. return 1;
  1685. }
  1686. if (compare(array[runHi++], array[lo]) < 0) {
  1687. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  1688. runHi++;
  1689. }
  1690. reverseRun(array, lo, runHi);
  1691. }
  1692. else {
  1693. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  1694. runHi++;
  1695. }
  1696. }
  1697. return runHi - lo;
  1698. }
  1699. function reverseRun(array, lo, hi) {
  1700. hi--;
  1701. while (lo < hi) {
  1702. var t = array[lo];
  1703. array[lo++] = array[hi];
  1704. array[hi--] = t;
  1705. }
  1706. }
  1707. function binaryInsertionSort(array, lo, hi, start, compare) {
  1708. if (start === lo) {
  1709. start++;
  1710. }
  1711. for (; start < hi; start++) {
  1712. var pivot = array[start];
  1713. var left = lo;
  1714. var right = start;
  1715. var mid;
  1716. while (left < right) {
  1717. mid = left + right >>> 1;
  1718. if (compare(pivot, array[mid]) < 0) {
  1719. right = mid;
  1720. }
  1721. else {
  1722. left = mid + 1;
  1723. }
  1724. }
  1725. var n = start - left;
  1726. switch (n) {
  1727. case 3:
  1728. array[left + 3] = array[left + 2];
  1729. case 2:
  1730. array[left + 2] = array[left + 1];
  1731. case 1:
  1732. array[left + 1] = array[left];
  1733. break;
  1734. default:
  1735. while (n > 0) {
  1736. array[left + n] = array[left + n - 1];
  1737. n--;
  1738. }
  1739. }
  1740. array[left] = pivot;
  1741. }
  1742. }
  1743. function gallopLeft(value, array, start, length, hint, compare) {
  1744. var lastOffset = 0;
  1745. var maxOffset = 0;
  1746. var offset = 1;
  1747. if (compare(value, array[start + hint]) > 0) {
  1748. maxOffset = length - hint;
  1749. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  1750. lastOffset = offset;
  1751. offset = (offset << 1) + 1;
  1752. if (offset <= 0) {
  1753. offset = maxOffset;
  1754. }
  1755. }
  1756. if (offset > maxOffset) {
  1757. offset = maxOffset;
  1758. }
  1759. lastOffset += hint;
  1760. offset += hint;
  1761. }
  1762. else {
  1763. maxOffset = hint + 1;
  1764. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  1765. lastOffset = offset;
  1766. offset = (offset << 1) + 1;
  1767. if (offset <= 0) {
  1768. offset = maxOffset;
  1769. }
  1770. }
  1771. if (offset > maxOffset) {
  1772. offset = maxOffset;
  1773. }
  1774. var tmp = lastOffset;
  1775. lastOffset = hint - offset;
  1776. offset = hint - tmp;
  1777. }
  1778. lastOffset++;
  1779. while (lastOffset < offset) {
  1780. var m = lastOffset + (offset - lastOffset >>> 1);
  1781. if (compare(value, array[start + m]) > 0) {
  1782. lastOffset = m + 1;
  1783. }
  1784. else {
  1785. offset = m;
  1786. }
  1787. }
  1788. return offset;
  1789. }
  1790. function gallopRight(value, array, start, length, hint, compare) {
  1791. var lastOffset = 0;
  1792. var maxOffset = 0;
  1793. var offset = 1;
  1794. if (compare(value, array[start + hint]) < 0) {
  1795. maxOffset = hint + 1;
  1796. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  1797. lastOffset = offset;
  1798. offset = (offset << 1) + 1;
  1799. if (offset <= 0) {
  1800. offset = maxOffset;
  1801. }
  1802. }
  1803. if (offset > maxOffset) {
  1804. offset = maxOffset;
  1805. }
  1806. var tmp = lastOffset;
  1807. lastOffset = hint - offset;
  1808. offset = hint - tmp;
  1809. }
  1810. else {
  1811. maxOffset = length - hint;
  1812. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  1813. lastOffset = offset;
  1814. offset = (offset << 1) + 1;
  1815. if (offset <= 0) {
  1816. offset = maxOffset;
  1817. }
  1818. }
  1819. if (offset > maxOffset) {
  1820. offset = maxOffset;
  1821. }
  1822. lastOffset += hint;
  1823. offset += hint;
  1824. }
  1825. lastOffset++;
  1826. while (lastOffset < offset) {
  1827. var m = lastOffset + (offset - lastOffset >>> 1);
  1828. if (compare(value, array[start + m]) < 0) {
  1829. offset = m;
  1830. }
  1831. else {
  1832. lastOffset = m + 1;
  1833. }
  1834. }
  1835. return offset;
  1836. }
  1837. function TimSort(array, compare) {
  1838. var minGallop = DEFAULT_MIN_GALLOPING;
  1839. var length = 0;
  1840. var runStart;
  1841. var runLength;
  1842. var stackSize = 0;
  1843. length = array.length;
  1844. var tmp = [];
  1845. runStart = [];
  1846. runLength = [];
  1847. function pushRun(_runStart, _runLength) {
  1848. runStart[stackSize] = _runStart;
  1849. runLength[stackSize] = _runLength;
  1850. stackSize += 1;
  1851. }
  1852. function mergeRuns() {
  1853. while (stackSize > 1) {
  1854. var n = stackSize - 2;
  1855. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  1856. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  1857. if (runLength[n - 1] < runLength[n + 1]) {
  1858. n--;
  1859. }
  1860. }
  1861. else if (runLength[n] > runLength[n + 1]) {
  1862. break;
  1863. }
  1864. mergeAt(n);
  1865. }
  1866. }
  1867. function forceMergeRuns() {
  1868. while (stackSize > 1) {
  1869. var n = stackSize - 2;
  1870. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  1871. n--;
  1872. }
  1873. mergeAt(n);
  1874. }
  1875. }
  1876. function mergeAt(i) {
  1877. var start1 = runStart[i];
  1878. var length1 = runLength[i];
  1879. var start2 = runStart[i + 1];
  1880. var length2 = runLength[i + 1];
  1881. runLength[i] = length1 + length2;
  1882. if (i === stackSize - 3) {
  1883. runStart[i + 1] = runStart[i + 2];
  1884. runLength[i + 1] = runLength[i + 2];
  1885. }
  1886. stackSize--;
  1887. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  1888. start1 += k;
  1889. length1 -= k;
  1890. if (length1 === 0) {
  1891. return;
  1892. }
  1893. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  1894. if (length2 === 0) {
  1895. return;
  1896. }
  1897. if (length1 <= length2) {
  1898. mergeLow(start1, length1, start2, length2);
  1899. }
  1900. else {
  1901. mergeHigh(start1, length1, start2, length2);
  1902. }
  1903. }
  1904. function mergeLow(start1, length1, start2, length2) {
  1905. var i = 0;
  1906. for (i = 0; i < length1; i++) {
  1907. tmp[i] = array[start1 + i];
  1908. }
  1909. var cursor1 = 0;
  1910. var cursor2 = start2;
  1911. var dest = start1;
  1912. array[dest++] = array[cursor2++];
  1913. if (--length2 === 0) {
  1914. for (i = 0; i < length1; i++) {
  1915. array[dest + i] = tmp[cursor1 + i];
  1916. }
  1917. return;
  1918. }
  1919. if (length1 === 1) {
  1920. for (i = 0; i < length2; i++) {
  1921. array[dest + i] = array[cursor2 + i];
  1922. }
  1923. array[dest + length2] = tmp[cursor1];
  1924. return;
  1925. }
  1926. var _minGallop = minGallop;
  1927. var count1;
  1928. var count2;
  1929. var exit;
  1930. while (1) {
  1931. count1 = 0;
  1932. count2 = 0;
  1933. exit = false;
  1934. do {
  1935. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  1936. array[dest++] = array[cursor2++];
  1937. count2++;
  1938. count1 = 0;
  1939. if (--length2 === 0) {
  1940. exit = true;
  1941. break;
  1942. }
  1943. }
  1944. else {
  1945. array[dest++] = tmp[cursor1++];
  1946. count1++;
  1947. count2 = 0;
  1948. if (--length1 === 1) {
  1949. exit = true;
  1950. break;
  1951. }
  1952. }
  1953. } while ((count1 | count2) < _minGallop);
  1954. if (exit) {
  1955. break;
  1956. }
  1957. do {
  1958. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  1959. if (count1 !== 0) {
  1960. for (i = 0; i < count1; i++) {
  1961. array[dest + i] = tmp[cursor1 + i];
  1962. }
  1963. dest += count1;
  1964. cursor1 += count1;
  1965. length1 -= count1;
  1966. if (length1 <= 1) {
  1967. exit = true;
  1968. break;
  1969. }
  1970. }
  1971. array[dest++] = array[cursor2++];
  1972. if (--length2 === 0) {
  1973. exit = true;
  1974. break;
  1975. }
  1976. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  1977. if (count2 !== 0) {
  1978. for (i = 0; i < count2; i++) {
  1979. array[dest + i] = array[cursor2 + i];
  1980. }
  1981. dest += count2;
  1982. cursor2 += count2;
  1983. length2 -= count2;
  1984. if (length2 === 0) {
  1985. exit = true;
  1986. break;
  1987. }
  1988. }
  1989. array[dest++] = tmp[cursor1++];
  1990. if (--length1 === 1) {
  1991. exit = true;
  1992. break;
  1993. }
  1994. _minGallop--;
  1995. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  1996. if (exit) {
  1997. break;
  1998. }
  1999. if (_minGallop < 0) {
  2000. _minGallop = 0;
  2001. }
  2002. _minGallop += 2;
  2003. }
  2004. minGallop = _minGallop;
  2005. minGallop < 1 && (minGallop = 1);
  2006. if (length1 === 1) {
  2007. for (i = 0; i < length2; i++) {
  2008. array[dest + i] = array[cursor2 + i];
  2009. }
  2010. array[dest + length2] = tmp[cursor1];
  2011. }
  2012. else if (length1 === 0) {
  2013. throw new Error();
  2014. }
  2015. else {
  2016. for (i = 0; i < length1; i++) {
  2017. array[dest + i] = tmp[cursor1 + i];
  2018. }
  2019. }
  2020. }
  2021. function mergeHigh(start1, length1, start2, length2) {
  2022. var i = 0;
  2023. for (i = 0; i < length2; i++) {
  2024. tmp[i] = array[start2 + i];
  2025. }
  2026. var cursor1 = start1 + length1 - 1;
  2027. var cursor2 = length2 - 1;
  2028. var dest = start2 + length2 - 1;
  2029. var customCursor = 0;
  2030. var customDest = 0;
  2031. array[dest--] = array[cursor1--];
  2032. if (--length1 === 0) {
  2033. customCursor = dest - (length2 - 1);
  2034. for (i = 0; i < length2; i++) {
  2035. array[customCursor + i] = tmp[i];
  2036. }
  2037. return;
  2038. }
  2039. if (length2 === 1) {
  2040. dest -= length1;
  2041. cursor1 -= length1;
  2042. customDest = dest + 1;
  2043. customCursor = cursor1 + 1;
  2044. for (i = length1 - 1; i >= 0; i--) {
  2045. array[customDest + i] = array[customCursor + i];
  2046. }
  2047. array[dest] = tmp[cursor2];
  2048. return;
  2049. }
  2050. var _minGallop = minGallop;
  2051. while (true) {
  2052. var count1 = 0;
  2053. var count2 = 0;
  2054. var exit = false;
  2055. do {
  2056. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2057. array[dest--] = array[cursor1--];
  2058. count1++;
  2059. count2 = 0;
  2060. if (--length1 === 0) {
  2061. exit = true;
  2062. break;
  2063. }
  2064. }
  2065. else {
  2066. array[dest--] = tmp[cursor2--];
  2067. count2++;
  2068. count1 = 0;
  2069. if (--length2 === 1) {
  2070. exit = true;
  2071. break;
  2072. }
  2073. }
  2074. } while ((count1 | count2) < _minGallop);
  2075. if (exit) {
  2076. break;
  2077. }
  2078. do {
  2079. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2080. if (count1 !== 0) {
  2081. dest -= count1;
  2082. cursor1 -= count1;
  2083. length1 -= count1;
  2084. customDest = dest + 1;
  2085. customCursor = cursor1 + 1;
  2086. for (i = count1 - 1; i >= 0; i--) {
  2087. array[customDest + i] = array[customCursor + i];
  2088. }
  2089. if (length1 === 0) {
  2090. exit = true;
  2091. break;
  2092. }
  2093. }
  2094. array[dest--] = tmp[cursor2--];
  2095. if (--length2 === 1) {
  2096. exit = true;
  2097. break;
  2098. }
  2099. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2100. if (count2 !== 0) {
  2101. dest -= count2;
  2102. cursor2 -= count2;
  2103. length2 -= count2;
  2104. customDest = dest + 1;
  2105. customCursor = cursor2 + 1;
  2106. for (i = 0; i < count2; i++) {
  2107. array[customDest + i] = tmp[customCursor + i];
  2108. }
  2109. if (length2 <= 1) {
  2110. exit = true;
  2111. break;
  2112. }
  2113. }
  2114. array[dest--] = array[cursor1--];
  2115. if (--length1 === 0) {
  2116. exit = true;
  2117. break;
  2118. }
  2119. _minGallop--;
  2120. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2121. if (exit) {
  2122. break;
  2123. }
  2124. if (_minGallop < 0) {
  2125. _minGallop = 0;
  2126. }
  2127. _minGallop += 2;
  2128. }
  2129. minGallop = _minGallop;
  2130. if (minGallop < 1) {
  2131. minGallop = 1;
  2132. }
  2133. if (length2 === 1) {
  2134. dest -= length1;
  2135. cursor1 -= length1;
  2136. customDest = dest + 1;
  2137. customCursor = cursor1 + 1;
  2138. for (i = length1 - 1; i >= 0; i--) {
  2139. array[customDest + i] = array[customCursor + i];
  2140. }
  2141. array[dest] = tmp[cursor2];
  2142. }
  2143. else if (length2 === 0) {
  2144. throw new Error();
  2145. }
  2146. else {
  2147. customCursor = dest - (length2 - 1);
  2148. for (i = 0; i < length2; i++) {
  2149. array[customCursor + i] = tmp[i];
  2150. }
  2151. }
  2152. }
  2153. return {
  2154. mergeRuns: mergeRuns,
  2155. forceMergeRuns: forceMergeRuns,
  2156. pushRun: pushRun
  2157. };
  2158. }
  2159. function sort(array, compare, lo, hi) {
  2160. if (!lo) {
  2161. lo = 0;
  2162. }
  2163. if (!hi) {
  2164. hi = array.length;
  2165. }
  2166. var remaining = hi - lo;
  2167. if (remaining < 2) {
  2168. return;
  2169. }
  2170. var runLength = 0;
  2171. if (remaining < DEFAULT_MIN_MERGE) {
  2172. runLength = makeAscendingRun(array, lo, hi, compare);
  2173. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2174. return;
  2175. }
  2176. var ts = TimSort(array, compare);
  2177. var minRun = minRunLength(remaining);
  2178. do {
  2179. runLength = makeAscendingRun(array, lo, hi, compare);
  2180. if (runLength < minRun) {
  2181. var force = remaining;
  2182. if (force > minRun) {
  2183. force = minRun;
  2184. }
  2185. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2186. runLength = force;
  2187. }
  2188. ts.pushRun(lo, runLength);
  2189. ts.mergeRuns();
  2190. remaining -= runLength;
  2191. lo += runLength;
  2192. } while (remaining !== 0);
  2193. ts.forceMergeRuns();
  2194. }
  2195. var REDRAW_BIT = 1;
  2196. var STYLE_CHANGED_BIT = 2;
  2197. var SHAPE_CHANGED_BIT = 4;
  2198. var invalidZErrorLogged = false;
  2199. function logInvalidZError() {
  2200. if (invalidZErrorLogged) {
  2201. return;
  2202. }
  2203. invalidZErrorLogged = true;
  2204. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2205. }
  2206. function shapeCompareFunc(a, b) {
  2207. if (a.zlevel === b.zlevel) {
  2208. if (a.z === b.z) {
  2209. return a.z2 - b.z2;
  2210. }
  2211. return a.z - b.z;
  2212. }
  2213. return a.zlevel - b.zlevel;
  2214. }
  2215. var Storage = (function () {
  2216. function Storage() {
  2217. this._roots = [];
  2218. this._displayList = [];
  2219. this._displayListLen = 0;
  2220. this.displayableSortFunc = shapeCompareFunc;
  2221. }
  2222. Storage.prototype.traverse = function (cb, context) {
  2223. for (var i = 0; i < this._roots.length; i++) {
  2224. this._roots[i].traverse(cb, context);
  2225. }
  2226. };
  2227. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2228. includeIgnore = includeIgnore || false;
  2229. var displayList = this._displayList;
  2230. if (update || !displayList.length) {
  2231. this.updateDisplayList(includeIgnore);
  2232. }
  2233. return displayList;
  2234. };
  2235. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2236. this._displayListLen = 0;
  2237. var roots = this._roots;
  2238. var displayList = this._displayList;
  2239. for (var i = 0, len = roots.length; i < len; i++) {
  2240. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2241. }
  2242. displayList.length = this._displayListLen;
  2243. sort(displayList, shapeCompareFunc);
  2244. };
  2245. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2246. if (el.ignore && !includeIgnore) {
  2247. return;
  2248. }
  2249. el.beforeUpdate();
  2250. el.update();
  2251. el.afterUpdate();
  2252. var userSetClipPath = el.getClipPath();
  2253. if (el.ignoreClip) {
  2254. clipPaths = null;
  2255. }
  2256. else if (userSetClipPath) {
  2257. if (clipPaths) {
  2258. clipPaths = clipPaths.slice();
  2259. }
  2260. else {
  2261. clipPaths = [];
  2262. }
  2263. var currentClipPath = userSetClipPath;
  2264. var parentClipPath = el;
  2265. while (currentClipPath) {
  2266. currentClipPath.parent = parentClipPath;
  2267. currentClipPath.updateTransform();
  2268. clipPaths.push(currentClipPath);
  2269. parentClipPath = currentClipPath;
  2270. currentClipPath = currentClipPath.getClipPath();
  2271. }
  2272. }
  2273. if (el.childrenRef) {
  2274. var children = el.childrenRef();
  2275. for (var i = 0; i < children.length; i++) {
  2276. var child = children[i];
  2277. if (el.__dirty) {
  2278. child.__dirty |= REDRAW_BIT;
  2279. }
  2280. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2281. }
  2282. el.__dirty = 0;
  2283. }
  2284. else {
  2285. var disp = el;
  2286. if (clipPaths && clipPaths.length) {
  2287. disp.__clipPaths = clipPaths;
  2288. }
  2289. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2290. disp.__clipPaths = [];
  2291. }
  2292. if (isNaN(disp.z)) {
  2293. logInvalidZError();
  2294. disp.z = 0;
  2295. }
  2296. if (isNaN(disp.z2)) {
  2297. logInvalidZError();
  2298. disp.z2 = 0;
  2299. }
  2300. if (isNaN(disp.zlevel)) {
  2301. logInvalidZError();
  2302. disp.zlevel = 0;
  2303. }
  2304. this._displayList[this._displayListLen++] = disp;
  2305. }
  2306. var decalEl = el.getDecalElement && el.getDecalElement();
  2307. if (decalEl) {
  2308. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2309. }
  2310. var textGuide = el.getTextGuideLine();
  2311. if (textGuide) {
  2312. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2313. }
  2314. var textEl = el.getTextContent();
  2315. if (textEl) {
  2316. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2317. }
  2318. };
  2319. Storage.prototype.addRoot = function (el) {
  2320. if (el.__zr && el.__zr.storage === this) {
  2321. return;
  2322. }
  2323. this._roots.push(el);
  2324. };
  2325. Storage.prototype.delRoot = function (el) {
  2326. if (el instanceof Array) {
  2327. for (var i = 0, l = el.length; i < l; i++) {
  2328. this.delRoot(el[i]);
  2329. }
  2330. return;
  2331. }
  2332. var idx = indexOf(this._roots, el);
  2333. if (idx >= 0) {
  2334. this._roots.splice(idx, 1);
  2335. }
  2336. };
  2337. Storage.prototype.delAllRoots = function () {
  2338. this._roots = [];
  2339. this._displayList = [];
  2340. this._displayListLen = 0;
  2341. return;
  2342. };
  2343. Storage.prototype.getRoots = function () {
  2344. return this._roots;
  2345. };
  2346. Storage.prototype.dispose = function () {
  2347. this._displayList = null;
  2348. this._roots = null;
  2349. };
  2350. return Storage;
  2351. }());
  2352. var requestAnimationFrame;
  2353. requestAnimationFrame = (env.hasGlobalWindow
  2354. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2355. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2356. || window.mozRequestAnimationFrame
  2357. || window.webkitRequestAnimationFrame)) || function (func) {
  2358. return setTimeout(func, 16);
  2359. };
  2360. var requestAnimationFrame$1 = requestAnimationFrame;
  2361. var easingFuncs = {
  2362. linear: function (k) {
  2363. return k;
  2364. },
  2365. quadraticIn: function (k) {
  2366. return k * k;
  2367. },
  2368. quadraticOut: function (k) {
  2369. return k * (2 - k);
  2370. },
  2371. quadraticInOut: function (k) {
  2372. if ((k *= 2) < 1) {
  2373. return 0.5 * k * k;
  2374. }
  2375. return -0.5 * (--k * (k - 2) - 1);
  2376. },
  2377. cubicIn: function (k) {
  2378. return k * k * k;
  2379. },
  2380. cubicOut: function (k) {
  2381. return --k * k * k + 1;
  2382. },
  2383. cubicInOut: function (k) {
  2384. if ((k *= 2) < 1) {
  2385. return 0.5 * k * k * k;
  2386. }
  2387. return 0.5 * ((k -= 2) * k * k + 2);
  2388. },
  2389. quarticIn: function (k) {
  2390. return k * k * k * k;
  2391. },
  2392. quarticOut: function (k) {
  2393. return 1 - (--k * k * k * k);
  2394. },
  2395. quarticInOut: function (k) {
  2396. if ((k *= 2) < 1) {
  2397. return 0.5 * k * k * k * k;
  2398. }
  2399. return -0.5 * ((k -= 2) * k * k * k - 2);
  2400. },
  2401. quinticIn: function (k) {
  2402. return k * k * k * k * k;
  2403. },
  2404. quinticOut: function (k) {
  2405. return --k * k * k * k * k + 1;
  2406. },
  2407. quinticInOut: function (k) {
  2408. if ((k *= 2) < 1) {
  2409. return 0.5 * k * k * k * k * k;
  2410. }
  2411. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2412. },
  2413. sinusoidalIn: function (k) {
  2414. return 1 - Math.cos(k * Math.PI / 2);
  2415. },
  2416. sinusoidalOut: function (k) {
  2417. return Math.sin(k * Math.PI / 2);
  2418. },
  2419. sinusoidalInOut: function (k) {
  2420. return 0.5 * (1 - Math.cos(Math.PI * k));
  2421. },
  2422. exponentialIn: function (k) {
  2423. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2424. },
  2425. exponentialOut: function (k) {
  2426. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2427. },
  2428. exponentialInOut: function (k) {
  2429. if (k === 0) {
  2430. return 0;
  2431. }
  2432. if (k === 1) {
  2433. return 1;
  2434. }
  2435. if ((k *= 2) < 1) {
  2436. return 0.5 * Math.pow(1024, k - 1);
  2437. }
  2438. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2439. },
  2440. circularIn: function (k) {
  2441. return 1 - Math.sqrt(1 - k * k);
  2442. },
  2443. circularOut: function (k) {
  2444. return Math.sqrt(1 - (--k * k));
  2445. },
  2446. circularInOut: function (k) {
  2447. if ((k *= 2) < 1) {
  2448. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2449. }
  2450. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2451. },
  2452. elasticIn: function (k) {
  2453. var s;
  2454. var a = 0.1;
  2455. var p = 0.4;
  2456. if (k === 0) {
  2457. return 0;
  2458. }
  2459. if (k === 1) {
  2460. return 1;
  2461. }
  2462. if (!a || a < 1) {
  2463. a = 1;
  2464. s = p / 4;
  2465. }
  2466. else {
  2467. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2468. }
  2469. return -(a * Math.pow(2, 10 * (k -= 1))
  2470. * Math.sin((k - s) * (2 * Math.PI) / p));
  2471. },
  2472. elasticOut: function (k) {
  2473. var s;
  2474. var a = 0.1;
  2475. var p = 0.4;
  2476. if (k === 0) {
  2477. return 0;
  2478. }
  2479. if (k === 1) {
  2480. return 1;
  2481. }
  2482. if (!a || a < 1) {
  2483. a = 1;
  2484. s = p / 4;
  2485. }
  2486. else {
  2487. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2488. }
  2489. return (a * Math.pow(2, -10 * k)
  2490. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2491. },
  2492. elasticInOut: function (k) {
  2493. var s;
  2494. var a = 0.1;
  2495. var p = 0.4;
  2496. if (k === 0) {
  2497. return 0;
  2498. }
  2499. if (k === 1) {
  2500. return 1;
  2501. }
  2502. if (!a || a < 1) {
  2503. a = 1;
  2504. s = p / 4;
  2505. }
  2506. else {
  2507. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2508. }
  2509. if ((k *= 2) < 1) {
  2510. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2511. * Math.sin((k - s) * (2 * Math.PI) / p));
  2512. }
  2513. return a * Math.pow(2, -10 * (k -= 1))
  2514. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2515. },
  2516. backIn: function (k) {
  2517. var s = 1.70158;
  2518. return k * k * ((s + 1) * k - s);
  2519. },
  2520. backOut: function (k) {
  2521. var s = 1.70158;
  2522. return --k * k * ((s + 1) * k + s) + 1;
  2523. },
  2524. backInOut: function (k) {
  2525. var s = 1.70158 * 1.525;
  2526. if ((k *= 2) < 1) {
  2527. return 0.5 * (k * k * ((s + 1) * k - s));
  2528. }
  2529. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2530. },
  2531. bounceIn: function (k) {
  2532. return 1 - easingFuncs.bounceOut(1 - k);
  2533. },
  2534. bounceOut: function (k) {
  2535. if (k < (1 / 2.75)) {
  2536. return 7.5625 * k * k;
  2537. }
  2538. else if (k < (2 / 2.75)) {
  2539. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2540. }
  2541. else if (k < (2.5 / 2.75)) {
  2542. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2543. }
  2544. else {
  2545. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2546. }
  2547. },
  2548. bounceInOut: function (k) {
  2549. if (k < 0.5) {
  2550. return easingFuncs.bounceIn(k * 2) * 0.5;
  2551. }
  2552. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2553. }
  2554. };
  2555. var mathPow = Math.pow;
  2556. var mathSqrt = Math.sqrt;
  2557. var EPSILON = 1e-8;
  2558. var EPSILON_NUMERIC = 1e-4;
  2559. var THREE_SQRT = mathSqrt(3);
  2560. var ONE_THIRD = 1 / 3;
  2561. var _v0 = create();
  2562. var _v1 = create();
  2563. var _v2 = create();
  2564. function isAroundZero(val) {
  2565. return val > -EPSILON && val < EPSILON;
  2566. }
  2567. function isNotAroundZero(val) {
  2568. return val > EPSILON || val < -EPSILON;
  2569. }
  2570. function cubicAt(p0, p1, p2, p3, t) {
  2571. var onet = 1 - t;
  2572. return onet * onet * (onet * p0 + 3 * t * p1)
  2573. + t * t * (t * p3 + 3 * onet * p2);
  2574. }
  2575. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  2576. var onet = 1 - t;
  2577. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  2578. + (p3 - p2) * t * t);
  2579. }
  2580. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  2581. var a = p3 + 3 * (p1 - p2) - p0;
  2582. var b = 3 * (p2 - p1 * 2 + p0);
  2583. var c = 3 * (p1 - p0);
  2584. var d = p0 - val;
  2585. var A = b * b - 3 * a * c;
  2586. var B = b * c - 9 * a * d;
  2587. var C = c * c - 3 * b * d;
  2588. var n = 0;
  2589. if (isAroundZero(A) && isAroundZero(B)) {
  2590. if (isAroundZero(b)) {
  2591. roots[0] = 0;
  2592. }
  2593. else {
  2594. var t1 = -c / b;
  2595. if (t1 >= 0 && t1 <= 1) {
  2596. roots[n++] = t1;
  2597. }
  2598. }
  2599. }
  2600. else {
  2601. var disc = B * B - 4 * A * C;
  2602. if (isAroundZero(disc)) {
  2603. var K = B / A;
  2604. var t1 = -b / a + K;
  2605. var t2 = -K / 2;
  2606. if (t1 >= 0 && t1 <= 1) {
  2607. roots[n++] = t1;
  2608. }
  2609. if (t2 >= 0 && t2 <= 1) {
  2610. roots[n++] = t2;
  2611. }
  2612. }
  2613. else if (disc > 0) {
  2614. var discSqrt = mathSqrt(disc);
  2615. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  2616. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  2617. if (Y1 < 0) {
  2618. Y1 = -mathPow(-Y1, ONE_THIRD);
  2619. }
  2620. else {
  2621. Y1 = mathPow(Y1, ONE_THIRD);
  2622. }
  2623. if (Y2 < 0) {
  2624. Y2 = -mathPow(-Y2, ONE_THIRD);
  2625. }
  2626. else {
  2627. Y2 = mathPow(Y2, ONE_THIRD);
  2628. }
  2629. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  2630. if (t1 >= 0 && t1 <= 1) {
  2631. roots[n++] = t1;
  2632. }
  2633. }
  2634. else {
  2635. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  2636. var theta = Math.acos(T) / 3;
  2637. var ASqrt = mathSqrt(A);
  2638. var tmp = Math.cos(theta);
  2639. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  2640. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  2641. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  2642. if (t1 >= 0 && t1 <= 1) {
  2643. roots[n++] = t1;
  2644. }
  2645. if (t2 >= 0 && t2 <= 1) {
  2646. roots[n++] = t2;
  2647. }
  2648. if (t3 >= 0 && t3 <= 1) {
  2649. roots[n++] = t3;
  2650. }
  2651. }
  2652. }
  2653. return n;
  2654. }
  2655. function cubicExtrema(p0, p1, p2, p3, extrema) {
  2656. var b = 6 * p2 - 12 * p1 + 6 * p0;
  2657. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  2658. var c = 3 * p1 - 3 * p0;
  2659. var n = 0;
  2660. if (isAroundZero(a)) {
  2661. if (isNotAroundZero(b)) {
  2662. var t1 = -c / b;
  2663. if (t1 >= 0 && t1 <= 1) {
  2664. extrema[n++] = t1;
  2665. }
  2666. }
  2667. }
  2668. else {
  2669. var disc = b * b - 4 * a * c;
  2670. if (isAroundZero(disc)) {
  2671. extrema[0] = -b / (2 * a);
  2672. }
  2673. else if (disc > 0) {
  2674. var discSqrt = mathSqrt(disc);
  2675. var t1 = (-b + discSqrt) / (2 * a);
  2676. var t2 = (-b - discSqrt) / (2 * a);
  2677. if (t1 >= 0 && t1 <= 1) {
  2678. extrema[n++] = t1;
  2679. }
  2680. if (t2 >= 0 && t2 <= 1) {
  2681. extrema[n++] = t2;
  2682. }
  2683. }
  2684. }
  2685. return n;
  2686. }
  2687. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  2688. var p01 = (p1 - p0) * t + p0;
  2689. var p12 = (p2 - p1) * t + p1;
  2690. var p23 = (p3 - p2) * t + p2;
  2691. var p012 = (p12 - p01) * t + p01;
  2692. var p123 = (p23 - p12) * t + p12;
  2693. var p0123 = (p123 - p012) * t + p012;
  2694. out[0] = p0;
  2695. out[1] = p01;
  2696. out[2] = p012;
  2697. out[3] = p0123;
  2698. out[4] = p0123;
  2699. out[5] = p123;
  2700. out[6] = p23;
  2701. out[7] = p3;
  2702. }
  2703. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  2704. var t;
  2705. var interval = 0.005;
  2706. var d = Infinity;
  2707. var prev;
  2708. var next;
  2709. var d1;
  2710. var d2;
  2711. _v0[0] = x;
  2712. _v0[1] = y;
  2713. for (var _t = 0; _t < 1; _t += 0.05) {
  2714. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  2715. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  2716. d1 = distSquare(_v0, _v1);
  2717. if (d1 < d) {
  2718. t = _t;
  2719. d = d1;
  2720. }
  2721. }
  2722. d = Infinity;
  2723. for (var i = 0; i < 32; i++) {
  2724. if (interval < EPSILON_NUMERIC) {
  2725. break;
  2726. }
  2727. prev = t - interval;
  2728. next = t + interval;
  2729. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  2730. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  2731. d1 = distSquare(_v1, _v0);
  2732. if (prev >= 0 && d1 < d) {
  2733. t = prev;
  2734. d = d1;
  2735. }
  2736. else {
  2737. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  2738. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  2739. d2 = distSquare(_v2, _v0);
  2740. if (next <= 1 && d2 < d) {
  2741. t = next;
  2742. d = d2;
  2743. }
  2744. else {
  2745. interval *= 0.5;
  2746. }
  2747. }
  2748. }
  2749. if (out) {
  2750. out[0] = cubicAt(x0, x1, x2, x3, t);
  2751. out[1] = cubicAt(y0, y1, y2, y3, t);
  2752. }
  2753. return mathSqrt(d);
  2754. }
  2755. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  2756. var px = x0;
  2757. var py = y0;
  2758. var d = 0;
  2759. var step = 1 / iteration;
  2760. for (var i = 1; i <= iteration; i++) {
  2761. var t = i * step;
  2762. var x = cubicAt(x0, x1, x2, x3, t);
  2763. var y = cubicAt(y0, y1, y2, y3, t);
  2764. var dx = x - px;
  2765. var dy = y - py;
  2766. d += Math.sqrt(dx * dx + dy * dy);
  2767. px = x;
  2768. py = y;
  2769. }
  2770. return d;
  2771. }
  2772. function quadraticAt(p0, p1, p2, t) {
  2773. var onet = 1 - t;
  2774. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  2775. }
  2776. function quadraticDerivativeAt(p0, p1, p2, t) {
  2777. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  2778. }
  2779. function quadraticRootAt(p0, p1, p2, val, roots) {
  2780. var a = p0 - 2 * p1 + p2;
  2781. var b = 2 * (p1 - p0);
  2782. var c = p0 - val;
  2783. var n = 0;
  2784. if (isAroundZero(a)) {
  2785. if (isNotAroundZero(b)) {
  2786. var t1 = -c / b;
  2787. if (t1 >= 0 && t1 <= 1) {
  2788. roots[n++] = t1;
  2789. }
  2790. }
  2791. }
  2792. else {
  2793. var disc = b * b - 4 * a * c;
  2794. if (isAroundZero(disc)) {
  2795. var t1 = -b / (2 * a);
  2796. if (t1 >= 0 && t1 <= 1) {
  2797. roots[n++] = t1;
  2798. }
  2799. }
  2800. else if (disc > 0) {
  2801. var discSqrt = mathSqrt(disc);
  2802. var t1 = (-b + discSqrt) / (2 * a);
  2803. var t2 = (-b - discSqrt) / (2 * a);
  2804. if (t1 >= 0 && t1 <= 1) {
  2805. roots[n++] = t1;
  2806. }
  2807. if (t2 >= 0 && t2 <= 1) {
  2808. roots[n++] = t2;
  2809. }
  2810. }
  2811. }
  2812. return n;
  2813. }
  2814. function quadraticExtremum(p0, p1, p2) {
  2815. var divider = p0 + p2 - 2 * p1;
  2816. if (divider === 0) {
  2817. return 0.5;
  2818. }
  2819. else {
  2820. return (p0 - p1) / divider;
  2821. }
  2822. }
  2823. function quadraticSubdivide(p0, p1, p2, t, out) {
  2824. var p01 = (p1 - p0) * t + p0;
  2825. var p12 = (p2 - p1) * t + p1;
  2826. var p012 = (p12 - p01) * t + p01;
  2827. out[0] = p0;
  2828. out[1] = p01;
  2829. out[2] = p012;
  2830. out[3] = p012;
  2831. out[4] = p12;
  2832. out[5] = p2;
  2833. }
  2834. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  2835. var t;
  2836. var interval = 0.005;
  2837. var d = Infinity;
  2838. _v0[0] = x;
  2839. _v0[1] = y;
  2840. for (var _t = 0; _t < 1; _t += 0.05) {
  2841. _v1[0] = quadraticAt(x0, x1, x2, _t);
  2842. _v1[1] = quadraticAt(y0, y1, y2, _t);
  2843. var d1 = distSquare(_v0, _v1);
  2844. if (d1 < d) {
  2845. t = _t;
  2846. d = d1;
  2847. }
  2848. }
  2849. d = Infinity;
  2850. for (var i = 0; i < 32; i++) {
  2851. if (interval < EPSILON_NUMERIC) {
  2852. break;
  2853. }
  2854. var prev = t - interval;
  2855. var next = t + interval;
  2856. _v1[0] = quadraticAt(x0, x1, x2, prev);
  2857. _v1[1] = quadraticAt(y0, y1, y2, prev);
  2858. var d1 = distSquare(_v1, _v0);
  2859. if (prev >= 0 && d1 < d) {
  2860. t = prev;
  2861. d = d1;
  2862. }
  2863. else {
  2864. _v2[0] = quadraticAt(x0, x1, x2, next);
  2865. _v2[1] = quadraticAt(y0, y1, y2, next);
  2866. var d2 = distSquare(_v2, _v0);
  2867. if (next <= 1 && d2 < d) {
  2868. t = next;
  2869. d = d2;
  2870. }
  2871. else {
  2872. interval *= 0.5;
  2873. }
  2874. }
  2875. }
  2876. if (out) {
  2877. out[0] = quadraticAt(x0, x1, x2, t);
  2878. out[1] = quadraticAt(y0, y1, y2, t);
  2879. }
  2880. return mathSqrt(d);
  2881. }
  2882. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  2883. var px = x0;
  2884. var py = y0;
  2885. var d = 0;
  2886. var step = 1 / iteration;
  2887. for (var i = 1; i <= iteration; i++) {
  2888. var t = i * step;
  2889. var x = quadraticAt(x0, x1, x2, t);
  2890. var y = quadraticAt(y0, y1, y2, t);
  2891. var dx = x - px;
  2892. var dy = y - py;
  2893. d += Math.sqrt(dx * dx + dy * dy);
  2894. px = x;
  2895. py = y;
  2896. }
  2897. return d;
  2898. }
  2899. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  2900. function createCubicEasingFunc(cubicEasingStr) {
  2901. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  2902. if (cubic) {
  2903. var points = cubic[1].split(',');
  2904. var a_1 = +trim(points[0]);
  2905. var b_1 = +trim(points[1]);
  2906. var c_1 = +trim(points[2]);
  2907. var d_1 = +trim(points[3]);
  2908. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  2909. return;
  2910. }
  2911. var roots_1 = [];
  2912. return function (p) {
  2913. return p <= 0
  2914. ? 0 : p >= 1
  2915. ? 1
  2916. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  2917. };
  2918. }
  2919. }
  2920. var Clip = (function () {
  2921. function Clip(opts) {
  2922. this._inited = false;
  2923. this._startTime = 0;
  2924. this._pausedTime = 0;
  2925. this._paused = false;
  2926. this._life = opts.life || 1000;
  2927. this._delay = opts.delay || 0;
  2928. this.loop = opts.loop || false;
  2929. this.onframe = opts.onframe || noop;
  2930. this.ondestroy = opts.ondestroy || noop;
  2931. this.onrestart = opts.onrestart || noop;
  2932. opts.easing && this.setEasing(opts.easing);
  2933. }
  2934. Clip.prototype.step = function (globalTime, deltaTime) {
  2935. if (!this._inited) {
  2936. this._startTime = globalTime + this._delay;
  2937. this._inited = true;
  2938. }
  2939. if (this._paused) {
  2940. this._pausedTime += deltaTime;
  2941. return;
  2942. }
  2943. var life = this._life;
  2944. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  2945. var percent = elapsedTime / life;
  2946. if (percent < 0) {
  2947. percent = 0;
  2948. }
  2949. percent = Math.min(percent, 1);
  2950. var easingFunc = this.easingFunc;
  2951. var schedule = easingFunc ? easingFunc(percent) : percent;
  2952. this.onframe(schedule);
  2953. if (percent === 1) {
  2954. if (this.loop) {
  2955. var remainder = elapsedTime % life;
  2956. this._startTime = globalTime - remainder;
  2957. this._pausedTime = 0;
  2958. this.onrestart();
  2959. }
  2960. else {
  2961. return true;
  2962. }
  2963. }
  2964. return false;
  2965. };
  2966. Clip.prototype.pause = function () {
  2967. this._paused = true;
  2968. };
  2969. Clip.prototype.resume = function () {
  2970. this._paused = false;
  2971. };
  2972. Clip.prototype.setEasing = function (easing) {
  2973. this.easing = easing;
  2974. this.easingFunc = isFunction(easing)
  2975. ? easing
  2976. : easingFuncs[easing] || createCubicEasingFunc(easing);
  2977. };
  2978. return Clip;
  2979. }());
  2980. var Entry = (function () {
  2981. function Entry(val) {
  2982. this.value = val;
  2983. }
  2984. return Entry;
  2985. }());
  2986. var LinkedList = (function () {
  2987. function LinkedList() {
  2988. this._len = 0;
  2989. }
  2990. LinkedList.prototype.insert = function (val) {
  2991. var entry = new Entry(val);
  2992. this.insertEntry(entry);
  2993. return entry;
  2994. };
  2995. LinkedList.prototype.insertEntry = function (entry) {
  2996. if (!this.head) {
  2997. this.head = this.tail = entry;
  2998. }
  2999. else {
  3000. this.tail.next = entry;
  3001. entry.prev = this.tail;
  3002. entry.next = null;
  3003. this.tail = entry;
  3004. }
  3005. this._len++;
  3006. };
  3007. LinkedList.prototype.remove = function (entry) {
  3008. var prev = entry.prev;
  3009. var next = entry.next;
  3010. if (prev) {
  3011. prev.next = next;
  3012. }
  3013. else {
  3014. this.head = next;
  3015. }
  3016. if (next) {
  3017. next.prev = prev;
  3018. }
  3019. else {
  3020. this.tail = prev;
  3021. }
  3022. entry.next = entry.prev = null;
  3023. this._len--;
  3024. };
  3025. LinkedList.prototype.len = function () {
  3026. return this._len;
  3027. };
  3028. LinkedList.prototype.clear = function () {
  3029. this.head = this.tail = null;
  3030. this._len = 0;
  3031. };
  3032. return LinkedList;
  3033. }());
  3034. var LRU = (function () {
  3035. function LRU(maxSize) {
  3036. this._list = new LinkedList();
  3037. this._maxSize = 10;
  3038. this._map = {};
  3039. this._maxSize = maxSize;
  3040. }
  3041. LRU.prototype.put = function (key, value) {
  3042. var list = this._list;
  3043. var map = this._map;
  3044. var removed = null;
  3045. if (map[key] == null) {
  3046. var len = list.len();
  3047. var entry = this._lastRemovedEntry;
  3048. if (len >= this._maxSize && len > 0) {
  3049. var leastUsedEntry = list.head;
  3050. list.remove(leastUsedEntry);
  3051. delete map[leastUsedEntry.key];
  3052. removed = leastUsedEntry.value;
  3053. this._lastRemovedEntry = leastUsedEntry;
  3054. }
  3055. if (entry) {
  3056. entry.value = value;
  3057. }
  3058. else {
  3059. entry = new Entry(value);
  3060. }
  3061. entry.key = key;
  3062. list.insertEntry(entry);
  3063. map[key] = entry;
  3064. }
  3065. return removed;
  3066. };
  3067. LRU.prototype.get = function (key) {
  3068. var entry = this._map[key];
  3069. var list = this._list;
  3070. if (entry != null) {
  3071. if (entry !== list.tail) {
  3072. list.remove(entry);
  3073. list.insertEntry(entry);
  3074. }
  3075. return entry.value;
  3076. }
  3077. };
  3078. LRU.prototype.clear = function () {
  3079. this._list.clear();
  3080. this._map = {};
  3081. };
  3082. LRU.prototype.len = function () {
  3083. return this._list.len();
  3084. };
  3085. return LRU;
  3086. }());
  3087. var kCSSColorTable = {
  3088. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3089. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3090. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3091. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3092. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3093. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3094. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3095. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3096. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3097. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3098. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3099. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3100. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3101. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3102. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3103. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3104. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3105. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3106. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3107. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3108. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3109. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3110. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3111. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3112. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3113. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3114. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3115. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3116. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3117. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3118. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3119. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3120. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3121. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3122. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3123. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3124. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3125. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3126. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3127. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3128. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3129. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3130. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3131. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3132. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3133. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3134. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3135. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3136. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3137. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3138. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3139. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3140. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3141. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3142. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3143. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3144. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3145. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3146. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3147. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3148. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3149. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3150. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3151. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3152. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3153. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3154. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3155. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3156. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3157. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3158. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3159. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3160. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3161. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3162. };
  3163. function clampCssByte(i) {
  3164. i = Math.round(i);
  3165. return i < 0 ? 0 : i > 255 ? 255 : i;
  3166. }
  3167. function clampCssAngle(i) {
  3168. i = Math.round(i);
  3169. return i < 0 ? 0 : i > 360 ? 360 : i;
  3170. }
  3171. function clampCssFloat(f) {
  3172. return f < 0 ? 0 : f > 1 ? 1 : f;
  3173. }
  3174. function parseCssInt(val) {
  3175. var str = val;
  3176. if (str.length && str.charAt(str.length - 1) === '%') {
  3177. return clampCssByte(parseFloat(str) / 100 * 255);
  3178. }
  3179. return clampCssByte(parseInt(str, 10));
  3180. }
  3181. function parseCssFloat(val) {
  3182. var str = val;
  3183. if (str.length && str.charAt(str.length - 1) === '%') {
  3184. return clampCssFloat(parseFloat(str) / 100);
  3185. }
  3186. return clampCssFloat(parseFloat(str));
  3187. }
  3188. function cssHueToRgb(m1, m2, h) {
  3189. if (h < 0) {
  3190. h += 1;
  3191. }
  3192. else if (h > 1) {
  3193. h -= 1;
  3194. }
  3195. if (h * 6 < 1) {
  3196. return m1 + (m2 - m1) * h * 6;
  3197. }
  3198. if (h * 2 < 1) {
  3199. return m2;
  3200. }
  3201. if (h * 3 < 2) {
  3202. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3203. }
  3204. return m1;
  3205. }
  3206. function lerpNumber(a, b, p) {
  3207. return a + (b - a) * p;
  3208. }
  3209. function setRgba(out, r, g, b, a) {
  3210. out[0] = r;
  3211. out[1] = g;
  3212. out[2] = b;
  3213. out[3] = a;
  3214. return out;
  3215. }
  3216. function copyRgba(out, a) {
  3217. out[0] = a[0];
  3218. out[1] = a[1];
  3219. out[2] = a[2];
  3220. out[3] = a[3];
  3221. return out;
  3222. }
  3223. var colorCache = new LRU(20);
  3224. var lastRemovedArr = null;
  3225. function putToCache(colorStr, rgbaArr) {
  3226. if (lastRemovedArr) {
  3227. copyRgba(lastRemovedArr, rgbaArr);
  3228. }
  3229. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3230. }
  3231. function parse(colorStr, rgbaArr) {
  3232. if (!colorStr) {
  3233. return;
  3234. }
  3235. rgbaArr = rgbaArr || [];
  3236. var cached = colorCache.get(colorStr);
  3237. if (cached) {
  3238. return copyRgba(rgbaArr, cached);
  3239. }
  3240. colorStr = colorStr + '';
  3241. var str = colorStr.replace(/ /g, '').toLowerCase();
  3242. if (str in kCSSColorTable) {
  3243. copyRgba(rgbaArr, kCSSColorTable[str]);
  3244. putToCache(colorStr, rgbaArr);
  3245. return rgbaArr;
  3246. }
  3247. var strLen = str.length;
  3248. if (str.charAt(0) === '#') {
  3249. if (strLen === 4 || strLen === 5) {
  3250. var iv = parseInt(str.slice(1, 4), 16);
  3251. if (!(iv >= 0 && iv <= 0xfff)) {
  3252. setRgba(rgbaArr, 0, 0, 0, 1);
  3253. return;
  3254. }
  3255. 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);
  3256. putToCache(colorStr, rgbaArr);
  3257. return rgbaArr;
  3258. }
  3259. else if (strLen === 7 || strLen === 9) {
  3260. var iv = parseInt(str.slice(1, 7), 16);
  3261. if (!(iv >= 0 && iv <= 0xffffff)) {
  3262. setRgba(rgbaArr, 0, 0, 0, 1);
  3263. return;
  3264. }
  3265. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3266. putToCache(colorStr, rgbaArr);
  3267. return rgbaArr;
  3268. }
  3269. return;
  3270. }
  3271. var op = str.indexOf('(');
  3272. var ep = str.indexOf(')');
  3273. if (op !== -1 && ep + 1 === strLen) {
  3274. var fname = str.substr(0, op);
  3275. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3276. var alpha = 1;
  3277. switch (fname) {
  3278. case 'rgba':
  3279. if (params.length !== 4) {
  3280. return params.length === 3
  3281. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3282. : setRgba(rgbaArr, 0, 0, 0, 1);
  3283. }
  3284. alpha = parseCssFloat(params.pop());
  3285. case 'rgb':
  3286. if (params.length !== 3) {
  3287. setRgba(rgbaArr, 0, 0, 0, 1);
  3288. return;
  3289. }
  3290. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  3291. putToCache(colorStr, rgbaArr);
  3292. return rgbaArr;
  3293. case 'hsla':
  3294. if (params.length !== 4) {
  3295. setRgba(rgbaArr, 0, 0, 0, 1);
  3296. return;
  3297. }
  3298. params[3] = parseCssFloat(params[3]);
  3299. hsla2rgba(params, rgbaArr);
  3300. putToCache(colorStr, rgbaArr);
  3301. return rgbaArr;
  3302. case 'hsl':
  3303. if (params.length !== 3) {
  3304. setRgba(rgbaArr, 0, 0, 0, 1);
  3305. return;
  3306. }
  3307. hsla2rgba(params, rgbaArr);
  3308. putToCache(colorStr, rgbaArr);
  3309. return rgbaArr;
  3310. default:
  3311. return;
  3312. }
  3313. }
  3314. setRgba(rgbaArr, 0, 0, 0, 1);
  3315. return;
  3316. }
  3317. function hsla2rgba(hsla, rgba) {
  3318. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3319. var s = parseCssFloat(hsla[1]);
  3320. var l = parseCssFloat(hsla[2]);
  3321. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3322. var m1 = l * 2 - m2;
  3323. rgba = rgba || [];
  3324. 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);
  3325. if (hsla.length === 4) {
  3326. rgba[3] = hsla[3];
  3327. }
  3328. return rgba;
  3329. }
  3330. function rgba2hsla(rgba) {
  3331. if (!rgba) {
  3332. return;
  3333. }
  3334. var R = rgba[0] / 255;
  3335. var G = rgba[1] / 255;
  3336. var B = rgba[2] / 255;
  3337. var vMin = Math.min(R, G, B);
  3338. var vMax = Math.max(R, G, B);
  3339. var delta = vMax - vMin;
  3340. var L = (vMax + vMin) / 2;
  3341. var H;
  3342. var S;
  3343. if (delta === 0) {
  3344. H = 0;
  3345. S = 0;
  3346. }
  3347. else {
  3348. if (L < 0.5) {
  3349. S = delta / (vMax + vMin);
  3350. }
  3351. else {
  3352. S = delta / (2 - vMax - vMin);
  3353. }
  3354. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3355. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3356. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3357. if (R === vMax) {
  3358. H = deltaB - deltaG;
  3359. }
  3360. else if (G === vMax) {
  3361. H = (1 / 3) + deltaR - deltaB;
  3362. }
  3363. else if (B === vMax) {
  3364. H = (2 / 3) + deltaG - deltaR;
  3365. }
  3366. if (H < 0) {
  3367. H += 1;
  3368. }
  3369. if (H > 1) {
  3370. H -= 1;
  3371. }
  3372. }
  3373. var hsla = [H * 360, S, L];
  3374. if (rgba[3] != null) {
  3375. hsla.push(rgba[3]);
  3376. }
  3377. return hsla;
  3378. }
  3379. function lift(color, level) {
  3380. var colorArr = parse(color);
  3381. if (colorArr) {
  3382. for (var i = 0; i < 3; i++) {
  3383. if (level < 0) {
  3384. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3385. }
  3386. else {
  3387. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3388. }
  3389. if (colorArr[i] > 255) {
  3390. colorArr[i] = 255;
  3391. }
  3392. else if (colorArr[i] < 0) {
  3393. colorArr[i] = 0;
  3394. }
  3395. }
  3396. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3397. }
  3398. }
  3399. function toHex(color) {
  3400. var colorArr = parse(color);
  3401. if (colorArr) {
  3402. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3403. }
  3404. }
  3405. function fastLerp(normalizedValue, colors, out) {
  3406. if (!(colors && colors.length)
  3407. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3408. return;
  3409. }
  3410. out = out || [];
  3411. var value = normalizedValue * (colors.length - 1);
  3412. var leftIndex = Math.floor(value);
  3413. var rightIndex = Math.ceil(value);
  3414. var leftColor = colors[leftIndex];
  3415. var rightColor = colors[rightIndex];
  3416. var dv = value - leftIndex;
  3417. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3418. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3419. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3420. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3421. return out;
  3422. }
  3423. var fastMapToColor = fastLerp;
  3424. function lerp$1(normalizedValue, colors, fullOutput) {
  3425. if (!(colors && colors.length)
  3426. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3427. return;
  3428. }
  3429. var value = normalizedValue * (colors.length - 1);
  3430. var leftIndex = Math.floor(value);
  3431. var rightIndex = Math.ceil(value);
  3432. var leftColor = parse(colors[leftIndex]);
  3433. var rightColor = parse(colors[rightIndex]);
  3434. var dv = value - leftIndex;
  3435. var color = stringify([
  3436. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3437. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3438. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3439. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3440. ], 'rgba');
  3441. return fullOutput
  3442. ? {
  3443. color: color,
  3444. leftIndex: leftIndex,
  3445. rightIndex: rightIndex,
  3446. value: value
  3447. }
  3448. : color;
  3449. }
  3450. var mapToColor = lerp$1;
  3451. function modifyHSL(color, h, s, l) {
  3452. var colorArr = parse(color);
  3453. if (color) {
  3454. colorArr = rgba2hsla(colorArr);
  3455. h != null && (colorArr[0] = clampCssAngle(h));
  3456. s != null && (colorArr[1] = parseCssFloat(s));
  3457. l != null && (colorArr[2] = parseCssFloat(l));
  3458. return stringify(hsla2rgba(colorArr), 'rgba');
  3459. }
  3460. }
  3461. function modifyAlpha(color, alpha) {
  3462. var colorArr = parse(color);
  3463. if (colorArr && alpha != null) {
  3464. colorArr[3] = clampCssFloat(alpha);
  3465. return stringify(colorArr, 'rgba');
  3466. }
  3467. }
  3468. function stringify(arrColor, type) {
  3469. if (!arrColor || !arrColor.length) {
  3470. return;
  3471. }
  3472. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3473. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3474. colorStr += ',' + arrColor[3];
  3475. }
  3476. return type + '(' + colorStr + ')';
  3477. }
  3478. function lum(color, backgroundLum) {
  3479. var arr = parse(color);
  3480. return arr
  3481. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  3482. + (1 - arr[3]) * backgroundLum
  3483. : 0;
  3484. }
  3485. function random() {
  3486. return stringify([
  3487. Math.round(Math.random() * 255),
  3488. Math.round(Math.random() * 255),
  3489. Math.round(Math.random() * 255)
  3490. ], 'rgb');
  3491. }
  3492. var color = /*#__PURE__*/Object.freeze({
  3493. __proto__: null,
  3494. parse: parse,
  3495. lift: lift,
  3496. toHex: toHex,
  3497. fastLerp: fastLerp,
  3498. fastMapToColor: fastMapToColor,
  3499. lerp: lerp$1,
  3500. mapToColor: mapToColor,
  3501. modifyHSL: modifyHSL,
  3502. modifyAlpha: modifyAlpha,
  3503. stringify: stringify,
  3504. lum: lum,
  3505. random: random
  3506. });
  3507. function isLinearGradient(val) {
  3508. return val.type === 'linear';
  3509. }
  3510. function isRadialGradient(val) {
  3511. return val.type === 'radial';
  3512. }
  3513. var arraySlice = Array.prototype.slice;
  3514. function interpolateNumber(p0, p1, percent) {
  3515. return (p1 - p0) * percent + p0;
  3516. }
  3517. function interpolate1DArray(out, p0, p1, percent) {
  3518. var len = p0.length;
  3519. for (var i = 0; i < len; i++) {
  3520. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3521. }
  3522. return out;
  3523. }
  3524. function interpolate2DArray(out, p0, p1, percent) {
  3525. var len = p0.length;
  3526. var len2 = len && p0[0].length;
  3527. for (var i = 0; i < len; i++) {
  3528. if (!out[i]) {
  3529. out[i] = [];
  3530. }
  3531. for (var j = 0; j < len2; j++) {
  3532. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  3533. }
  3534. }
  3535. return out;
  3536. }
  3537. function add1DArray(out, p0, p1, sign) {
  3538. var len = p0.length;
  3539. for (var i = 0; i < len; i++) {
  3540. out[i] = p0[i] + p1[i] * sign;
  3541. }
  3542. return out;
  3543. }
  3544. function add2DArray(out, p0, p1, sign) {
  3545. var len = p0.length;
  3546. var len2 = len && p0[0].length;
  3547. for (var i = 0; i < len; i++) {
  3548. if (!out[i]) {
  3549. out[i] = [];
  3550. }
  3551. for (var j = 0; j < len2; j++) {
  3552. out[i][j] = p0[i][j] + p1[i][j] * sign;
  3553. }
  3554. }
  3555. return out;
  3556. }
  3557. function fillColorStops(val0, val1) {
  3558. var len0 = val0.length;
  3559. var len1 = val1.length;
  3560. var shorterArr = len0 > len1 ? val1 : val0;
  3561. var shorterLen = Math.min(len0, len1);
  3562. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  3563. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  3564. shorterArr.push({
  3565. offset: last.offset,
  3566. color: last.color.slice()
  3567. });
  3568. }
  3569. }
  3570. function fillArray(val0, val1, arrDim) {
  3571. var arr0 = val0;
  3572. var arr1 = val1;
  3573. if (!arr0.push || !arr1.push) {
  3574. return;
  3575. }
  3576. var arr0Len = arr0.length;
  3577. var arr1Len = arr1.length;
  3578. if (arr0Len !== arr1Len) {
  3579. var isPreviousLarger = arr0Len > arr1Len;
  3580. if (isPreviousLarger) {
  3581. arr0.length = arr1Len;
  3582. }
  3583. else {
  3584. for (var i = arr0Len; i < arr1Len; i++) {
  3585. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  3586. }
  3587. }
  3588. }
  3589. var len2 = arr0[0] && arr0[0].length;
  3590. for (var i = 0; i < arr0.length; i++) {
  3591. if (arrDim === 1) {
  3592. if (isNaN(arr0[i])) {
  3593. arr0[i] = arr1[i];
  3594. }
  3595. }
  3596. else {
  3597. for (var j = 0; j < len2; j++) {
  3598. if (isNaN(arr0[i][j])) {
  3599. arr0[i][j] = arr1[i][j];
  3600. }
  3601. }
  3602. }
  3603. }
  3604. }
  3605. function cloneValue(value) {
  3606. if (isArrayLike(value)) {
  3607. var len = value.length;
  3608. if (isArrayLike(value[0])) {
  3609. var ret = [];
  3610. for (var i = 0; i < len; i++) {
  3611. ret.push(arraySlice.call(value[i]));
  3612. }
  3613. return ret;
  3614. }
  3615. return arraySlice.call(value);
  3616. }
  3617. return value;
  3618. }
  3619. function rgba2String(rgba) {
  3620. rgba[0] = Math.floor(rgba[0]) || 0;
  3621. rgba[1] = Math.floor(rgba[1]) || 0;
  3622. rgba[2] = Math.floor(rgba[2]) || 0;
  3623. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  3624. return 'rgba(' + rgba.join(',') + ')';
  3625. }
  3626. function guessArrayDim(value) {
  3627. return isArrayLike(value && value[0]) ? 2 : 1;
  3628. }
  3629. var VALUE_TYPE_NUMBER = 0;
  3630. var VALUE_TYPE_1D_ARRAY = 1;
  3631. var VALUE_TYPE_2D_ARRAY = 2;
  3632. var VALUE_TYPE_COLOR = 3;
  3633. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  3634. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  3635. var VALUE_TYPE_UNKOWN = 6;
  3636. function isGradientValueType(valType) {
  3637. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  3638. }
  3639. function isArrayValueType(valType) {
  3640. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  3641. }
  3642. var tmpRgba = [0, 0, 0, 0];
  3643. var Track = (function () {
  3644. function Track(propName) {
  3645. this.keyframes = [];
  3646. this.discrete = false;
  3647. this._invalid = false;
  3648. this._needsSort = false;
  3649. this._lastFr = 0;
  3650. this._lastFrP = 0;
  3651. this.propName = propName;
  3652. }
  3653. Track.prototype.isFinished = function () {
  3654. return this._finished;
  3655. };
  3656. Track.prototype.setFinished = function () {
  3657. this._finished = true;
  3658. if (this._additiveTrack) {
  3659. this._additiveTrack.setFinished();
  3660. }
  3661. };
  3662. Track.prototype.needsAnimate = function () {
  3663. return this.keyframes.length >= 1;
  3664. };
  3665. Track.prototype.getAdditiveTrack = function () {
  3666. return this._additiveTrack;
  3667. };
  3668. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  3669. this._needsSort = true;
  3670. var keyframes = this.keyframes;
  3671. var len = keyframes.length;
  3672. var discrete = false;
  3673. var valType = VALUE_TYPE_UNKOWN;
  3674. var value = rawValue;
  3675. if (isArrayLike(rawValue)) {
  3676. var arrayDim = guessArrayDim(rawValue);
  3677. valType = arrayDim;
  3678. if (arrayDim === 1 && !isNumber(rawValue[0])
  3679. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  3680. discrete = true;
  3681. }
  3682. }
  3683. else {
  3684. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  3685. valType = VALUE_TYPE_NUMBER;
  3686. }
  3687. else if (isString(rawValue)) {
  3688. if (!isNaN(+rawValue)) {
  3689. valType = VALUE_TYPE_NUMBER;
  3690. }
  3691. else {
  3692. var colorArray = parse(rawValue);
  3693. if (colorArray) {
  3694. value = colorArray;
  3695. valType = VALUE_TYPE_COLOR;
  3696. }
  3697. }
  3698. }
  3699. else if (isGradientObject(rawValue)) {
  3700. var parsedGradient = extend({}, value);
  3701. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  3702. offset: colorStop.offset,
  3703. color: parse(colorStop.color)
  3704. }); });
  3705. if (isLinearGradient(rawValue)) {
  3706. valType = VALUE_TYPE_LINEAR_GRADIENT;
  3707. }
  3708. else if (isRadialGradient(rawValue)) {
  3709. valType = VALUE_TYPE_RADIAL_GRADIENT;
  3710. }
  3711. value = parsedGradient;
  3712. }
  3713. }
  3714. if (len === 0) {
  3715. this.valType = valType;
  3716. }
  3717. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  3718. discrete = true;
  3719. }
  3720. this.discrete = this.discrete || discrete;
  3721. var kf = {
  3722. time: time,
  3723. value: value,
  3724. rawValue: rawValue,
  3725. percent: 0
  3726. };
  3727. if (easing) {
  3728. kf.easing = easing;
  3729. kf.easingFunc = isFunction(easing)
  3730. ? easing
  3731. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3732. }
  3733. keyframes.push(kf);
  3734. return kf;
  3735. };
  3736. Track.prototype.prepare = function (maxTime, additiveTrack) {
  3737. var kfs = this.keyframes;
  3738. if (this._needsSort) {
  3739. kfs.sort(function (a, b) {
  3740. return a.time - b.time;
  3741. });
  3742. }
  3743. var valType = this.valType;
  3744. var kfsLen = kfs.length;
  3745. var lastKf = kfs[kfsLen - 1];
  3746. var isDiscrete = this.discrete;
  3747. var isArr = isArrayValueType(valType);
  3748. var isGradient = isGradientValueType(valType);
  3749. for (var i = 0; i < kfsLen; i++) {
  3750. var kf = kfs[i];
  3751. var value = kf.value;
  3752. var lastValue = lastKf.value;
  3753. kf.percent = kf.time / maxTime;
  3754. if (!isDiscrete) {
  3755. if (isArr && i !== kfsLen - 1) {
  3756. fillArray(value, lastValue, valType);
  3757. }
  3758. else if (isGradient) {
  3759. fillColorStops(value.colorStops, lastValue.colorStops);
  3760. }
  3761. }
  3762. }
  3763. if (!isDiscrete
  3764. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  3765. && additiveTrack
  3766. && this.needsAnimate()
  3767. && additiveTrack.needsAnimate()
  3768. && valType === additiveTrack.valType
  3769. && !additiveTrack._finished) {
  3770. this._additiveTrack = additiveTrack;
  3771. var startValue = kfs[0].value;
  3772. for (var i = 0; i < kfsLen; i++) {
  3773. if (valType === VALUE_TYPE_NUMBER) {
  3774. kfs[i].additiveValue = kfs[i].value - startValue;
  3775. }
  3776. else if (valType === VALUE_TYPE_COLOR) {
  3777. kfs[i].additiveValue =
  3778. add1DArray([], kfs[i].value, startValue, -1);
  3779. }
  3780. else if (isArrayValueType(valType)) {
  3781. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  3782. ? add1DArray([], kfs[i].value, startValue, -1)
  3783. : add2DArray([], kfs[i].value, startValue, -1);
  3784. }
  3785. }
  3786. }
  3787. };
  3788. Track.prototype.step = function (target, percent) {
  3789. if (this._finished) {
  3790. return;
  3791. }
  3792. if (this._additiveTrack && this._additiveTrack._finished) {
  3793. this._additiveTrack = null;
  3794. }
  3795. var isAdditive = this._additiveTrack != null;
  3796. var valueKey = isAdditive ? 'additiveValue' : 'value';
  3797. var valType = this.valType;
  3798. var keyframes = this.keyframes;
  3799. var kfsNum = keyframes.length;
  3800. var propName = this.propName;
  3801. var isValueColor = valType === VALUE_TYPE_COLOR;
  3802. var frameIdx;
  3803. var lastFrame = this._lastFr;
  3804. var mathMin = Math.min;
  3805. var frame;
  3806. var nextFrame;
  3807. if (kfsNum === 1) {
  3808. frame = nextFrame = keyframes[0];
  3809. }
  3810. else {
  3811. if (percent < 0) {
  3812. frameIdx = 0;
  3813. }
  3814. else if (percent < this._lastFrP) {
  3815. var start = mathMin(lastFrame + 1, kfsNum - 1);
  3816. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  3817. if (keyframes[frameIdx].percent <= percent) {
  3818. break;
  3819. }
  3820. }
  3821. frameIdx = mathMin(frameIdx, kfsNum - 2);
  3822. }
  3823. else {
  3824. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  3825. if (keyframes[frameIdx].percent > percent) {
  3826. break;
  3827. }
  3828. }
  3829. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  3830. }
  3831. nextFrame = keyframes[frameIdx + 1];
  3832. frame = keyframes[frameIdx];
  3833. }
  3834. if (!(frame && nextFrame)) {
  3835. return;
  3836. }
  3837. this._lastFr = frameIdx;
  3838. this._lastFrP = percent;
  3839. var interval = (nextFrame.percent - frame.percent);
  3840. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  3841. if (nextFrame.easingFunc) {
  3842. w = nextFrame.easingFunc(w);
  3843. }
  3844. var targetArr = isAdditive ? this._additiveValue
  3845. : (isValueColor ? tmpRgba : target[propName]);
  3846. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  3847. targetArr = this._additiveValue = [];
  3848. }
  3849. if (this.discrete) {
  3850. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  3851. }
  3852. else if (isArrayValueType(valType)) {
  3853. valType === VALUE_TYPE_1D_ARRAY
  3854. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  3855. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3856. }
  3857. else if (isGradientValueType(valType)) {
  3858. var val = frame[valueKey];
  3859. var nextVal_1 = nextFrame[valueKey];
  3860. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  3861. target[propName] = {
  3862. type: isLinearGradient_1 ? 'linear' : 'radial',
  3863. x: interpolateNumber(val.x, nextVal_1.x, w),
  3864. y: interpolateNumber(val.y, nextVal_1.y, w),
  3865. colorStops: map(val.colorStops, function (colorStop, idx) {
  3866. var nextColorStop = nextVal_1.colorStops[idx];
  3867. return {
  3868. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  3869. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  3870. };
  3871. }),
  3872. global: nextVal_1.global
  3873. };
  3874. if (isLinearGradient_1) {
  3875. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  3876. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  3877. }
  3878. else {
  3879. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  3880. }
  3881. }
  3882. else if (isValueColor) {
  3883. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3884. if (!isAdditive) {
  3885. target[propName] = rgba2String(targetArr);
  3886. }
  3887. }
  3888. else {
  3889. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  3890. if (isAdditive) {
  3891. this._additiveValue = value;
  3892. }
  3893. else {
  3894. target[propName] = value;
  3895. }
  3896. }
  3897. if (isAdditive) {
  3898. this._addToTarget(target);
  3899. }
  3900. };
  3901. Track.prototype._addToTarget = function (target) {
  3902. var valType = this.valType;
  3903. var propName = this.propName;
  3904. var additiveValue = this._additiveValue;
  3905. if (valType === VALUE_TYPE_NUMBER) {
  3906. target[propName] = target[propName] + additiveValue;
  3907. }
  3908. else if (valType === VALUE_TYPE_COLOR) {
  3909. parse(target[propName], tmpRgba);
  3910. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  3911. target[propName] = rgba2String(tmpRgba);
  3912. }
  3913. else if (valType === VALUE_TYPE_1D_ARRAY) {
  3914. add1DArray(target[propName], target[propName], additiveValue, 1);
  3915. }
  3916. else if (valType === VALUE_TYPE_2D_ARRAY) {
  3917. add2DArray(target[propName], target[propName], additiveValue, 1);
  3918. }
  3919. };
  3920. return Track;
  3921. }());
  3922. var Animator = (function () {
  3923. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  3924. this._tracks = {};
  3925. this._trackKeys = [];
  3926. this._maxTime = 0;
  3927. this._started = 0;
  3928. this._clip = null;
  3929. this._target = target;
  3930. this._loop = loop;
  3931. if (loop && additiveTo) {
  3932. logError('Can\' use additive animation on looped animation.');
  3933. return;
  3934. }
  3935. this._additiveAnimators = additiveTo;
  3936. this._allowDiscrete = allowDiscreteAnimation;
  3937. }
  3938. Animator.prototype.getMaxTime = function () {
  3939. return this._maxTime;
  3940. };
  3941. Animator.prototype.getDelay = function () {
  3942. return this._delay;
  3943. };
  3944. Animator.prototype.getLoop = function () {
  3945. return this._loop;
  3946. };
  3947. Animator.prototype.getTarget = function () {
  3948. return this._target;
  3949. };
  3950. Animator.prototype.changeTarget = function (target) {
  3951. this._target = target;
  3952. };
  3953. Animator.prototype.when = function (time, props, easing) {
  3954. return this.whenWithKeys(time, props, keys(props), easing);
  3955. };
  3956. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  3957. var tracks = this._tracks;
  3958. for (var i = 0; i < propNames.length; i++) {
  3959. var propName = propNames[i];
  3960. var track = tracks[propName];
  3961. if (!track) {
  3962. track = tracks[propName] = new Track(propName);
  3963. var initialValue = void 0;
  3964. var additiveTrack = this._getAdditiveTrack(propName);
  3965. if (additiveTrack) {
  3966. var addtiveTrackKfs = additiveTrack.keyframes;
  3967. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  3968. initialValue = lastFinalKf && lastFinalKf.value;
  3969. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  3970. initialValue = rgba2String(initialValue);
  3971. }
  3972. }
  3973. else {
  3974. initialValue = this._target[propName];
  3975. }
  3976. if (initialValue == null) {
  3977. continue;
  3978. }
  3979. if (time > 0) {
  3980. track.addKeyframe(0, cloneValue(initialValue), easing);
  3981. }
  3982. this._trackKeys.push(propName);
  3983. }
  3984. track.addKeyframe(time, cloneValue(props[propName]), easing);
  3985. }
  3986. this._maxTime = Math.max(this._maxTime, time);
  3987. return this;
  3988. };
  3989. Animator.prototype.pause = function () {
  3990. this._clip.pause();
  3991. this._paused = true;
  3992. };
  3993. Animator.prototype.resume = function () {
  3994. this._clip.resume();
  3995. this._paused = false;
  3996. };
  3997. Animator.prototype.isPaused = function () {
  3998. return !!this._paused;
  3999. };
  4000. Animator.prototype.duration = function (duration) {
  4001. this._maxTime = duration;
  4002. this._force = true;
  4003. return this;
  4004. };
  4005. Animator.prototype._doneCallback = function () {
  4006. this._setTracksFinished();
  4007. this._clip = null;
  4008. var doneList = this._doneCbs;
  4009. if (doneList) {
  4010. var len = doneList.length;
  4011. for (var i = 0; i < len; i++) {
  4012. doneList[i].call(this);
  4013. }
  4014. }
  4015. };
  4016. Animator.prototype._abortedCallback = function () {
  4017. this._setTracksFinished();
  4018. var animation = this.animation;
  4019. var abortedList = this._abortedCbs;
  4020. if (animation) {
  4021. animation.removeClip(this._clip);
  4022. }
  4023. this._clip = null;
  4024. if (abortedList) {
  4025. for (var i = 0; i < abortedList.length; i++) {
  4026. abortedList[i].call(this);
  4027. }
  4028. }
  4029. };
  4030. Animator.prototype._setTracksFinished = function () {
  4031. var tracks = this._tracks;
  4032. var tracksKeys = this._trackKeys;
  4033. for (var i = 0; i < tracksKeys.length; i++) {
  4034. tracks[tracksKeys[i]].setFinished();
  4035. }
  4036. };
  4037. Animator.prototype._getAdditiveTrack = function (trackName) {
  4038. var additiveTrack;
  4039. var additiveAnimators = this._additiveAnimators;
  4040. if (additiveAnimators) {
  4041. for (var i = 0; i < additiveAnimators.length; i++) {
  4042. var track = additiveAnimators[i].getTrack(trackName);
  4043. if (track) {
  4044. additiveTrack = track;
  4045. }
  4046. }
  4047. }
  4048. return additiveTrack;
  4049. };
  4050. Animator.prototype.start = function (easing) {
  4051. if (this._started > 0) {
  4052. return;
  4053. }
  4054. this._started = 1;
  4055. var self = this;
  4056. var tracks = [];
  4057. var maxTime = this._maxTime || 0;
  4058. for (var i = 0; i < this._trackKeys.length; i++) {
  4059. var propName = this._trackKeys[i];
  4060. var track = this._tracks[propName];
  4061. var additiveTrack = this._getAdditiveTrack(propName);
  4062. var kfs = track.keyframes;
  4063. var kfsNum = kfs.length;
  4064. track.prepare(maxTime, additiveTrack);
  4065. if (track.needsAnimate()) {
  4066. if (!this._allowDiscrete && track.discrete) {
  4067. var lastKf = kfs[kfsNum - 1];
  4068. if (lastKf) {
  4069. self._target[track.propName] = lastKf.rawValue;
  4070. }
  4071. track.setFinished();
  4072. }
  4073. else {
  4074. tracks.push(track);
  4075. }
  4076. }
  4077. }
  4078. if (tracks.length || this._force) {
  4079. var clip = new Clip({
  4080. life: maxTime,
  4081. loop: this._loop,
  4082. delay: this._delay || 0,
  4083. onframe: function (percent) {
  4084. self._started = 2;
  4085. var additiveAnimators = self._additiveAnimators;
  4086. if (additiveAnimators) {
  4087. var stillHasAdditiveAnimator = false;
  4088. for (var i = 0; i < additiveAnimators.length; i++) {
  4089. if (additiveAnimators[i]._clip) {
  4090. stillHasAdditiveAnimator = true;
  4091. break;
  4092. }
  4093. }
  4094. if (!stillHasAdditiveAnimator) {
  4095. self._additiveAnimators = null;
  4096. }
  4097. }
  4098. for (var i = 0; i < tracks.length; i++) {
  4099. tracks[i].step(self._target, percent);
  4100. }
  4101. var onframeList = self._onframeCbs;
  4102. if (onframeList) {
  4103. for (var i = 0; i < onframeList.length; i++) {
  4104. onframeList[i](self._target, percent);
  4105. }
  4106. }
  4107. },
  4108. ondestroy: function () {
  4109. self._doneCallback();
  4110. }
  4111. });
  4112. this._clip = clip;
  4113. if (this.animation) {
  4114. this.animation.addClip(clip);
  4115. }
  4116. if (easing) {
  4117. clip.setEasing(easing);
  4118. }
  4119. }
  4120. else {
  4121. this._doneCallback();
  4122. }
  4123. return this;
  4124. };
  4125. Animator.prototype.stop = function (forwardToLast) {
  4126. if (!this._clip) {
  4127. return;
  4128. }
  4129. var clip = this._clip;
  4130. if (forwardToLast) {
  4131. clip.onframe(1);
  4132. }
  4133. this._abortedCallback();
  4134. };
  4135. Animator.prototype.delay = function (time) {
  4136. this._delay = time;
  4137. return this;
  4138. };
  4139. Animator.prototype.during = function (cb) {
  4140. if (cb) {
  4141. if (!this._onframeCbs) {
  4142. this._onframeCbs = [];
  4143. }
  4144. this._onframeCbs.push(cb);
  4145. }
  4146. return this;
  4147. };
  4148. Animator.prototype.done = function (cb) {
  4149. if (cb) {
  4150. if (!this._doneCbs) {
  4151. this._doneCbs = [];
  4152. }
  4153. this._doneCbs.push(cb);
  4154. }
  4155. return this;
  4156. };
  4157. Animator.prototype.aborted = function (cb) {
  4158. if (cb) {
  4159. if (!this._abortedCbs) {
  4160. this._abortedCbs = [];
  4161. }
  4162. this._abortedCbs.push(cb);
  4163. }
  4164. return this;
  4165. };
  4166. Animator.prototype.getClip = function () {
  4167. return this._clip;
  4168. };
  4169. Animator.prototype.getTrack = function (propName) {
  4170. return this._tracks[propName];
  4171. };
  4172. Animator.prototype.getTracks = function () {
  4173. var _this = this;
  4174. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4175. };
  4176. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4177. if (!propNames.length || !this._clip) {
  4178. return true;
  4179. }
  4180. var tracks = this._tracks;
  4181. var tracksKeys = this._trackKeys;
  4182. for (var i = 0; i < propNames.length; i++) {
  4183. var track = tracks[propNames[i]];
  4184. if (track && !track.isFinished()) {
  4185. if (forwardToLast) {
  4186. track.step(this._target, 1);
  4187. }
  4188. else if (this._started === 1) {
  4189. track.step(this._target, 0);
  4190. }
  4191. track.setFinished();
  4192. }
  4193. }
  4194. var allAborted = true;
  4195. for (var i = 0; i < tracksKeys.length; i++) {
  4196. if (!tracks[tracksKeys[i]].isFinished()) {
  4197. allAborted = false;
  4198. break;
  4199. }
  4200. }
  4201. if (allAborted) {
  4202. this._abortedCallback();
  4203. }
  4204. return allAborted;
  4205. };
  4206. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4207. if (!target) {
  4208. return;
  4209. }
  4210. trackKeys = trackKeys || this._trackKeys;
  4211. for (var i = 0; i < trackKeys.length; i++) {
  4212. var propName = trackKeys[i];
  4213. var track = this._tracks[propName];
  4214. if (!track || track.isFinished()) {
  4215. continue;
  4216. }
  4217. var kfs = track.keyframes;
  4218. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4219. if (kf) {
  4220. target[propName] = cloneValue(kf.rawValue);
  4221. }
  4222. }
  4223. };
  4224. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4225. trackKeys = trackKeys || keys(finalProps);
  4226. for (var i = 0; i < trackKeys.length; i++) {
  4227. var propName = trackKeys[i];
  4228. var track = this._tracks[propName];
  4229. if (!track) {
  4230. continue;
  4231. }
  4232. var kfs = track.keyframes;
  4233. if (kfs.length > 1) {
  4234. var lastKf = kfs.pop();
  4235. track.addKeyframe(lastKf.time, finalProps[propName]);
  4236. track.prepare(this._maxTime, track.getAdditiveTrack());
  4237. }
  4238. }
  4239. };
  4240. return Animator;
  4241. }());
  4242. function getTime() {
  4243. return new Date().getTime();
  4244. }
  4245. var Animation = (function (_super) {
  4246. __extends(Animation, _super);
  4247. function Animation(opts) {
  4248. var _this = _super.call(this) || this;
  4249. _this._running = false;
  4250. _this._time = 0;
  4251. _this._pausedTime = 0;
  4252. _this._pauseStart = 0;
  4253. _this._paused = false;
  4254. opts = opts || {};
  4255. _this.stage = opts.stage || {};
  4256. return _this;
  4257. }
  4258. Animation.prototype.addClip = function (clip) {
  4259. if (clip.animation) {
  4260. this.removeClip(clip);
  4261. }
  4262. if (!this._head) {
  4263. this._head = this._tail = clip;
  4264. }
  4265. else {
  4266. this._tail.next = clip;
  4267. clip.prev = this._tail;
  4268. clip.next = null;
  4269. this._tail = clip;
  4270. }
  4271. clip.animation = this;
  4272. };
  4273. Animation.prototype.addAnimator = function (animator) {
  4274. animator.animation = this;
  4275. var clip = animator.getClip();
  4276. if (clip) {
  4277. this.addClip(clip);
  4278. }
  4279. };
  4280. Animation.prototype.removeClip = function (clip) {
  4281. if (!clip.animation) {
  4282. return;
  4283. }
  4284. var prev = clip.prev;
  4285. var next = clip.next;
  4286. if (prev) {
  4287. prev.next = next;
  4288. }
  4289. else {
  4290. this._head = next;
  4291. }
  4292. if (next) {
  4293. next.prev = prev;
  4294. }
  4295. else {
  4296. this._tail = prev;
  4297. }
  4298. clip.next = clip.prev = clip.animation = null;
  4299. };
  4300. Animation.prototype.removeAnimator = function (animator) {
  4301. var clip = animator.getClip();
  4302. if (clip) {
  4303. this.removeClip(clip);
  4304. }
  4305. animator.animation = null;
  4306. };
  4307. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  4308. var time = getTime() - this._pausedTime;
  4309. var delta = time - this._time;
  4310. var clip = this._head;
  4311. while (clip) {
  4312. var nextClip = clip.next;
  4313. var finished = clip.step(time, delta);
  4314. if (finished) {
  4315. clip.ondestroy();
  4316. this.removeClip(clip);
  4317. clip = nextClip;
  4318. }
  4319. else {
  4320. clip = nextClip;
  4321. }
  4322. }
  4323. this._time = time;
  4324. if (!notTriggerFrameAndStageUpdate) {
  4325. this.trigger('frame', delta);
  4326. this.stage.update && this.stage.update();
  4327. }
  4328. };
  4329. Animation.prototype._startLoop = function () {
  4330. var self = this;
  4331. this._running = true;
  4332. function step() {
  4333. if (self._running) {
  4334. requestAnimationFrame$1(step);
  4335. !self._paused && self.update();
  4336. }
  4337. }
  4338. requestAnimationFrame$1(step);
  4339. };
  4340. Animation.prototype.start = function () {
  4341. if (this._running) {
  4342. return;
  4343. }
  4344. this._time = getTime();
  4345. this._pausedTime = 0;
  4346. this._startLoop();
  4347. };
  4348. Animation.prototype.stop = function () {
  4349. this._running = false;
  4350. };
  4351. Animation.prototype.pause = function () {
  4352. if (!this._paused) {
  4353. this._pauseStart = getTime();
  4354. this._paused = true;
  4355. }
  4356. };
  4357. Animation.prototype.resume = function () {
  4358. if (this._paused) {
  4359. this._pausedTime += getTime() - this._pauseStart;
  4360. this._paused = false;
  4361. }
  4362. };
  4363. Animation.prototype.clear = function () {
  4364. var clip = this._head;
  4365. while (clip) {
  4366. var nextClip = clip.next;
  4367. clip.prev = clip.next = clip.animation = null;
  4368. clip = nextClip;
  4369. }
  4370. this._head = this._tail = null;
  4371. };
  4372. Animation.prototype.isFinished = function () {
  4373. return this._head == null;
  4374. };
  4375. Animation.prototype.animate = function (target, options) {
  4376. options = options || {};
  4377. this.start();
  4378. var animator = new Animator(target, options.loop);
  4379. this.addAnimator(animator);
  4380. return animator;
  4381. };
  4382. return Animation;
  4383. }(Eventful));
  4384. var TOUCH_CLICK_DELAY = 300;
  4385. var globalEventSupported = env.domSupported;
  4386. var localNativeListenerNames = (function () {
  4387. var mouseHandlerNames = [
  4388. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  4389. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  4390. ];
  4391. var touchHandlerNames = [
  4392. 'touchstart', 'touchend', 'touchmove'
  4393. ];
  4394. var pointerEventNameMap = {
  4395. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  4396. };
  4397. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  4398. var nm = name.replace('mouse', 'pointer');
  4399. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  4400. });
  4401. return {
  4402. mouse: mouseHandlerNames,
  4403. touch: touchHandlerNames,
  4404. pointer: pointerHandlerNames
  4405. };
  4406. })();
  4407. var globalNativeListenerNames = {
  4408. mouse: ['mousemove', 'mouseup'],
  4409. pointer: ['pointermove', 'pointerup']
  4410. };
  4411. var wheelEventSupported = false;
  4412. function isPointerFromTouch(event) {
  4413. var pointerType = event.pointerType;
  4414. return pointerType === 'pen' || pointerType === 'touch';
  4415. }
  4416. function setTouchTimer(scope) {
  4417. scope.touching = true;
  4418. if (scope.touchTimer != null) {
  4419. clearTimeout(scope.touchTimer);
  4420. scope.touchTimer = null;
  4421. }
  4422. scope.touchTimer = setTimeout(function () {
  4423. scope.touching = false;
  4424. scope.touchTimer = null;
  4425. }, 700);
  4426. }
  4427. function markTouch(event) {
  4428. event && (event.zrByTouch = true);
  4429. }
  4430. function normalizeGlobalEvent(instance, event) {
  4431. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  4432. }
  4433. function isLocalEl(instance, el) {
  4434. var elTmp = el;
  4435. var isLocal = false;
  4436. while (elTmp && elTmp.nodeType !== 9
  4437. && !(isLocal = elTmp.domBelongToZr
  4438. || (elTmp !== el && elTmp === instance.painterRoot))) {
  4439. elTmp = elTmp.parentNode;
  4440. }
  4441. return isLocal;
  4442. }
  4443. var FakeGlobalEvent = (function () {
  4444. function FakeGlobalEvent(instance, event) {
  4445. this.stopPropagation = noop;
  4446. this.stopImmediatePropagation = noop;
  4447. this.preventDefault = noop;
  4448. this.type = event.type;
  4449. this.target = this.currentTarget = instance.dom;
  4450. this.pointerType = event.pointerType;
  4451. this.clientX = event.clientX;
  4452. this.clientY = event.clientY;
  4453. }
  4454. return FakeGlobalEvent;
  4455. }());
  4456. var localDOMHandlers = {
  4457. mousedown: function (event) {
  4458. event = normalizeEvent(this.dom, event);
  4459. this.__mayPointerCapture = [event.zrX, event.zrY];
  4460. this.trigger('mousedown', event);
  4461. },
  4462. mousemove: function (event) {
  4463. event = normalizeEvent(this.dom, event);
  4464. var downPoint = this.__mayPointerCapture;
  4465. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  4466. this.__togglePointerCapture(true);
  4467. }
  4468. this.trigger('mousemove', event);
  4469. },
  4470. mouseup: function (event) {
  4471. event = normalizeEvent(this.dom, event);
  4472. this.__togglePointerCapture(false);
  4473. this.trigger('mouseup', event);
  4474. },
  4475. mouseout: function (event) {
  4476. event = normalizeEvent(this.dom, event);
  4477. var element = event.toElement || event.relatedTarget;
  4478. if (!isLocalEl(this, element)) {
  4479. if (this.__pointerCapturing) {
  4480. event.zrEventControl = 'no_globalout';
  4481. }
  4482. this.trigger('mouseout', event);
  4483. }
  4484. },
  4485. wheel: function (event) {
  4486. wheelEventSupported = true;
  4487. event = normalizeEvent(this.dom, event);
  4488. this.trigger('mousewheel', event);
  4489. },
  4490. mousewheel: function (event) {
  4491. if (wheelEventSupported) {
  4492. return;
  4493. }
  4494. event = normalizeEvent(this.dom, event);
  4495. this.trigger('mousewheel', event);
  4496. },
  4497. touchstart: function (event) {
  4498. event = normalizeEvent(this.dom, event);
  4499. markTouch(event);
  4500. this.__lastTouchMoment = new Date();
  4501. this.handler.processGesture(event, 'start');
  4502. localDOMHandlers.mousemove.call(this, event);
  4503. localDOMHandlers.mousedown.call(this, event);
  4504. },
  4505. touchmove: function (event) {
  4506. event = normalizeEvent(this.dom, event);
  4507. markTouch(event);
  4508. this.handler.processGesture(event, 'change');
  4509. localDOMHandlers.mousemove.call(this, event);
  4510. },
  4511. touchend: function (event) {
  4512. event = normalizeEvent(this.dom, event);
  4513. markTouch(event);
  4514. this.handler.processGesture(event, 'end');
  4515. localDOMHandlers.mouseup.call(this, event);
  4516. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  4517. localDOMHandlers.click.call(this, event);
  4518. }
  4519. },
  4520. pointerdown: function (event) {
  4521. localDOMHandlers.mousedown.call(this, event);
  4522. },
  4523. pointermove: function (event) {
  4524. if (!isPointerFromTouch(event)) {
  4525. localDOMHandlers.mousemove.call(this, event);
  4526. }
  4527. },
  4528. pointerup: function (event) {
  4529. localDOMHandlers.mouseup.call(this, event);
  4530. },
  4531. pointerout: function (event) {
  4532. if (!isPointerFromTouch(event)) {
  4533. localDOMHandlers.mouseout.call(this, event);
  4534. }
  4535. }
  4536. };
  4537. each(['click', 'dblclick', 'contextmenu'], function (name) {
  4538. localDOMHandlers[name] = function (event) {
  4539. event = normalizeEvent(this.dom, event);
  4540. this.trigger(name, event);
  4541. };
  4542. });
  4543. var globalDOMHandlers = {
  4544. pointermove: function (event) {
  4545. if (!isPointerFromTouch(event)) {
  4546. globalDOMHandlers.mousemove.call(this, event);
  4547. }
  4548. },
  4549. pointerup: function (event) {
  4550. globalDOMHandlers.mouseup.call(this, event);
  4551. },
  4552. mousemove: function (event) {
  4553. this.trigger('mousemove', event);
  4554. },
  4555. mouseup: function (event) {
  4556. var pointerCaptureReleasing = this.__pointerCapturing;
  4557. this.__togglePointerCapture(false);
  4558. this.trigger('mouseup', event);
  4559. if (pointerCaptureReleasing) {
  4560. event.zrEventControl = 'only_globalout';
  4561. this.trigger('mouseout', event);
  4562. }
  4563. }
  4564. };
  4565. function mountLocalDOMEventListeners(instance, scope) {
  4566. var domHandlers = scope.domHandlers;
  4567. if (env.pointerEventsSupported) {
  4568. each(localNativeListenerNames.pointer, function (nativeEventName) {
  4569. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4570. domHandlers[nativeEventName].call(instance, event);
  4571. });
  4572. });
  4573. }
  4574. else {
  4575. if (env.touchEventsSupported) {
  4576. each(localNativeListenerNames.touch, function (nativeEventName) {
  4577. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4578. domHandlers[nativeEventName].call(instance, event);
  4579. setTouchTimer(scope);
  4580. });
  4581. });
  4582. }
  4583. each(localNativeListenerNames.mouse, function (nativeEventName) {
  4584. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4585. event = getNativeEvent(event);
  4586. if (!scope.touching) {
  4587. domHandlers[nativeEventName].call(instance, event);
  4588. }
  4589. });
  4590. });
  4591. }
  4592. }
  4593. function mountGlobalDOMEventListeners(instance, scope) {
  4594. if (env.pointerEventsSupported) {
  4595. each(globalNativeListenerNames.pointer, mount);
  4596. }
  4597. else if (!env.touchEventsSupported) {
  4598. each(globalNativeListenerNames.mouse, mount);
  4599. }
  4600. function mount(nativeEventName) {
  4601. function nativeEventListener(event) {
  4602. event = getNativeEvent(event);
  4603. if (!isLocalEl(instance, event.target)) {
  4604. event = normalizeGlobalEvent(instance, event);
  4605. scope.domHandlers[nativeEventName].call(instance, event);
  4606. }
  4607. }
  4608. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  4609. }
  4610. }
  4611. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  4612. scope.mounted[nativeEventName] = listener;
  4613. scope.listenerOpts[nativeEventName] = opt;
  4614. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  4615. }
  4616. function unmountDOMEventListeners(scope) {
  4617. var mounted = scope.mounted;
  4618. for (var nativeEventName in mounted) {
  4619. if (mounted.hasOwnProperty(nativeEventName)) {
  4620. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  4621. }
  4622. }
  4623. scope.mounted = {};
  4624. }
  4625. var DOMHandlerScope = (function () {
  4626. function DOMHandlerScope(domTarget, domHandlers) {
  4627. this.mounted = {};
  4628. this.listenerOpts = {};
  4629. this.touching = false;
  4630. this.domTarget = domTarget;
  4631. this.domHandlers = domHandlers;
  4632. }
  4633. return DOMHandlerScope;
  4634. }());
  4635. var HandlerDomProxy = (function (_super) {
  4636. __extends(HandlerDomProxy, _super);
  4637. function HandlerDomProxy(dom, painterRoot) {
  4638. var _this = _super.call(this) || this;
  4639. _this.__pointerCapturing = false;
  4640. _this.dom = dom;
  4641. _this.painterRoot = painterRoot;
  4642. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  4643. if (globalEventSupported) {
  4644. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  4645. }
  4646. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  4647. return _this;
  4648. }
  4649. HandlerDomProxy.prototype.dispose = function () {
  4650. unmountDOMEventListeners(this._localHandlerScope);
  4651. if (globalEventSupported) {
  4652. unmountDOMEventListeners(this._globalHandlerScope);
  4653. }
  4654. };
  4655. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  4656. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  4657. };
  4658. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  4659. this.__mayPointerCapture = null;
  4660. if (globalEventSupported
  4661. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  4662. this.__pointerCapturing = isPointerCapturing;
  4663. var globalHandlerScope = this._globalHandlerScope;
  4664. isPointerCapturing
  4665. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  4666. : unmountDOMEventListeners(globalHandlerScope);
  4667. }
  4668. };
  4669. return HandlerDomProxy;
  4670. }(Eventful));
  4671. var dpr = 1;
  4672. if (env.hasGlobalWindow) {
  4673. dpr = Math.max(window.devicePixelRatio
  4674. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  4675. || 1, 1);
  4676. }
  4677. var devicePixelRatio = dpr;
  4678. var DARK_MODE_THRESHOLD = 0.4;
  4679. var DARK_LABEL_COLOR = '#333';
  4680. var LIGHT_LABEL_COLOR = '#ccc';
  4681. var LIGHTER_LABEL_COLOR = '#eee';
  4682. function create$1() {
  4683. return [1, 0, 0, 1, 0, 0];
  4684. }
  4685. function identity(out) {
  4686. out[0] = 1;
  4687. out[1] = 0;
  4688. out[2] = 0;
  4689. out[3] = 1;
  4690. out[4] = 0;
  4691. out[5] = 0;
  4692. return out;
  4693. }
  4694. function copy$1(out, m) {
  4695. out[0] = m[0];
  4696. out[1] = m[1];
  4697. out[2] = m[2];
  4698. out[3] = m[3];
  4699. out[4] = m[4];
  4700. out[5] = m[5];
  4701. return out;
  4702. }
  4703. function mul$1(out, m1, m2) {
  4704. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  4705. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  4706. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  4707. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  4708. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  4709. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  4710. out[0] = out0;
  4711. out[1] = out1;
  4712. out[2] = out2;
  4713. out[3] = out3;
  4714. out[4] = out4;
  4715. out[5] = out5;
  4716. return out;
  4717. }
  4718. function translate(out, a, v) {
  4719. out[0] = a[0];
  4720. out[1] = a[1];
  4721. out[2] = a[2];
  4722. out[3] = a[3];
  4723. out[4] = a[4] + v[0];
  4724. out[5] = a[5] + v[1];
  4725. return out;
  4726. }
  4727. function rotate(out, a, rad) {
  4728. var aa = a[0];
  4729. var ac = a[2];
  4730. var atx = a[4];
  4731. var ab = a[1];
  4732. var ad = a[3];
  4733. var aty = a[5];
  4734. var st = Math.sin(rad);
  4735. var ct = Math.cos(rad);
  4736. out[0] = aa * ct + ab * st;
  4737. out[1] = -aa * st + ab * ct;
  4738. out[2] = ac * ct + ad * st;
  4739. out[3] = -ac * st + ct * ad;
  4740. out[4] = ct * atx + st * aty;
  4741. out[5] = ct * aty - st * atx;
  4742. return out;
  4743. }
  4744. function scale$1(out, a, v) {
  4745. var vx = v[0];
  4746. var vy = v[1];
  4747. out[0] = a[0] * vx;
  4748. out[1] = a[1] * vy;
  4749. out[2] = a[2] * vx;
  4750. out[3] = a[3] * vy;
  4751. out[4] = a[4] * vx;
  4752. out[5] = a[5] * vy;
  4753. return out;
  4754. }
  4755. function invert(out, a) {
  4756. var aa = a[0];
  4757. var ac = a[2];
  4758. var atx = a[4];
  4759. var ab = a[1];
  4760. var ad = a[3];
  4761. var aty = a[5];
  4762. var det = aa * ad - ab * ac;
  4763. if (!det) {
  4764. return null;
  4765. }
  4766. det = 1.0 / det;
  4767. out[0] = ad * det;
  4768. out[1] = -ab * det;
  4769. out[2] = -ac * det;
  4770. out[3] = aa * det;
  4771. out[4] = (ac * aty - ad * atx) * det;
  4772. out[5] = (ab * atx - aa * aty) * det;
  4773. return out;
  4774. }
  4775. function clone$2(a) {
  4776. var b = create$1();
  4777. copy$1(b, a);
  4778. return b;
  4779. }
  4780. var matrix = /*#__PURE__*/Object.freeze({
  4781. __proto__: null,
  4782. create: create$1,
  4783. identity: identity,
  4784. copy: copy$1,
  4785. mul: mul$1,
  4786. translate: translate,
  4787. rotate: rotate,
  4788. scale: scale$1,
  4789. invert: invert,
  4790. clone: clone$2
  4791. });
  4792. var mIdentity = identity;
  4793. var EPSILON$1 = 5e-5;
  4794. function isNotAroundZero$1(val) {
  4795. return val > EPSILON$1 || val < -EPSILON$1;
  4796. }
  4797. var scaleTmp = [];
  4798. var tmpTransform = [];
  4799. var originTransform = create$1();
  4800. var abs = Math.abs;
  4801. var Transformable = (function () {
  4802. function Transformable() {
  4803. }
  4804. Transformable.prototype.getLocalTransform = function (m) {
  4805. return Transformable.getLocalTransform(this, m);
  4806. };
  4807. Transformable.prototype.setPosition = function (arr) {
  4808. this.x = arr[0];
  4809. this.y = arr[1];
  4810. };
  4811. Transformable.prototype.setScale = function (arr) {
  4812. this.scaleX = arr[0];
  4813. this.scaleY = arr[1];
  4814. };
  4815. Transformable.prototype.setSkew = function (arr) {
  4816. this.skewX = arr[0];
  4817. this.skewY = arr[1];
  4818. };
  4819. Transformable.prototype.setOrigin = function (arr) {
  4820. this.originX = arr[0];
  4821. this.originY = arr[1];
  4822. };
  4823. Transformable.prototype.needLocalTransform = function () {
  4824. return isNotAroundZero$1(this.rotation)
  4825. || isNotAroundZero$1(this.x)
  4826. || isNotAroundZero$1(this.y)
  4827. || isNotAroundZero$1(this.scaleX - 1)
  4828. || isNotAroundZero$1(this.scaleY - 1)
  4829. || isNotAroundZero$1(this.skewX)
  4830. || isNotAroundZero$1(this.skewY);
  4831. };
  4832. Transformable.prototype.updateTransform = function () {
  4833. var parentTransform = this.parent && this.parent.transform;
  4834. var needLocalTransform = this.needLocalTransform();
  4835. var m = this.transform;
  4836. if (!(needLocalTransform || parentTransform)) {
  4837. m && mIdentity(m);
  4838. return;
  4839. }
  4840. m = m || create$1();
  4841. if (needLocalTransform) {
  4842. this.getLocalTransform(m);
  4843. }
  4844. else {
  4845. mIdentity(m);
  4846. }
  4847. if (parentTransform) {
  4848. if (needLocalTransform) {
  4849. mul$1(m, parentTransform, m);
  4850. }
  4851. else {
  4852. copy$1(m, parentTransform);
  4853. }
  4854. }
  4855. this.transform = m;
  4856. this._resolveGlobalScaleRatio(m);
  4857. };
  4858. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  4859. var globalScaleRatio = this.globalScaleRatio;
  4860. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  4861. this.getGlobalScale(scaleTmp);
  4862. var relX = scaleTmp[0] < 0 ? -1 : 1;
  4863. var relY = scaleTmp[1] < 0 ? -1 : 1;
  4864. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  4865. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  4866. m[0] *= sx;
  4867. m[1] *= sx;
  4868. m[2] *= sy;
  4869. m[3] *= sy;
  4870. }
  4871. this.invTransform = this.invTransform || create$1();
  4872. invert(this.invTransform, m);
  4873. };
  4874. Transformable.prototype.getComputedTransform = function () {
  4875. var transformNode = this;
  4876. var ancestors = [];
  4877. while (transformNode) {
  4878. ancestors.push(transformNode);
  4879. transformNode = transformNode.parent;
  4880. }
  4881. while (transformNode = ancestors.pop()) {
  4882. transformNode.updateTransform();
  4883. }
  4884. return this.transform;
  4885. };
  4886. Transformable.prototype.setLocalTransform = function (m) {
  4887. if (!m) {
  4888. return;
  4889. }
  4890. var sx = m[0] * m[0] + m[1] * m[1];
  4891. var sy = m[2] * m[2] + m[3] * m[3];
  4892. var rotation = Math.atan2(m[1], m[0]);
  4893. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  4894. sy = Math.sqrt(sy) * Math.cos(shearX);
  4895. sx = Math.sqrt(sx);
  4896. this.skewX = shearX;
  4897. this.skewY = 0;
  4898. this.rotation = -rotation;
  4899. this.x = +m[4];
  4900. this.y = +m[5];
  4901. this.scaleX = sx;
  4902. this.scaleY = sy;
  4903. this.originX = 0;
  4904. this.originY = 0;
  4905. };
  4906. Transformable.prototype.decomposeTransform = function () {
  4907. if (!this.transform) {
  4908. return;
  4909. }
  4910. var parent = this.parent;
  4911. var m = this.transform;
  4912. if (parent && parent.transform) {
  4913. mul$1(tmpTransform, parent.invTransform, m);
  4914. m = tmpTransform;
  4915. }
  4916. var ox = this.originX;
  4917. var oy = this.originY;
  4918. if (ox || oy) {
  4919. originTransform[4] = ox;
  4920. originTransform[5] = oy;
  4921. mul$1(tmpTransform, m, originTransform);
  4922. tmpTransform[4] -= ox;
  4923. tmpTransform[5] -= oy;
  4924. m = tmpTransform;
  4925. }
  4926. this.setLocalTransform(m);
  4927. };
  4928. Transformable.prototype.getGlobalScale = function (out) {
  4929. var m = this.transform;
  4930. out = out || [];
  4931. if (!m) {
  4932. out[0] = 1;
  4933. out[1] = 1;
  4934. return out;
  4935. }
  4936. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  4937. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  4938. if (m[0] < 0) {
  4939. out[0] = -out[0];
  4940. }
  4941. if (m[3] < 0) {
  4942. out[1] = -out[1];
  4943. }
  4944. return out;
  4945. };
  4946. Transformable.prototype.transformCoordToLocal = function (x, y) {
  4947. var v2 = [x, y];
  4948. var invTransform = this.invTransform;
  4949. if (invTransform) {
  4950. applyTransform(v2, v2, invTransform);
  4951. }
  4952. return v2;
  4953. };
  4954. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  4955. var v2 = [x, y];
  4956. var transform = this.transform;
  4957. if (transform) {
  4958. applyTransform(v2, v2, transform);
  4959. }
  4960. return v2;
  4961. };
  4962. Transformable.prototype.getLineScale = function () {
  4963. var m = this.transform;
  4964. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  4965. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  4966. : 1;
  4967. };
  4968. Transformable.prototype.copyTransform = function (source) {
  4969. copyTransform(this, source);
  4970. };
  4971. Transformable.getLocalTransform = function (target, m) {
  4972. m = m || [];
  4973. var ox = target.originX || 0;
  4974. var oy = target.originY || 0;
  4975. var sx = target.scaleX;
  4976. var sy = target.scaleY;
  4977. var ax = target.anchorX;
  4978. var ay = target.anchorY;
  4979. var rotation = target.rotation || 0;
  4980. var x = target.x;
  4981. var y = target.y;
  4982. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  4983. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  4984. if (ox || oy || ax || ay) {
  4985. var dx = ox + ax;
  4986. var dy = oy + ay;
  4987. m[4] = -dx * sx - skewX * dy * sy;
  4988. m[5] = -dy * sy - skewY * dx * sx;
  4989. }
  4990. else {
  4991. m[4] = m[5] = 0;
  4992. }
  4993. m[0] = sx;
  4994. m[3] = sy;
  4995. m[1] = skewY * sx;
  4996. m[2] = skewX * sy;
  4997. rotation && rotate(m, m, rotation);
  4998. m[4] += ox + x;
  4999. m[5] += oy + y;
  5000. return m;
  5001. };
  5002. Transformable.initDefaultProps = (function () {
  5003. var proto = Transformable.prototype;
  5004. proto.scaleX =
  5005. proto.scaleY =
  5006. proto.globalScaleRatio = 1;
  5007. proto.x =
  5008. proto.y =
  5009. proto.originX =
  5010. proto.originY =
  5011. proto.skewX =
  5012. proto.skewY =
  5013. proto.rotation =
  5014. proto.anchorX =
  5015. proto.anchorY = 0;
  5016. })();
  5017. return Transformable;
  5018. }());
  5019. var TRANSFORMABLE_PROPS = [
  5020. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5021. ];
  5022. function copyTransform(target, source) {
  5023. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5024. var propName = TRANSFORMABLE_PROPS[i];
  5025. target[propName] = source[propName];
  5026. }
  5027. }
  5028. var Point = (function () {
  5029. function Point(x, y) {
  5030. this.x = x || 0;
  5031. this.y = y || 0;
  5032. }
  5033. Point.prototype.copy = function (other) {
  5034. this.x = other.x;
  5035. this.y = other.y;
  5036. return this;
  5037. };
  5038. Point.prototype.clone = function () {
  5039. return new Point(this.x, this.y);
  5040. };
  5041. Point.prototype.set = function (x, y) {
  5042. this.x = x;
  5043. this.y = y;
  5044. return this;
  5045. };
  5046. Point.prototype.equal = function (other) {
  5047. return other.x === this.x && other.y === this.y;
  5048. };
  5049. Point.prototype.add = function (other) {
  5050. this.x += other.x;
  5051. this.y += other.y;
  5052. return this;
  5053. };
  5054. Point.prototype.scale = function (scalar) {
  5055. this.x *= scalar;
  5056. this.y *= scalar;
  5057. };
  5058. Point.prototype.scaleAndAdd = function (other, scalar) {
  5059. this.x += other.x * scalar;
  5060. this.y += other.y * scalar;
  5061. };
  5062. Point.prototype.sub = function (other) {
  5063. this.x -= other.x;
  5064. this.y -= other.y;
  5065. return this;
  5066. };
  5067. Point.prototype.dot = function (other) {
  5068. return this.x * other.x + this.y * other.y;
  5069. };
  5070. Point.prototype.len = function () {
  5071. return Math.sqrt(this.x * this.x + this.y * this.y);
  5072. };
  5073. Point.prototype.lenSquare = function () {
  5074. return this.x * this.x + this.y * this.y;
  5075. };
  5076. Point.prototype.normalize = function () {
  5077. var len = this.len();
  5078. this.x /= len;
  5079. this.y /= len;
  5080. return this;
  5081. };
  5082. Point.prototype.distance = function (other) {
  5083. var dx = this.x - other.x;
  5084. var dy = this.y - other.y;
  5085. return Math.sqrt(dx * dx + dy * dy);
  5086. };
  5087. Point.prototype.distanceSquare = function (other) {
  5088. var dx = this.x - other.x;
  5089. var dy = this.y - other.y;
  5090. return dx * dx + dy * dy;
  5091. };
  5092. Point.prototype.negate = function () {
  5093. this.x = -this.x;
  5094. this.y = -this.y;
  5095. return this;
  5096. };
  5097. Point.prototype.transform = function (m) {
  5098. if (!m) {
  5099. return;
  5100. }
  5101. var x = this.x;
  5102. var y = this.y;
  5103. this.x = m[0] * x + m[2] * y + m[4];
  5104. this.y = m[1] * x + m[3] * y + m[5];
  5105. return this;
  5106. };
  5107. Point.prototype.toArray = function (out) {
  5108. out[0] = this.x;
  5109. out[1] = this.y;
  5110. return out;
  5111. };
  5112. Point.prototype.fromArray = function (input) {
  5113. this.x = input[0];
  5114. this.y = input[1];
  5115. };
  5116. Point.set = function (p, x, y) {
  5117. p.x = x;
  5118. p.y = y;
  5119. };
  5120. Point.copy = function (p, p2) {
  5121. p.x = p2.x;
  5122. p.y = p2.y;
  5123. };
  5124. Point.len = function (p) {
  5125. return Math.sqrt(p.x * p.x + p.y * p.y);
  5126. };
  5127. Point.lenSquare = function (p) {
  5128. return p.x * p.x + p.y * p.y;
  5129. };
  5130. Point.dot = function (p0, p1) {
  5131. return p0.x * p1.x + p0.y * p1.y;
  5132. };
  5133. Point.add = function (out, p0, p1) {
  5134. out.x = p0.x + p1.x;
  5135. out.y = p0.y + p1.y;
  5136. };
  5137. Point.sub = function (out, p0, p1) {
  5138. out.x = p0.x - p1.x;
  5139. out.y = p0.y - p1.y;
  5140. };
  5141. Point.scale = function (out, p0, scalar) {
  5142. out.x = p0.x * scalar;
  5143. out.y = p0.y * scalar;
  5144. };
  5145. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  5146. out.x = p0.x + p1.x * scalar;
  5147. out.y = p0.y + p1.y * scalar;
  5148. };
  5149. Point.lerp = function (out, p0, p1, t) {
  5150. var onet = 1 - t;
  5151. out.x = onet * p0.x + t * p1.x;
  5152. out.y = onet * p0.y + t * p1.y;
  5153. };
  5154. return Point;
  5155. }());
  5156. var mathMin = Math.min;
  5157. var mathMax = Math.max;
  5158. var lt = new Point();
  5159. var rb = new Point();
  5160. var lb = new Point();
  5161. var rt = new Point();
  5162. var minTv = new Point();
  5163. var maxTv = new Point();
  5164. var BoundingRect = (function () {
  5165. function BoundingRect(x, y, width, height) {
  5166. if (width < 0) {
  5167. x = x + width;
  5168. width = -width;
  5169. }
  5170. if (height < 0) {
  5171. y = y + height;
  5172. height = -height;
  5173. }
  5174. this.x = x;
  5175. this.y = y;
  5176. this.width = width;
  5177. this.height = height;
  5178. }
  5179. BoundingRect.prototype.union = function (other) {
  5180. var x = mathMin(other.x, this.x);
  5181. var y = mathMin(other.y, this.y);
  5182. if (isFinite(this.x) && isFinite(this.width)) {
  5183. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  5184. }
  5185. else {
  5186. this.width = other.width;
  5187. }
  5188. if (isFinite(this.y) && isFinite(this.height)) {
  5189. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  5190. }
  5191. else {
  5192. this.height = other.height;
  5193. }
  5194. this.x = x;
  5195. this.y = y;
  5196. };
  5197. BoundingRect.prototype.applyTransform = function (m) {
  5198. BoundingRect.applyTransform(this, this, m);
  5199. };
  5200. BoundingRect.prototype.calculateTransform = function (b) {
  5201. var a = this;
  5202. var sx = b.width / a.width;
  5203. var sy = b.height / a.height;
  5204. var m = create$1();
  5205. translate(m, m, [-a.x, -a.y]);
  5206. scale$1(m, m, [sx, sy]);
  5207. translate(m, m, [b.x, b.y]);
  5208. return m;
  5209. };
  5210. BoundingRect.prototype.intersect = function (b, mtv) {
  5211. if (!b) {
  5212. return false;
  5213. }
  5214. if (!(b instanceof BoundingRect)) {
  5215. b = BoundingRect.create(b);
  5216. }
  5217. var a = this;
  5218. var ax0 = a.x;
  5219. var ax1 = a.x + a.width;
  5220. var ay0 = a.y;
  5221. var ay1 = a.y + a.height;
  5222. var bx0 = b.x;
  5223. var bx1 = b.x + b.width;
  5224. var by0 = b.y;
  5225. var by1 = b.y + b.height;
  5226. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5227. if (mtv) {
  5228. var dMin = Infinity;
  5229. var dMax = 0;
  5230. var d0 = Math.abs(ax1 - bx0);
  5231. var d1 = Math.abs(bx1 - ax0);
  5232. var d2 = Math.abs(ay1 - by0);
  5233. var d3 = Math.abs(by1 - ay0);
  5234. var dx = Math.min(d0, d1);
  5235. var dy = Math.min(d2, d3);
  5236. if (ax1 < bx0 || bx1 < ax0) {
  5237. if (dx > dMax) {
  5238. dMax = dx;
  5239. if (d0 < d1) {
  5240. Point.set(maxTv, -d0, 0);
  5241. }
  5242. else {
  5243. Point.set(maxTv, d1, 0);
  5244. }
  5245. }
  5246. }
  5247. else {
  5248. if (dx < dMin) {
  5249. dMin = dx;
  5250. if (d0 < d1) {
  5251. Point.set(minTv, d0, 0);
  5252. }
  5253. else {
  5254. Point.set(minTv, -d1, 0);
  5255. }
  5256. }
  5257. }
  5258. if (ay1 < by0 || by1 < ay0) {
  5259. if (dy > dMax) {
  5260. dMax = dy;
  5261. if (d2 < d3) {
  5262. Point.set(maxTv, 0, -d2);
  5263. }
  5264. else {
  5265. Point.set(maxTv, 0, d3);
  5266. }
  5267. }
  5268. }
  5269. else {
  5270. if (dx < dMin) {
  5271. dMin = dx;
  5272. if (d2 < d3) {
  5273. Point.set(minTv, 0, d2);
  5274. }
  5275. else {
  5276. Point.set(minTv, 0, -d3);
  5277. }
  5278. }
  5279. }
  5280. }
  5281. if (mtv) {
  5282. Point.copy(mtv, overlap ? minTv : maxTv);
  5283. }
  5284. return overlap;
  5285. };
  5286. BoundingRect.prototype.contain = function (x, y) {
  5287. var rect = this;
  5288. return x >= rect.x
  5289. && x <= (rect.x + rect.width)
  5290. && y >= rect.y
  5291. && y <= (rect.y + rect.height);
  5292. };
  5293. BoundingRect.prototype.clone = function () {
  5294. return new BoundingRect(this.x, this.y, this.width, this.height);
  5295. };
  5296. BoundingRect.prototype.copy = function (other) {
  5297. BoundingRect.copy(this, other);
  5298. };
  5299. BoundingRect.prototype.plain = function () {
  5300. return {
  5301. x: this.x,
  5302. y: this.y,
  5303. width: this.width,
  5304. height: this.height
  5305. };
  5306. };
  5307. BoundingRect.prototype.isFinite = function () {
  5308. return isFinite(this.x)
  5309. && isFinite(this.y)
  5310. && isFinite(this.width)
  5311. && isFinite(this.height);
  5312. };
  5313. BoundingRect.prototype.isZero = function () {
  5314. return this.width === 0 || this.height === 0;
  5315. };
  5316. BoundingRect.create = function (rect) {
  5317. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5318. };
  5319. BoundingRect.copy = function (target, source) {
  5320. target.x = source.x;
  5321. target.y = source.y;
  5322. target.width = source.width;
  5323. target.height = source.height;
  5324. };
  5325. BoundingRect.applyTransform = function (target, source, m) {
  5326. if (!m) {
  5327. if (target !== source) {
  5328. BoundingRect.copy(target, source);
  5329. }
  5330. return;
  5331. }
  5332. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  5333. var sx = m[0];
  5334. var sy = m[3];
  5335. var tx = m[4];
  5336. var ty = m[5];
  5337. target.x = source.x * sx + tx;
  5338. target.y = source.y * sy + ty;
  5339. target.width = source.width * sx;
  5340. target.height = source.height * sy;
  5341. if (target.width < 0) {
  5342. target.x += target.width;
  5343. target.width = -target.width;
  5344. }
  5345. if (target.height < 0) {
  5346. target.y += target.height;
  5347. target.height = -target.height;
  5348. }
  5349. return;
  5350. }
  5351. lt.x = lb.x = source.x;
  5352. lt.y = rt.y = source.y;
  5353. rb.x = rt.x = source.x + source.width;
  5354. rb.y = lb.y = source.y + source.height;
  5355. lt.transform(m);
  5356. rt.transform(m);
  5357. rb.transform(m);
  5358. lb.transform(m);
  5359. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  5360. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  5361. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  5362. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  5363. target.width = maxX - target.x;
  5364. target.height = maxY - target.y;
  5365. };
  5366. return BoundingRect;
  5367. }());
  5368. var textWidthCache = {};
  5369. function getWidth(text, font) {
  5370. font = font || DEFAULT_FONT;
  5371. var cacheOfFont = textWidthCache[font];
  5372. if (!cacheOfFont) {
  5373. cacheOfFont = textWidthCache[font] = new LRU(500);
  5374. }
  5375. var width = cacheOfFont.get(text);
  5376. if (width == null) {
  5377. width = platformApi.measureText(text, font).width;
  5378. cacheOfFont.put(text, width);
  5379. }
  5380. return width;
  5381. }
  5382. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5383. var width = getWidth(text, font);
  5384. var height = getLineHeight(font);
  5385. var x = adjustTextX(0, width, textAlign);
  5386. var y = adjustTextY(0, height, textBaseline);
  5387. var rect = new BoundingRect(x, y, width, height);
  5388. return rect;
  5389. }
  5390. function getBoundingRect(text, font, textAlign, textBaseline) {
  5391. var textLines = ((text || '') + '').split('\n');
  5392. var len = textLines.length;
  5393. if (len === 1) {
  5394. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5395. }
  5396. else {
  5397. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5398. for (var i = 0; i < textLines.length; i++) {
  5399. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5400. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5401. }
  5402. return uniondRect;
  5403. }
  5404. }
  5405. function adjustTextX(x, width, textAlign) {
  5406. if (textAlign === 'right') {
  5407. x -= width;
  5408. }
  5409. else if (textAlign === 'center') {
  5410. x -= width / 2;
  5411. }
  5412. return x;
  5413. }
  5414. function adjustTextY(y, height, verticalAlign) {
  5415. if (verticalAlign === 'middle') {
  5416. y -= height / 2;
  5417. }
  5418. else if (verticalAlign === 'bottom') {
  5419. y -= height;
  5420. }
  5421. return y;
  5422. }
  5423. function getLineHeight(font) {
  5424. return getWidth('国', font);
  5425. }
  5426. function parsePercent(value, maxValue) {
  5427. if (typeof value === 'string') {
  5428. if (value.lastIndexOf('%') >= 0) {
  5429. return parseFloat(value) / 100 * maxValue;
  5430. }
  5431. return parseFloat(value);
  5432. }
  5433. return value;
  5434. }
  5435. function calculateTextPosition(out, opts, rect) {
  5436. var textPosition = opts.position || 'inside';
  5437. var distance = opts.distance != null ? opts.distance : 5;
  5438. var height = rect.height;
  5439. var width = rect.width;
  5440. var halfHeight = height / 2;
  5441. var x = rect.x;
  5442. var y = rect.y;
  5443. var textAlign = 'left';
  5444. var textVerticalAlign = 'top';
  5445. if (textPosition instanceof Array) {
  5446. x += parsePercent(textPosition[0], rect.width);
  5447. y += parsePercent(textPosition[1], rect.height);
  5448. textAlign = null;
  5449. textVerticalAlign = null;
  5450. }
  5451. else {
  5452. switch (textPosition) {
  5453. case 'left':
  5454. x -= distance;
  5455. y += halfHeight;
  5456. textAlign = 'right';
  5457. textVerticalAlign = 'middle';
  5458. break;
  5459. case 'right':
  5460. x += distance + width;
  5461. y += halfHeight;
  5462. textVerticalAlign = 'middle';
  5463. break;
  5464. case 'top':
  5465. x += width / 2;
  5466. y -= distance;
  5467. textAlign = 'center';
  5468. textVerticalAlign = 'bottom';
  5469. break;
  5470. case 'bottom':
  5471. x += width / 2;
  5472. y += height + distance;
  5473. textAlign = 'center';
  5474. break;
  5475. case 'inside':
  5476. x += width / 2;
  5477. y += halfHeight;
  5478. textAlign = 'center';
  5479. textVerticalAlign = 'middle';
  5480. break;
  5481. case 'insideLeft':
  5482. x += distance;
  5483. y += halfHeight;
  5484. textVerticalAlign = 'middle';
  5485. break;
  5486. case 'insideRight':
  5487. x += width - distance;
  5488. y += halfHeight;
  5489. textAlign = 'right';
  5490. textVerticalAlign = 'middle';
  5491. break;
  5492. case 'insideTop':
  5493. x += width / 2;
  5494. y += distance;
  5495. textAlign = 'center';
  5496. break;
  5497. case 'insideBottom':
  5498. x += width / 2;
  5499. y += height - distance;
  5500. textAlign = 'center';
  5501. textVerticalAlign = 'bottom';
  5502. break;
  5503. case 'insideTopLeft':
  5504. x += distance;
  5505. y += distance;
  5506. break;
  5507. case 'insideTopRight':
  5508. x += width - distance;
  5509. y += distance;
  5510. textAlign = 'right';
  5511. break;
  5512. case 'insideBottomLeft':
  5513. x += distance;
  5514. y += height - distance;
  5515. textVerticalAlign = 'bottom';
  5516. break;
  5517. case 'insideBottomRight':
  5518. x += width - distance;
  5519. y += height - distance;
  5520. textAlign = 'right';
  5521. textVerticalAlign = 'bottom';
  5522. break;
  5523. }
  5524. }
  5525. out = out || {};
  5526. out.x = x;
  5527. out.y = y;
  5528. out.align = textAlign;
  5529. out.verticalAlign = textVerticalAlign;
  5530. return out;
  5531. }
  5532. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5533. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5534. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5535. obj[key] = true;
  5536. return obj;
  5537. }, { ignore: false });
  5538. var tmpTextPosCalcRes = {};
  5539. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5540. var Element = (function () {
  5541. function Element(props) {
  5542. this.id = guid();
  5543. this.animators = [];
  5544. this.currentStates = [];
  5545. this.states = {};
  5546. this._init(props);
  5547. }
  5548. Element.prototype._init = function (props) {
  5549. this.attr(props);
  5550. };
  5551. Element.prototype.drift = function (dx, dy, e) {
  5552. switch (this.draggable) {
  5553. case 'horizontal':
  5554. dy = 0;
  5555. break;
  5556. case 'vertical':
  5557. dx = 0;
  5558. break;
  5559. }
  5560. var m = this.transform;
  5561. if (!m) {
  5562. m = this.transform = [1, 0, 0, 1, 0, 0];
  5563. }
  5564. m[4] += dx;
  5565. m[5] += dy;
  5566. this.decomposeTransform();
  5567. this.markRedraw();
  5568. };
  5569. Element.prototype.beforeUpdate = function () { };
  5570. Element.prototype.afterUpdate = function () { };
  5571. Element.prototype.update = function () {
  5572. this.updateTransform();
  5573. if (this.__dirty) {
  5574. this.updateInnerText();
  5575. }
  5576. };
  5577. Element.prototype.updateInnerText = function (forceUpdate) {
  5578. var textEl = this._textContent;
  5579. if (textEl && (!textEl.ignore || forceUpdate)) {
  5580. if (!this.textConfig) {
  5581. this.textConfig = {};
  5582. }
  5583. var textConfig = this.textConfig;
  5584. var isLocal = textConfig.local;
  5585. var innerTransformable = textEl.innerTransformable;
  5586. var textAlign = void 0;
  5587. var textVerticalAlign = void 0;
  5588. var textStyleChanged = false;
  5589. innerTransformable.parent = isLocal ? this : null;
  5590. var innerOrigin = false;
  5591. innerTransformable.copyTransform(textEl);
  5592. if (textConfig.position != null) {
  5593. var layoutRect = tmpBoundingRect;
  5594. if (textConfig.layoutRect) {
  5595. layoutRect.copy(textConfig.layoutRect);
  5596. }
  5597. else {
  5598. layoutRect.copy(this.getBoundingRect());
  5599. }
  5600. if (!isLocal) {
  5601. layoutRect.applyTransform(this.transform);
  5602. }
  5603. if (this.calculateTextPosition) {
  5604. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5605. }
  5606. else {
  5607. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5608. }
  5609. innerTransformable.x = tmpTextPosCalcRes.x;
  5610. innerTransformable.y = tmpTextPosCalcRes.y;
  5611. textAlign = tmpTextPosCalcRes.align;
  5612. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5613. var textOrigin = textConfig.origin;
  5614. if (textOrigin && textConfig.rotation != null) {
  5615. var relOriginX = void 0;
  5616. var relOriginY = void 0;
  5617. if (textOrigin === 'center') {
  5618. relOriginX = layoutRect.width * 0.5;
  5619. relOriginY = layoutRect.height * 0.5;
  5620. }
  5621. else {
  5622. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5623. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5624. }
  5625. innerOrigin = true;
  5626. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5627. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5628. }
  5629. }
  5630. if (textConfig.rotation != null) {
  5631. innerTransformable.rotation = textConfig.rotation;
  5632. }
  5633. var textOffset = textConfig.offset;
  5634. if (textOffset) {
  5635. innerTransformable.x += textOffset[0];
  5636. innerTransformable.y += textOffset[1];
  5637. if (!innerOrigin) {
  5638. innerTransformable.originX = -textOffset[0];
  5639. innerTransformable.originY = -textOffset[1];
  5640. }
  5641. }
  5642. var isInside = textConfig.inside == null
  5643. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5644. : textConfig.inside;
  5645. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5646. var textFill = void 0;
  5647. var textStroke = void 0;
  5648. var autoStroke = void 0;
  5649. if (isInside && this.canBeInsideText()) {
  5650. textFill = textConfig.insideFill;
  5651. textStroke = textConfig.insideStroke;
  5652. if (textFill == null || textFill === 'auto') {
  5653. textFill = this.getInsideTextFill();
  5654. }
  5655. if (textStroke == null || textStroke === 'auto') {
  5656. textStroke = this.getInsideTextStroke(textFill);
  5657. autoStroke = true;
  5658. }
  5659. }
  5660. else {
  5661. textFill = textConfig.outsideFill;
  5662. textStroke = textConfig.outsideStroke;
  5663. if (textFill == null || textFill === 'auto') {
  5664. textFill = this.getOutsideFill();
  5665. }
  5666. if (textStroke == null || textStroke === 'auto') {
  5667. textStroke = this.getOutsideStroke(textFill);
  5668. autoStroke = true;
  5669. }
  5670. }
  5671. textFill = textFill || '#000';
  5672. if (textFill !== innerTextDefaultStyle.fill
  5673. || textStroke !== innerTextDefaultStyle.stroke
  5674. || autoStroke !== innerTextDefaultStyle.autoStroke
  5675. || textAlign !== innerTextDefaultStyle.align
  5676. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5677. textStyleChanged = true;
  5678. innerTextDefaultStyle.fill = textFill;
  5679. innerTextDefaultStyle.stroke = textStroke;
  5680. innerTextDefaultStyle.autoStroke = autoStroke;
  5681. innerTextDefaultStyle.align = textAlign;
  5682. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5683. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5684. }
  5685. textEl.__dirty |= REDRAW_BIT;
  5686. if (textStyleChanged) {
  5687. textEl.dirtyStyle(true);
  5688. }
  5689. }
  5690. };
  5691. Element.prototype.canBeInsideText = function () {
  5692. return true;
  5693. };
  5694. Element.prototype.getInsideTextFill = function () {
  5695. return '#fff';
  5696. };
  5697. Element.prototype.getInsideTextStroke = function (textFill) {
  5698. return '#000';
  5699. };
  5700. Element.prototype.getOutsideFill = function () {
  5701. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5702. };
  5703. Element.prototype.getOutsideStroke = function (textFill) {
  5704. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5705. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5706. if (!colorArr) {
  5707. colorArr = [255, 255, 255, 1];
  5708. }
  5709. var alpha = colorArr[3];
  5710. var isDark = this.__zr.isDarkMode();
  5711. for (var i = 0; i < 3; i++) {
  5712. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5713. }
  5714. colorArr[3] = 1;
  5715. return stringify(colorArr, 'rgba');
  5716. };
  5717. Element.prototype.traverse = function (cb, context) { };
  5718. Element.prototype.attrKV = function (key, value) {
  5719. if (key === 'textConfig') {
  5720. this.setTextConfig(value);
  5721. }
  5722. else if (key === 'textContent') {
  5723. this.setTextContent(value);
  5724. }
  5725. else if (key === 'clipPath') {
  5726. this.setClipPath(value);
  5727. }
  5728. else if (key === 'extra') {
  5729. this.extra = this.extra || {};
  5730. extend(this.extra, value);
  5731. }
  5732. else {
  5733. this[key] = value;
  5734. }
  5735. };
  5736. Element.prototype.hide = function () {
  5737. this.ignore = true;
  5738. this.markRedraw();
  5739. };
  5740. Element.prototype.show = function () {
  5741. this.ignore = false;
  5742. this.markRedraw();
  5743. };
  5744. Element.prototype.attr = function (keyOrObj, value) {
  5745. if (typeof keyOrObj === 'string') {
  5746. this.attrKV(keyOrObj, value);
  5747. }
  5748. else if (isObject(keyOrObj)) {
  5749. var obj = keyOrObj;
  5750. var keysArr = keys(obj);
  5751. for (var i = 0; i < keysArr.length; i++) {
  5752. var key = keysArr[i];
  5753. this.attrKV(key, keyOrObj[key]);
  5754. }
  5755. }
  5756. this.markRedraw();
  5757. return this;
  5758. };
  5759. Element.prototype.saveCurrentToNormalState = function (toState) {
  5760. this._innerSaveToNormal(toState);
  5761. var normalState = this._normalState;
  5762. for (var i = 0; i < this.animators.length; i++) {
  5763. var animator = this.animators[i];
  5764. var fromStateTransition = animator.__fromStateTransition;
  5765. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  5766. continue;
  5767. }
  5768. var targetName = animator.targetName;
  5769. var target = targetName
  5770. ? normalState[targetName] : normalState;
  5771. animator.saveTo(target);
  5772. }
  5773. };
  5774. Element.prototype._innerSaveToNormal = function (toState) {
  5775. var normalState = this._normalState;
  5776. if (!normalState) {
  5777. normalState = this._normalState = {};
  5778. }
  5779. if (toState.textConfig && !normalState.textConfig) {
  5780. normalState.textConfig = this.textConfig;
  5781. }
  5782. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  5783. };
  5784. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  5785. for (var i = 0; i < primaryKeys.length; i++) {
  5786. var key = primaryKeys[i];
  5787. if (toState[key] != null && !(key in normalState)) {
  5788. normalState[key] = this[key];
  5789. }
  5790. }
  5791. };
  5792. Element.prototype.hasState = function () {
  5793. return this.currentStates.length > 0;
  5794. };
  5795. Element.prototype.getState = function (name) {
  5796. return this.states[name];
  5797. };
  5798. Element.prototype.ensureState = function (name) {
  5799. var states = this.states;
  5800. if (!states[name]) {
  5801. states[name] = {};
  5802. }
  5803. return states[name];
  5804. };
  5805. Element.prototype.clearStates = function (noAnimation) {
  5806. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  5807. };
  5808. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  5809. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  5810. var hasStates = this.hasState();
  5811. if (!hasStates && toNormalState) {
  5812. return;
  5813. }
  5814. var currentStates = this.currentStates;
  5815. var animationCfg = this.stateTransition;
  5816. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  5817. return;
  5818. }
  5819. var state;
  5820. if (this.stateProxy && !toNormalState) {
  5821. state = this.stateProxy(stateName);
  5822. }
  5823. if (!state) {
  5824. state = (this.states && this.states[stateName]);
  5825. }
  5826. if (!state && !toNormalState) {
  5827. logError("State " + stateName + " not exists.");
  5828. return;
  5829. }
  5830. if (!toNormalState) {
  5831. this.saveCurrentToNormalState(state);
  5832. }
  5833. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  5834. if (useHoverLayer) {
  5835. this._toggleHoverLayerFlag(true);
  5836. }
  5837. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  5838. var textContent = this._textContent;
  5839. var textGuide = this._textGuide;
  5840. if (textContent) {
  5841. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5842. }
  5843. if (textGuide) {
  5844. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5845. }
  5846. if (toNormalState) {
  5847. this.currentStates = [];
  5848. this._normalState = {};
  5849. }
  5850. else {
  5851. if (!keepCurrentStates) {
  5852. this.currentStates = [stateName];
  5853. }
  5854. else {
  5855. this.currentStates.push(stateName);
  5856. }
  5857. }
  5858. this._updateAnimationTargets();
  5859. this.markRedraw();
  5860. if (!useHoverLayer && this.__inHover) {
  5861. this._toggleHoverLayerFlag(false);
  5862. this.__dirty &= ~REDRAW_BIT;
  5863. }
  5864. return state;
  5865. };
  5866. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  5867. if (!states.length) {
  5868. this.clearStates();
  5869. }
  5870. else {
  5871. var stateObjects = [];
  5872. var currentStates = this.currentStates;
  5873. var len = states.length;
  5874. var notChange = len === currentStates.length;
  5875. if (notChange) {
  5876. for (var i = 0; i < len; i++) {
  5877. if (states[i] !== currentStates[i]) {
  5878. notChange = false;
  5879. break;
  5880. }
  5881. }
  5882. }
  5883. if (notChange) {
  5884. return;
  5885. }
  5886. for (var i = 0; i < len; i++) {
  5887. var stateName = states[i];
  5888. var stateObj = void 0;
  5889. if (this.stateProxy) {
  5890. stateObj = this.stateProxy(stateName, states);
  5891. }
  5892. if (!stateObj) {
  5893. stateObj = this.states[stateName];
  5894. }
  5895. if (stateObj) {
  5896. stateObjects.push(stateObj);
  5897. }
  5898. }
  5899. var lastStateObj = stateObjects[len - 1];
  5900. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  5901. if (useHoverLayer) {
  5902. this._toggleHoverLayerFlag(true);
  5903. }
  5904. var mergedState = this._mergeStates(stateObjects);
  5905. var animationCfg = this.stateTransition;
  5906. this.saveCurrentToNormalState(mergedState);
  5907. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  5908. var textContent = this._textContent;
  5909. var textGuide = this._textGuide;
  5910. if (textContent) {
  5911. textContent.useStates(states, noAnimation, useHoverLayer);
  5912. }
  5913. if (textGuide) {
  5914. textGuide.useStates(states, noAnimation, useHoverLayer);
  5915. }
  5916. this._updateAnimationTargets();
  5917. this.currentStates = states.slice();
  5918. this.markRedraw();
  5919. if (!useHoverLayer && this.__inHover) {
  5920. this._toggleHoverLayerFlag(false);
  5921. this.__dirty &= ~REDRAW_BIT;
  5922. }
  5923. }
  5924. };
  5925. Element.prototype._updateAnimationTargets = function () {
  5926. for (var i = 0; i < this.animators.length; i++) {
  5927. var animator = this.animators[i];
  5928. if (animator.targetName) {
  5929. animator.changeTarget(this[animator.targetName]);
  5930. }
  5931. }
  5932. };
  5933. Element.prototype.removeState = function (state) {
  5934. var idx = indexOf(this.currentStates, state);
  5935. if (idx >= 0) {
  5936. var currentStates = this.currentStates.slice();
  5937. currentStates.splice(idx, 1);
  5938. this.useStates(currentStates);
  5939. }
  5940. };
  5941. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  5942. var currentStates = this.currentStates.slice();
  5943. var idx = indexOf(currentStates, oldState);
  5944. var newStateExists = indexOf(currentStates, newState) >= 0;
  5945. if (idx >= 0) {
  5946. if (!newStateExists) {
  5947. currentStates[idx] = newState;
  5948. }
  5949. else {
  5950. currentStates.splice(idx, 1);
  5951. }
  5952. }
  5953. else if (forceAdd && !newStateExists) {
  5954. currentStates.push(newState);
  5955. }
  5956. this.useStates(currentStates);
  5957. };
  5958. Element.prototype.toggleState = function (state, enable) {
  5959. if (enable) {
  5960. this.useState(state, true);
  5961. }
  5962. else {
  5963. this.removeState(state);
  5964. }
  5965. };
  5966. Element.prototype._mergeStates = function (states) {
  5967. var mergedState = {};
  5968. var mergedTextConfig;
  5969. for (var i = 0; i < states.length; i++) {
  5970. var state = states[i];
  5971. extend(mergedState, state);
  5972. if (state.textConfig) {
  5973. mergedTextConfig = mergedTextConfig || {};
  5974. extend(mergedTextConfig, state.textConfig);
  5975. }
  5976. }
  5977. if (mergedTextConfig) {
  5978. mergedState.textConfig = mergedTextConfig;
  5979. }
  5980. return mergedState;
  5981. };
  5982. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  5983. var needsRestoreToNormal = !(state && keepCurrentStates);
  5984. if (state && state.textConfig) {
  5985. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  5986. extend(this.textConfig, state.textConfig);
  5987. }
  5988. else if (needsRestoreToNormal) {
  5989. if (normalState.textConfig) {
  5990. this.textConfig = normalState.textConfig;
  5991. }
  5992. }
  5993. var transitionTarget = {};
  5994. var hasTransition = false;
  5995. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  5996. var key = PRIMARY_STATES_KEYS[i];
  5997. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  5998. if (state && state[key] != null) {
  5999. if (propNeedsTransition) {
  6000. hasTransition = true;
  6001. transitionTarget[key] = state[key];
  6002. }
  6003. else {
  6004. this[key] = state[key];
  6005. }
  6006. }
  6007. else if (needsRestoreToNormal) {
  6008. if (normalState[key] != null) {
  6009. if (propNeedsTransition) {
  6010. hasTransition = true;
  6011. transitionTarget[key] = normalState[key];
  6012. }
  6013. else {
  6014. this[key] = normalState[key];
  6015. }
  6016. }
  6017. }
  6018. }
  6019. if (!transition) {
  6020. for (var i = 0; i < this.animators.length; i++) {
  6021. var animator = this.animators[i];
  6022. var targetName = animator.targetName;
  6023. if (!animator.getLoop()) {
  6024. animator.__changeFinalValue(targetName
  6025. ? (state || normalState)[targetName]
  6026. : (state || normalState));
  6027. }
  6028. }
  6029. }
  6030. if (hasTransition) {
  6031. this._transitionState(stateName, transitionTarget, animationCfg);
  6032. }
  6033. };
  6034. Element.prototype._attachComponent = function (componentEl) {
  6035. if (componentEl.__zr && !componentEl.__hostTarget) {
  6036. if ("development" !== 'production') {
  6037. throw new Error('Text element has been added to zrender.');
  6038. }
  6039. return;
  6040. }
  6041. if (componentEl === this) {
  6042. if ("development" !== 'production') {
  6043. throw new Error('Recursive component attachment.');
  6044. }
  6045. return;
  6046. }
  6047. var zr = this.__zr;
  6048. if (zr) {
  6049. componentEl.addSelfToZr(zr);
  6050. }
  6051. componentEl.__zr = zr;
  6052. componentEl.__hostTarget = this;
  6053. };
  6054. Element.prototype._detachComponent = function (componentEl) {
  6055. if (componentEl.__zr) {
  6056. componentEl.removeSelfFromZr(componentEl.__zr);
  6057. }
  6058. componentEl.__zr = null;
  6059. componentEl.__hostTarget = null;
  6060. };
  6061. Element.prototype.getClipPath = function () {
  6062. return this._clipPath;
  6063. };
  6064. Element.prototype.setClipPath = function (clipPath) {
  6065. if (this._clipPath && this._clipPath !== clipPath) {
  6066. this.removeClipPath();
  6067. }
  6068. this._attachComponent(clipPath);
  6069. this._clipPath = clipPath;
  6070. this.markRedraw();
  6071. };
  6072. Element.prototype.removeClipPath = function () {
  6073. var clipPath = this._clipPath;
  6074. if (clipPath) {
  6075. this._detachComponent(clipPath);
  6076. this._clipPath = null;
  6077. this.markRedraw();
  6078. }
  6079. };
  6080. Element.prototype.getTextContent = function () {
  6081. return this._textContent;
  6082. };
  6083. Element.prototype.setTextContent = function (textEl) {
  6084. var previousTextContent = this._textContent;
  6085. if (previousTextContent === textEl) {
  6086. return;
  6087. }
  6088. if (previousTextContent && previousTextContent !== textEl) {
  6089. this.removeTextContent();
  6090. }
  6091. if ("development" !== 'production') {
  6092. if (textEl.__zr && !textEl.__hostTarget) {
  6093. throw new Error('Text element has been added to zrender.');
  6094. }
  6095. }
  6096. textEl.innerTransformable = new Transformable();
  6097. this._attachComponent(textEl);
  6098. this._textContent = textEl;
  6099. this.markRedraw();
  6100. };
  6101. Element.prototype.setTextConfig = function (cfg) {
  6102. if (!this.textConfig) {
  6103. this.textConfig = {};
  6104. }
  6105. extend(this.textConfig, cfg);
  6106. this.markRedraw();
  6107. };
  6108. Element.prototype.removeTextConfig = function () {
  6109. this.textConfig = null;
  6110. this.markRedraw();
  6111. };
  6112. Element.prototype.removeTextContent = function () {
  6113. var textEl = this._textContent;
  6114. if (textEl) {
  6115. textEl.innerTransformable = null;
  6116. this._detachComponent(textEl);
  6117. this._textContent = null;
  6118. this._innerTextDefaultStyle = null;
  6119. this.markRedraw();
  6120. }
  6121. };
  6122. Element.prototype.getTextGuideLine = function () {
  6123. return this._textGuide;
  6124. };
  6125. Element.prototype.setTextGuideLine = function (guideLine) {
  6126. if (this._textGuide && this._textGuide !== guideLine) {
  6127. this.removeTextGuideLine();
  6128. }
  6129. this._attachComponent(guideLine);
  6130. this._textGuide = guideLine;
  6131. this.markRedraw();
  6132. };
  6133. Element.prototype.removeTextGuideLine = function () {
  6134. var textGuide = this._textGuide;
  6135. if (textGuide) {
  6136. this._detachComponent(textGuide);
  6137. this._textGuide = null;
  6138. this.markRedraw();
  6139. }
  6140. };
  6141. Element.prototype.markRedraw = function () {
  6142. this.__dirty |= REDRAW_BIT;
  6143. var zr = this.__zr;
  6144. if (zr) {
  6145. if (this.__inHover) {
  6146. zr.refreshHover();
  6147. }
  6148. else {
  6149. zr.refresh();
  6150. }
  6151. }
  6152. if (this.__hostTarget) {
  6153. this.__hostTarget.markRedraw();
  6154. }
  6155. };
  6156. Element.prototype.dirty = function () {
  6157. this.markRedraw();
  6158. };
  6159. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6160. this.__inHover = inHover;
  6161. var textContent = this._textContent;
  6162. var textGuide = this._textGuide;
  6163. if (textContent) {
  6164. textContent.__inHover = inHover;
  6165. }
  6166. if (textGuide) {
  6167. textGuide.__inHover = inHover;
  6168. }
  6169. };
  6170. Element.prototype.addSelfToZr = function (zr) {
  6171. if (this.__zr === zr) {
  6172. return;
  6173. }
  6174. this.__zr = zr;
  6175. var animators = this.animators;
  6176. if (animators) {
  6177. for (var i = 0; i < animators.length; i++) {
  6178. zr.animation.addAnimator(animators[i]);
  6179. }
  6180. }
  6181. if (this._clipPath) {
  6182. this._clipPath.addSelfToZr(zr);
  6183. }
  6184. if (this._textContent) {
  6185. this._textContent.addSelfToZr(zr);
  6186. }
  6187. if (this._textGuide) {
  6188. this._textGuide.addSelfToZr(zr);
  6189. }
  6190. };
  6191. Element.prototype.removeSelfFromZr = function (zr) {
  6192. if (!this.__zr) {
  6193. return;
  6194. }
  6195. this.__zr = null;
  6196. var animators = this.animators;
  6197. if (animators) {
  6198. for (var i = 0; i < animators.length; i++) {
  6199. zr.animation.removeAnimator(animators[i]);
  6200. }
  6201. }
  6202. if (this._clipPath) {
  6203. this._clipPath.removeSelfFromZr(zr);
  6204. }
  6205. if (this._textContent) {
  6206. this._textContent.removeSelfFromZr(zr);
  6207. }
  6208. if (this._textGuide) {
  6209. this._textGuide.removeSelfFromZr(zr);
  6210. }
  6211. };
  6212. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6213. var target = key ? this[key] : this;
  6214. if ("development" !== 'production') {
  6215. if (!target) {
  6216. logError('Property "'
  6217. + key
  6218. + '" is not existed in element '
  6219. + this.id);
  6220. return;
  6221. }
  6222. }
  6223. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6224. key && (animator.targetName = key);
  6225. this.addAnimator(animator, key);
  6226. return animator;
  6227. };
  6228. Element.prototype.addAnimator = function (animator, key) {
  6229. var zr = this.__zr;
  6230. var el = this;
  6231. animator.during(function () {
  6232. el.updateDuringAnimation(key);
  6233. }).done(function () {
  6234. var animators = el.animators;
  6235. var idx = indexOf(animators, animator);
  6236. if (idx >= 0) {
  6237. animators.splice(idx, 1);
  6238. }
  6239. });
  6240. this.animators.push(animator);
  6241. if (zr) {
  6242. zr.animation.addAnimator(animator);
  6243. }
  6244. zr && zr.wakeUp();
  6245. };
  6246. Element.prototype.updateDuringAnimation = function (key) {
  6247. this.markRedraw();
  6248. };
  6249. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6250. var animators = this.animators;
  6251. var len = animators.length;
  6252. var leftAnimators = [];
  6253. for (var i = 0; i < len; i++) {
  6254. var animator = animators[i];
  6255. if (!scope || scope === animator.scope) {
  6256. animator.stop(forwardToLast);
  6257. }
  6258. else {
  6259. leftAnimators.push(animator);
  6260. }
  6261. }
  6262. this.animators = leftAnimators;
  6263. return this;
  6264. };
  6265. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6266. animateTo(this, target, cfg, animationProps);
  6267. };
  6268. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6269. animateTo(this, target, cfg, animationProps, true);
  6270. };
  6271. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6272. var animators = animateTo(this, target, cfg, animationProps);
  6273. for (var i = 0; i < animators.length; i++) {
  6274. animators[i].__fromStateTransition = stateName;
  6275. }
  6276. };
  6277. Element.prototype.getBoundingRect = function () {
  6278. return null;
  6279. };
  6280. Element.prototype.getPaintRect = function () {
  6281. return null;
  6282. };
  6283. Element.initDefaultProps = (function () {
  6284. var elProto = Element.prototype;
  6285. elProto.type = 'element';
  6286. elProto.name = '';
  6287. elProto.ignore =
  6288. elProto.silent =
  6289. elProto.isGroup =
  6290. elProto.draggable =
  6291. elProto.dragging =
  6292. elProto.ignoreClip =
  6293. elProto.__inHover = false;
  6294. elProto.__dirty = REDRAW_BIT;
  6295. var logs = {};
  6296. function logDeprecatedError(key, xKey, yKey) {
  6297. if (!logs[key + xKey + yKey]) {
  6298. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6299. logs[key + xKey + yKey] = true;
  6300. }
  6301. }
  6302. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6303. Object.defineProperty(elProto, key, {
  6304. get: function () {
  6305. if ("development" !== 'production') {
  6306. logDeprecatedError(key, xKey, yKey);
  6307. }
  6308. if (!this[privateKey]) {
  6309. var pos = this[privateKey] = [];
  6310. enhanceArray(this, pos);
  6311. }
  6312. return this[privateKey];
  6313. },
  6314. set: function (pos) {
  6315. if ("development" !== 'production') {
  6316. logDeprecatedError(key, xKey, yKey);
  6317. }
  6318. this[xKey] = pos[0];
  6319. this[yKey] = pos[1];
  6320. this[privateKey] = pos;
  6321. enhanceArray(this, pos);
  6322. }
  6323. });
  6324. function enhanceArray(self, pos) {
  6325. Object.defineProperty(pos, 0, {
  6326. get: function () {
  6327. return self[xKey];
  6328. },
  6329. set: function (val) {
  6330. self[xKey] = val;
  6331. }
  6332. });
  6333. Object.defineProperty(pos, 1, {
  6334. get: function () {
  6335. return self[yKey];
  6336. },
  6337. set: function (val) {
  6338. self[yKey] = val;
  6339. }
  6340. });
  6341. }
  6342. }
  6343. if (Object.defineProperty) {
  6344. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6345. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6346. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6347. }
  6348. })();
  6349. return Element;
  6350. }());
  6351. mixin(Element, Eventful);
  6352. mixin(Element, Transformable);
  6353. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6354. cfg = cfg || {};
  6355. var animators = [];
  6356. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6357. var finishCount = animators.length;
  6358. var doneHappened = false;
  6359. var cfgDone = cfg.done;
  6360. var cfgAborted = cfg.aborted;
  6361. var doneCb = function () {
  6362. doneHappened = true;
  6363. finishCount--;
  6364. if (finishCount <= 0) {
  6365. doneHappened
  6366. ? (cfgDone && cfgDone())
  6367. : (cfgAborted && cfgAborted());
  6368. }
  6369. };
  6370. var abortedCb = function () {
  6371. finishCount--;
  6372. if (finishCount <= 0) {
  6373. doneHappened
  6374. ? (cfgDone && cfgDone())
  6375. : (cfgAborted && cfgAborted());
  6376. }
  6377. };
  6378. if (!finishCount) {
  6379. cfgDone && cfgDone();
  6380. }
  6381. if (animators.length > 0 && cfg.during) {
  6382. animators[0].during(function (target, percent) {
  6383. cfg.during(percent);
  6384. });
  6385. }
  6386. for (var i = 0; i < animators.length; i++) {
  6387. var animator = animators[i];
  6388. if (doneCb) {
  6389. animator.done(doneCb);
  6390. }
  6391. if (abortedCb) {
  6392. animator.aborted(abortedCb);
  6393. }
  6394. if (cfg.force) {
  6395. animator.duration(cfg.duration);
  6396. }
  6397. animator.start(cfg.easing);
  6398. }
  6399. return animators;
  6400. }
  6401. function copyArrShallow(source, target, len) {
  6402. for (var i = 0; i < len; i++) {
  6403. source[i] = target[i];
  6404. }
  6405. }
  6406. function is2DArray(value) {
  6407. return isArrayLike(value[0]);
  6408. }
  6409. function copyValue(target, source, key) {
  6410. if (isArrayLike(source[key])) {
  6411. if (!isArrayLike(target[key])) {
  6412. target[key] = [];
  6413. }
  6414. if (isTypedArray(source[key])) {
  6415. var len = source[key].length;
  6416. if (target[key].length !== len) {
  6417. target[key] = new (source[key].constructor)(len);
  6418. copyArrShallow(target[key], source[key], len);
  6419. }
  6420. }
  6421. else {
  6422. var sourceArr = source[key];
  6423. var targetArr = target[key];
  6424. var len0 = sourceArr.length;
  6425. if (is2DArray(sourceArr)) {
  6426. var len1 = sourceArr[0].length;
  6427. for (var i = 0; i < len0; i++) {
  6428. if (!targetArr[i]) {
  6429. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6430. }
  6431. else {
  6432. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6433. }
  6434. }
  6435. }
  6436. else {
  6437. copyArrShallow(targetArr, sourceArr, len0);
  6438. }
  6439. targetArr.length = sourceArr.length;
  6440. }
  6441. }
  6442. else {
  6443. target[key] = source[key];
  6444. }
  6445. }
  6446. function isValueSame(val1, val2) {
  6447. return val1 === val2
  6448. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6449. }
  6450. function is1DArraySame(arr0, arr1) {
  6451. var len = arr0.length;
  6452. if (len !== arr1.length) {
  6453. return false;
  6454. }
  6455. for (var i = 0; i < len; i++) {
  6456. if (arr0[i] !== arr1[i]) {
  6457. return false;
  6458. }
  6459. }
  6460. return true;
  6461. }
  6462. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6463. var targetKeys = keys(target);
  6464. var duration = cfg.duration;
  6465. var delay = cfg.delay;
  6466. var additive = cfg.additive;
  6467. var setToFinal = cfg.setToFinal;
  6468. var animateAll = !isObject(animationProps);
  6469. var existsAnimators = animatable.animators;
  6470. var animationKeys = [];
  6471. for (var k = 0; k < targetKeys.length; k++) {
  6472. var innerKey = targetKeys[k];
  6473. var targetVal = target[innerKey];
  6474. if (targetVal != null && animateObj[innerKey] != null
  6475. && (animateAll || animationProps[innerKey])) {
  6476. if (isObject(targetVal)
  6477. && !isArrayLike(targetVal)
  6478. && !isGradientObject(targetVal)) {
  6479. if (topKey) {
  6480. if (!reverse) {
  6481. animateObj[innerKey] = targetVal;
  6482. animatable.updateDuringAnimation(topKey);
  6483. }
  6484. continue;
  6485. }
  6486. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6487. }
  6488. else {
  6489. animationKeys.push(innerKey);
  6490. }
  6491. }
  6492. else if (!reverse) {
  6493. animateObj[innerKey] = targetVal;
  6494. animatable.updateDuringAnimation(topKey);
  6495. animationKeys.push(innerKey);
  6496. }
  6497. }
  6498. var keyLen = animationKeys.length;
  6499. if (!additive && keyLen) {
  6500. for (var i = 0; i < existsAnimators.length; i++) {
  6501. var animator = existsAnimators[i];
  6502. if (animator.targetName === topKey) {
  6503. var allAborted = animator.stopTracks(animationKeys);
  6504. if (allAborted) {
  6505. var idx = indexOf(existsAnimators, animator);
  6506. existsAnimators.splice(idx, 1);
  6507. }
  6508. }
  6509. }
  6510. }
  6511. if (!cfg.force) {
  6512. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6513. keyLen = animationKeys.length;
  6514. }
  6515. if (keyLen > 0
  6516. || (cfg.force && !animators.length)) {
  6517. var revertedSource = void 0;
  6518. var reversedTarget = void 0;
  6519. var sourceClone = void 0;
  6520. if (reverse) {
  6521. reversedTarget = {};
  6522. if (setToFinal) {
  6523. revertedSource = {};
  6524. }
  6525. for (var i = 0; i < keyLen; i++) {
  6526. var innerKey = animationKeys[i];
  6527. reversedTarget[innerKey] = animateObj[innerKey];
  6528. if (setToFinal) {
  6529. revertedSource[innerKey] = target[innerKey];
  6530. }
  6531. else {
  6532. animateObj[innerKey] = target[innerKey];
  6533. }
  6534. }
  6535. }
  6536. else if (setToFinal) {
  6537. sourceClone = {};
  6538. for (var i = 0; i < keyLen; i++) {
  6539. var innerKey = animationKeys[i];
  6540. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6541. copyValue(animateObj, target, innerKey);
  6542. }
  6543. }
  6544. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6545. animator.targetName = topKey;
  6546. if (cfg.scope) {
  6547. animator.scope = cfg.scope;
  6548. }
  6549. if (setToFinal && revertedSource) {
  6550. animator.whenWithKeys(0, revertedSource, animationKeys);
  6551. }
  6552. if (sourceClone) {
  6553. animator.whenWithKeys(0, sourceClone, animationKeys);
  6554. }
  6555. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6556. animatable.addAnimator(animator, topKey);
  6557. animators.push(animator);
  6558. }
  6559. }
  6560. var Group = (function (_super) {
  6561. __extends(Group, _super);
  6562. function Group(opts) {
  6563. var _this = _super.call(this) || this;
  6564. _this.isGroup = true;
  6565. _this._children = [];
  6566. _this.attr(opts);
  6567. return _this;
  6568. }
  6569. Group.prototype.childrenRef = function () {
  6570. return this._children;
  6571. };
  6572. Group.prototype.children = function () {
  6573. return this._children.slice();
  6574. };
  6575. Group.prototype.childAt = function (idx) {
  6576. return this._children[idx];
  6577. };
  6578. Group.prototype.childOfName = function (name) {
  6579. var children = this._children;
  6580. for (var i = 0; i < children.length; i++) {
  6581. if (children[i].name === name) {
  6582. return children[i];
  6583. }
  6584. }
  6585. };
  6586. Group.prototype.childCount = function () {
  6587. return this._children.length;
  6588. };
  6589. Group.prototype.add = function (child) {
  6590. if (child) {
  6591. if (child !== this && child.parent !== this) {
  6592. this._children.push(child);
  6593. this._doAdd(child);
  6594. }
  6595. if ("development" !== 'production') {
  6596. if (child.__hostTarget) {
  6597. throw 'This elemenet has been used as an attachment';
  6598. }
  6599. }
  6600. }
  6601. return this;
  6602. };
  6603. Group.prototype.addBefore = function (child, nextSibling) {
  6604. if (child && child !== this && child.parent !== this
  6605. && nextSibling && nextSibling.parent === this) {
  6606. var children = this._children;
  6607. var idx = children.indexOf(nextSibling);
  6608. if (idx >= 0) {
  6609. children.splice(idx, 0, child);
  6610. this._doAdd(child);
  6611. }
  6612. }
  6613. return this;
  6614. };
  6615. Group.prototype.replace = function (oldChild, newChild) {
  6616. var idx = indexOf(this._children, oldChild);
  6617. if (idx >= 0) {
  6618. this.replaceAt(newChild, idx);
  6619. }
  6620. return this;
  6621. };
  6622. Group.prototype.replaceAt = function (child, index) {
  6623. var children = this._children;
  6624. var old = children[index];
  6625. if (child && child !== this && child.parent !== this && child !== old) {
  6626. children[index] = child;
  6627. old.parent = null;
  6628. var zr = this.__zr;
  6629. if (zr) {
  6630. old.removeSelfFromZr(zr);
  6631. }
  6632. this._doAdd(child);
  6633. }
  6634. return this;
  6635. };
  6636. Group.prototype._doAdd = function (child) {
  6637. if (child.parent) {
  6638. child.parent.remove(child);
  6639. }
  6640. child.parent = this;
  6641. var zr = this.__zr;
  6642. if (zr && zr !== child.__zr) {
  6643. child.addSelfToZr(zr);
  6644. }
  6645. zr && zr.refresh();
  6646. };
  6647. Group.prototype.remove = function (child) {
  6648. var zr = this.__zr;
  6649. var children = this._children;
  6650. var idx = indexOf(children, child);
  6651. if (idx < 0) {
  6652. return this;
  6653. }
  6654. children.splice(idx, 1);
  6655. child.parent = null;
  6656. if (zr) {
  6657. child.removeSelfFromZr(zr);
  6658. }
  6659. zr && zr.refresh();
  6660. return this;
  6661. };
  6662. Group.prototype.removeAll = function () {
  6663. var children = this._children;
  6664. var zr = this.__zr;
  6665. for (var i = 0; i < children.length; i++) {
  6666. var child = children[i];
  6667. if (zr) {
  6668. child.removeSelfFromZr(zr);
  6669. }
  6670. child.parent = null;
  6671. }
  6672. children.length = 0;
  6673. return this;
  6674. };
  6675. Group.prototype.eachChild = function (cb, context) {
  6676. var children = this._children;
  6677. for (var i = 0; i < children.length; i++) {
  6678. var child = children[i];
  6679. cb.call(context, child, i);
  6680. }
  6681. return this;
  6682. };
  6683. Group.prototype.traverse = function (cb, context) {
  6684. for (var i = 0; i < this._children.length; i++) {
  6685. var child = this._children[i];
  6686. var stopped = cb.call(context, child);
  6687. if (child.isGroup && !stopped) {
  6688. child.traverse(cb, context);
  6689. }
  6690. }
  6691. return this;
  6692. };
  6693. Group.prototype.addSelfToZr = function (zr) {
  6694. _super.prototype.addSelfToZr.call(this, zr);
  6695. for (var i = 0; i < this._children.length; i++) {
  6696. var child = this._children[i];
  6697. child.addSelfToZr(zr);
  6698. }
  6699. };
  6700. Group.prototype.removeSelfFromZr = function (zr) {
  6701. _super.prototype.removeSelfFromZr.call(this, zr);
  6702. for (var i = 0; i < this._children.length; i++) {
  6703. var child = this._children[i];
  6704. child.removeSelfFromZr(zr);
  6705. }
  6706. };
  6707. Group.prototype.getBoundingRect = function (includeChildren) {
  6708. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6709. var children = includeChildren || this._children;
  6710. var tmpMat = [];
  6711. var rect = null;
  6712. for (var i = 0; i < children.length; i++) {
  6713. var child = children[i];
  6714. if (child.ignore || child.invisible) {
  6715. continue;
  6716. }
  6717. var childRect = child.getBoundingRect();
  6718. var transform = child.getLocalTransform(tmpMat);
  6719. if (transform) {
  6720. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6721. rect = rect || tmpRect.clone();
  6722. rect.union(tmpRect);
  6723. }
  6724. else {
  6725. rect = rect || childRect.clone();
  6726. rect.union(childRect);
  6727. }
  6728. }
  6729. return rect || tmpRect;
  6730. };
  6731. return Group;
  6732. }(Element));
  6733. Group.prototype.type = 'group';
  6734. /*!
  6735. * ZRender, a high performance 2d drawing library.
  6736. *
  6737. * Copyright (c) 2013, Baidu Inc.
  6738. * All rights reserved.
  6739. *
  6740. * LICENSE
  6741. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6742. */
  6743. var painterCtors = {};
  6744. var instances = {};
  6745. function delInstance(id) {
  6746. delete instances[id];
  6747. }
  6748. function isDarkMode(backgroundColor) {
  6749. if (!backgroundColor) {
  6750. return false;
  6751. }
  6752. if (typeof backgroundColor === 'string') {
  6753. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6754. }
  6755. else if (backgroundColor.colorStops) {
  6756. var colorStops = backgroundColor.colorStops;
  6757. var totalLum = 0;
  6758. var len = colorStops.length;
  6759. for (var i = 0; i < len; i++) {
  6760. totalLum += lum(colorStops[i].color, 1);
  6761. }
  6762. totalLum /= len;
  6763. return totalLum < DARK_MODE_THRESHOLD;
  6764. }
  6765. return false;
  6766. }
  6767. var ZRender = (function () {
  6768. function ZRender(id, dom, opts) {
  6769. var _this = this;
  6770. this._sleepAfterStill = 10;
  6771. this._stillFrameAccum = 0;
  6772. this._needsRefresh = true;
  6773. this._needsRefreshHover = true;
  6774. this._darkMode = false;
  6775. opts = opts || {};
  6776. this.dom = dom;
  6777. this.id = id;
  6778. var storage = new Storage();
  6779. var rendererType = opts.renderer || 'canvas';
  6780. if (!painterCtors[rendererType]) {
  6781. rendererType = keys(painterCtors)[0];
  6782. }
  6783. if ("development" !== 'production') {
  6784. if (!painterCtors[rendererType]) {
  6785. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  6786. }
  6787. }
  6788. opts.useDirtyRect = opts.useDirtyRect == null
  6789. ? false
  6790. : opts.useDirtyRect;
  6791. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  6792. var ssrMode = opts.ssr || painter.ssrOnly;
  6793. this.storage = storage;
  6794. this.painter = painter;
  6795. var handerProxy = (!env.node && !env.worker && !ssrMode)
  6796. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  6797. : null;
  6798. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  6799. this.animation = new Animation({
  6800. stage: {
  6801. update: ssrMode ? null : function () { return _this._flush(true); }
  6802. }
  6803. });
  6804. if (!ssrMode) {
  6805. this.animation.start();
  6806. }
  6807. }
  6808. ZRender.prototype.add = function (el) {
  6809. if (!el) {
  6810. return;
  6811. }
  6812. this.storage.addRoot(el);
  6813. el.addSelfToZr(this);
  6814. this.refresh();
  6815. };
  6816. ZRender.prototype.remove = function (el) {
  6817. if (!el) {
  6818. return;
  6819. }
  6820. this.storage.delRoot(el);
  6821. el.removeSelfFromZr(this);
  6822. this.refresh();
  6823. };
  6824. ZRender.prototype.configLayer = function (zLevel, config) {
  6825. if (this.painter.configLayer) {
  6826. this.painter.configLayer(zLevel, config);
  6827. }
  6828. this.refresh();
  6829. };
  6830. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  6831. if (this.painter.setBackgroundColor) {
  6832. this.painter.setBackgroundColor(backgroundColor);
  6833. }
  6834. this.refresh();
  6835. this._backgroundColor = backgroundColor;
  6836. this._darkMode = isDarkMode(backgroundColor);
  6837. };
  6838. ZRender.prototype.getBackgroundColor = function () {
  6839. return this._backgroundColor;
  6840. };
  6841. ZRender.prototype.setDarkMode = function (darkMode) {
  6842. this._darkMode = darkMode;
  6843. };
  6844. ZRender.prototype.isDarkMode = function () {
  6845. return this._darkMode;
  6846. };
  6847. ZRender.prototype.refreshImmediately = function (fromInside) {
  6848. if (!fromInside) {
  6849. this.animation.update(true);
  6850. }
  6851. this._needsRefresh = false;
  6852. this.painter.refresh();
  6853. this._needsRefresh = false;
  6854. };
  6855. ZRender.prototype.refresh = function () {
  6856. this._needsRefresh = true;
  6857. this.animation.start();
  6858. };
  6859. ZRender.prototype.flush = function () {
  6860. this._flush(false);
  6861. };
  6862. ZRender.prototype._flush = function (fromInside) {
  6863. var triggerRendered;
  6864. var start = getTime();
  6865. if (this._needsRefresh) {
  6866. triggerRendered = true;
  6867. this.refreshImmediately(fromInside);
  6868. }
  6869. if (this._needsRefreshHover) {
  6870. triggerRendered = true;
  6871. this.refreshHoverImmediately();
  6872. }
  6873. var end = getTime();
  6874. if (triggerRendered) {
  6875. this._stillFrameAccum = 0;
  6876. this.trigger('rendered', {
  6877. elapsedTime: end - start
  6878. });
  6879. }
  6880. else if (this._sleepAfterStill > 0) {
  6881. this._stillFrameAccum++;
  6882. if (this._stillFrameAccum > this._sleepAfterStill) {
  6883. this.animation.stop();
  6884. }
  6885. }
  6886. };
  6887. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  6888. this._sleepAfterStill = stillFramesCount;
  6889. };
  6890. ZRender.prototype.wakeUp = function () {
  6891. this.animation.start();
  6892. this._stillFrameAccum = 0;
  6893. };
  6894. ZRender.prototype.refreshHover = function () {
  6895. this._needsRefreshHover = true;
  6896. };
  6897. ZRender.prototype.refreshHoverImmediately = function () {
  6898. this._needsRefreshHover = false;
  6899. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  6900. this.painter.refreshHover();
  6901. }
  6902. };
  6903. ZRender.prototype.resize = function (opts) {
  6904. opts = opts || {};
  6905. this.painter.resize(opts.width, opts.height);
  6906. this.handler.resize();
  6907. };
  6908. ZRender.prototype.clearAnimation = function () {
  6909. this.animation.clear();
  6910. };
  6911. ZRender.prototype.getWidth = function () {
  6912. return this.painter.getWidth();
  6913. };
  6914. ZRender.prototype.getHeight = function () {
  6915. return this.painter.getHeight();
  6916. };
  6917. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  6918. this.handler.setCursorStyle(cursorStyle);
  6919. };
  6920. ZRender.prototype.findHover = function (x, y) {
  6921. return this.handler.findHover(x, y);
  6922. };
  6923. ZRender.prototype.on = function (eventName, eventHandler, context) {
  6924. this.handler.on(eventName, eventHandler, context);
  6925. return this;
  6926. };
  6927. ZRender.prototype.off = function (eventName, eventHandler) {
  6928. this.handler.off(eventName, eventHandler);
  6929. };
  6930. ZRender.prototype.trigger = function (eventName, event) {
  6931. this.handler.trigger(eventName, event);
  6932. };
  6933. ZRender.prototype.clear = function () {
  6934. var roots = this.storage.getRoots();
  6935. for (var i = 0; i < roots.length; i++) {
  6936. if (roots[i] instanceof Group) {
  6937. roots[i].removeSelfFromZr(this);
  6938. }
  6939. }
  6940. this.storage.delAllRoots();
  6941. this.painter.clear();
  6942. };
  6943. ZRender.prototype.dispose = function () {
  6944. this.animation.stop();
  6945. this.clear();
  6946. this.storage.dispose();
  6947. this.painter.dispose();
  6948. this.handler.dispose();
  6949. this.animation =
  6950. this.storage =
  6951. this.painter =
  6952. this.handler = null;
  6953. delInstance(this.id);
  6954. };
  6955. return ZRender;
  6956. }());
  6957. function init(dom, opts) {
  6958. var zr = new ZRender(guid(), dom, opts);
  6959. instances[zr.id] = zr;
  6960. return zr;
  6961. }
  6962. function dispose(zr) {
  6963. zr.dispose();
  6964. }
  6965. function disposeAll() {
  6966. for (var key in instances) {
  6967. if (instances.hasOwnProperty(key)) {
  6968. instances[key].dispose();
  6969. }
  6970. }
  6971. instances = {};
  6972. }
  6973. function getInstance(id) {
  6974. return instances[id];
  6975. }
  6976. function registerPainter(name, Ctor) {
  6977. painterCtors[name] = Ctor;
  6978. }
  6979. var version = '5.3.2';
  6980. var zrender = /*#__PURE__*/Object.freeze({
  6981. __proto__: null,
  6982. init: init,
  6983. dispose: dispose,
  6984. disposeAll: disposeAll,
  6985. getInstance: getInstance,
  6986. registerPainter: registerPainter,
  6987. version: version
  6988. });
  6989. var RADIAN_EPSILON = 1e-4; // Although chrome already enlarge this number to 100 for `toFixed`, but
  6990. // we sill follow the spec for compatibility.
  6991. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  6992. function _trim(str) {
  6993. return str.replace(/^\s+|\s+$/g, '');
  6994. }
  6995. /**
  6996. * Linear mapping a value from domain to range
  6997. * @param val
  6998. * @param domain Domain extent domain[0] can be bigger than domain[1]
  6999. * @param range Range extent range[0] can be bigger than range[1]
  7000. * @param clamp Default to be false
  7001. */
  7002. function linearMap(val, domain, range, clamp) {
  7003. var d0 = domain[0];
  7004. var d1 = domain[1];
  7005. var r0 = range[0];
  7006. var r1 = range[1];
  7007. var subDomain = d1 - d0;
  7008. var subRange = r1 - r0;
  7009. if (subDomain === 0) {
  7010. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7011. } // Avoid accuracy problem in edge, such as
  7012. // 146.39 - 62.83 === 83.55999999999999.
  7013. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7014. // It is a little verbose for efficiency considering this method
  7015. // is a hotspot.
  7016. if (clamp) {
  7017. if (subDomain > 0) {
  7018. if (val <= d0) {
  7019. return r0;
  7020. } else if (val >= d1) {
  7021. return r1;
  7022. }
  7023. } else {
  7024. if (val >= d0) {
  7025. return r0;
  7026. } else if (val <= d1) {
  7027. return r1;
  7028. }
  7029. }
  7030. } else {
  7031. if (val === d0) {
  7032. return r0;
  7033. }
  7034. if (val === d1) {
  7035. return r1;
  7036. }
  7037. }
  7038. return (val - d0) / subDomain * subRange + r0;
  7039. }
  7040. /**
  7041. * Convert a percent string to absolute number.
  7042. * Returns NaN if percent is not a valid string or number
  7043. */
  7044. function parsePercent$1(percent, all) {
  7045. switch (percent) {
  7046. case 'center':
  7047. case 'middle':
  7048. percent = '50%';
  7049. break;
  7050. case 'left':
  7051. case 'top':
  7052. percent = '0%';
  7053. break;
  7054. case 'right':
  7055. case 'bottom':
  7056. percent = '100%';
  7057. break;
  7058. }
  7059. if (isString(percent)) {
  7060. if (_trim(percent).match(/%$/)) {
  7061. return parseFloat(percent) / 100 * all;
  7062. }
  7063. return parseFloat(percent);
  7064. }
  7065. return percent == null ? NaN : +percent;
  7066. }
  7067. function round(x, precision, returnStr) {
  7068. if (precision == null) {
  7069. precision = 10;
  7070. } // Avoid range error
  7071. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX); // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7072. x = (+x).toFixed(precision);
  7073. return returnStr ? x : +x;
  7074. }
  7075. /**
  7076. * Inplacd asc sort arr.
  7077. * The input arr will be modified.
  7078. */
  7079. function asc(arr) {
  7080. arr.sort(function (a, b) {
  7081. return a - b;
  7082. });
  7083. return arr;
  7084. }
  7085. /**
  7086. * Get precision.
  7087. */
  7088. function getPrecision(val) {
  7089. val = +val;
  7090. if (isNaN(val)) {
  7091. return 0;
  7092. } // It is much faster than methods converting number to string as follows
  7093. // let tmp = val.toString();
  7094. // return tmp.length - 1 - tmp.indexOf('.');
  7095. // especially when precision is low
  7096. // Notice:
  7097. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7098. // (see https://jsbench.me/2vkpcekkvw/1)
  7099. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7100. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7101. if (val > 1e-14) {
  7102. var e = 1;
  7103. for (var i = 0; i < 15; i++, e *= 10) {
  7104. if (Math.round(val * e) / e === val) {
  7105. return i;
  7106. }
  7107. }
  7108. }
  7109. return getPrecisionSafe(val);
  7110. }
  7111. /**
  7112. * Get precision with slow but safe method
  7113. */
  7114. function getPrecisionSafe(val) {
  7115. // toLowerCase for: '3.4E-12'
  7116. var str = val.toString().toLowerCase(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  7117. var eIndex = str.indexOf('e');
  7118. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7119. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7120. var dotIndex = str.indexOf('.');
  7121. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7122. return Math.max(0, decimalPartLen - exp);
  7123. }
  7124. /**
  7125. * Minimal dicernible data precisioin according to a single pixel.
  7126. */
  7127. function getPixelPrecision(dataExtent, pixelExtent) {
  7128. var log = Math.log;
  7129. var LN10 = Math.LN10;
  7130. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7131. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  7132. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7133. return !isFinite(precision) ? 20 : precision;
  7134. }
  7135. /**
  7136. * Get a data of given precision, assuring the sum of percentages
  7137. * in valueList is 1.
  7138. * The largest remainer method is used.
  7139. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7140. *
  7141. * @param valueList a list of all data
  7142. * @param idx index of the data to be processed in valueList
  7143. * @param precision integer number showing digits of precision
  7144. * @return percent ranging from 0 to 100
  7145. */
  7146. function getPercentWithPrecision(valueList, idx, precision) {
  7147. if (!valueList[idx]) {
  7148. return 0;
  7149. }
  7150. var sum = reduce(valueList, function (acc, val) {
  7151. return acc + (isNaN(val) ? 0 : val);
  7152. }, 0);
  7153. if (sum === 0) {
  7154. return 0;
  7155. }
  7156. var digits = Math.pow(10, precision);
  7157. var votesPerQuota = map(valueList, function (val) {
  7158. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7159. });
  7160. var targetSeats = digits * 100;
  7161. var seats = map(votesPerQuota, function (votes) {
  7162. // Assign automatic seats.
  7163. return Math.floor(votes);
  7164. });
  7165. var currentSum = reduce(seats, function (acc, val) {
  7166. return acc + val;
  7167. }, 0);
  7168. var remainder = map(votesPerQuota, function (votes, idx) {
  7169. return votes - seats[idx];
  7170. }); // Has remainding votes.
  7171. while (currentSum < targetSeats) {
  7172. // Find next largest remainder.
  7173. var max = Number.NEGATIVE_INFINITY;
  7174. var maxId = null;
  7175. for (var i = 0, len = remainder.length; i < len; ++i) {
  7176. if (remainder[i] > max) {
  7177. max = remainder[i];
  7178. maxId = i;
  7179. }
  7180. } // Add a vote to max remainder.
  7181. ++seats[maxId];
  7182. remainder[maxId] = 0;
  7183. ++currentSum;
  7184. }
  7185. return seats[idx] / digits;
  7186. }
  7187. /**
  7188. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7189. * See <http://0.30000000000000004.com/>
  7190. */
  7191. function addSafe(val0, val1) {
  7192. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1)); // const multiplier = Math.pow(10, maxPrecision);
  7193. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7194. var sum = val0 + val1; // // PENDING: support more?
  7195. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7196. } // Number.MAX_SAFE_INTEGER, ie do not support.
  7197. var MAX_SAFE_INTEGER = 9007199254740991;
  7198. /**
  7199. * To 0 - 2 * PI, considering negative radian.
  7200. */
  7201. function remRadian(radian) {
  7202. var pi2 = Math.PI * 2;
  7203. return (radian % pi2 + pi2) % pi2;
  7204. }
  7205. /**
  7206. * @param {type} radian
  7207. * @return {boolean}
  7208. */
  7209. function isRadianAroundZero(val) {
  7210. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7211. } // eslint-disable-next-line
  7212. 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
  7213. /**
  7214. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7215. * These values can be accepted:
  7216. * + An instance of Date, represent a time in its own time zone.
  7217. * + Or string in a subset of ISO 8601, only including:
  7218. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7219. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7220. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7221. * all of which will be treated as local time if time zone is not specified
  7222. * (see <https://momentjs.com/>).
  7223. * + Or other string format, including (all of which will be treated as loacal time):
  7224. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7225. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7226. * + a timestamp, which represent a time in UTC.
  7227. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7228. */
  7229. function parseDate(value) {
  7230. if (value instanceof Date) {
  7231. return value;
  7232. } else if (isString(value)) {
  7233. // Different browsers parse date in different way, so we parse it manually.
  7234. // Some other issues:
  7235. // new Date('1970-01-01') is UTC,
  7236. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7237. // See issue #3623
  7238. var match = TIME_REG.exec(value);
  7239. if (!match) {
  7240. // return Invalid Date.
  7241. return new Date(NaN);
  7242. } // Use local time when no timezone offset specifed.
  7243. if (!match[8]) {
  7244. // match[n] can only be string or undefined.
  7245. // But take care of '12' + 1 => '121'.
  7246. 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);
  7247. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7248. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7249. // For example, system timezone is set as "Time Zone: America/Toronto",
  7250. // then these code will get different result:
  7251. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7252. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7253. // So we should not use `new Date`, but use `Date.UTC`.
  7254. else {
  7255. var hour = +match[4] || 0;
  7256. if (match[8].toUpperCase() !== 'Z') {
  7257. hour -= +match[8].slice(0, 3);
  7258. }
  7259. 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));
  7260. }
  7261. } else if (value == null) {
  7262. return new Date(NaN);
  7263. }
  7264. return new Date(Math.round(value));
  7265. }
  7266. /**
  7267. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7268. *
  7269. * @param val
  7270. * @return
  7271. */
  7272. function quantity(val) {
  7273. return Math.pow(10, quantityExponent(val));
  7274. }
  7275. /**
  7276. * Exponent of the quantity of a number
  7277. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7278. *
  7279. * @param val non-negative value
  7280. * @return
  7281. */
  7282. function quantityExponent(val) {
  7283. if (val === 0) {
  7284. return 0;
  7285. }
  7286. var exp = Math.floor(Math.log(val) / Math.LN10);
  7287. /**
  7288. * exp is expected to be the rounded-down result of the base-10 log of val.
  7289. * But due to the precision loss with Math.log(val), we need to restore it
  7290. * using 10^exp to make sure we can get val back from exp. #11249
  7291. */
  7292. if (val / Math.pow(10, exp) >= 10) {
  7293. exp++;
  7294. }
  7295. return exp;
  7296. }
  7297. /**
  7298. * find a “nice” number approximately equal to x. Round the number if round = true,
  7299. * take ceiling if round = false. The primary observation is that the “nicest”
  7300. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7301. *
  7302. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7303. *
  7304. * @param val Non-negative value.
  7305. * @param round
  7306. * @return Niced number
  7307. */
  7308. function nice(val, round) {
  7309. var exponent = quantityExponent(val);
  7310. var exp10 = Math.pow(10, exponent);
  7311. var f = val / exp10; // 1 <= f < 10
  7312. var nf;
  7313. if (round) {
  7314. if (f < 1.5) {
  7315. nf = 1;
  7316. } else if (f < 2.5) {
  7317. nf = 2;
  7318. } else if (f < 4) {
  7319. nf = 3;
  7320. } else if (f < 7) {
  7321. nf = 5;
  7322. } else {
  7323. nf = 10;
  7324. }
  7325. } else {
  7326. if (f < 1) {
  7327. nf = 1;
  7328. } else if (f < 2) {
  7329. nf = 2;
  7330. } else if (f < 3) {
  7331. nf = 3;
  7332. } else if (f < 5) {
  7333. nf = 5;
  7334. } else {
  7335. nf = 10;
  7336. }
  7337. }
  7338. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7339. // 20 is the uppper bound of toFixed.
  7340. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7341. }
  7342. /**
  7343. * This code was copied from "d3.js"
  7344. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7345. * See the license statement at the head of this file.
  7346. * @param ascArr
  7347. */
  7348. function quantile(ascArr, p) {
  7349. var H = (ascArr.length - 1) * p + 1;
  7350. var h = Math.floor(H);
  7351. var v = +ascArr[h - 1];
  7352. var e = H - h;
  7353. return e ? v + e * (ascArr[h] - v) : v;
  7354. }
  7355. /**
  7356. * Order intervals asc, and split them when overlap.
  7357. * expect(numberUtil.reformIntervals([
  7358. * {interval: [18, 62], close: [1, 1]},
  7359. * {interval: [-Infinity, -70], close: [0, 0]},
  7360. * {interval: [-70, -26], close: [1, 1]},
  7361. * {interval: [-26, 18], close: [1, 1]},
  7362. * {interval: [62, 150], close: [1, 1]},
  7363. * {interval: [106, 150], close: [1, 1]},
  7364. * {interval: [150, Infinity], close: [0, 0]}
  7365. * ])).toEqual([
  7366. * {interval: [-Infinity, -70], close: [0, 0]},
  7367. * {interval: [-70, -26], close: [1, 1]},
  7368. * {interval: [-26, 18], close: [0, 1]},
  7369. * {interval: [18, 62], close: [0, 1]},
  7370. * {interval: [62, 150], close: [0, 1]},
  7371. * {interval: [150, Infinity], close: [0, 0]}
  7372. * ]);
  7373. * @param list, where `close` mean open or close
  7374. * of the interval, and Infinity can be used.
  7375. * @return The origin list, which has been reformed.
  7376. */
  7377. function reformIntervals(list) {
  7378. list.sort(function (a, b) {
  7379. return littleThan(a, b, 0) ? -1 : 1;
  7380. });
  7381. var curr = -Infinity;
  7382. var currClose = 1;
  7383. for (var i = 0; i < list.length;) {
  7384. var interval = list[i].interval;
  7385. var close_1 = list[i].close;
  7386. for (var lg = 0; lg < 2; lg++) {
  7387. if (interval[lg] <= curr) {
  7388. interval[lg] = curr;
  7389. close_1[lg] = !lg ? 1 - currClose : 1;
  7390. }
  7391. curr = interval[lg];
  7392. currClose = close_1[lg];
  7393. }
  7394. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7395. list.splice(i, 1);
  7396. } else {
  7397. i++;
  7398. }
  7399. }
  7400. return list;
  7401. function littleThan(a, b, lg) {
  7402. 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));
  7403. }
  7404. }
  7405. /**
  7406. * [Numberic is defined as]:
  7407. * `parseFloat(val) == val`
  7408. * For example:
  7409. * numeric:
  7410. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7411. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7412. * not-numeric:
  7413. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7414. * empty string, string with only white-spaces or line-terminal (see es spec),
  7415. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7416. * non-string, ...
  7417. *
  7418. * @test See full test cases in `test/ut/spec/util/number.js`.
  7419. * @return Must be a typeof number. If not numeric, return NaN.
  7420. */
  7421. function numericToNumber(val) {
  7422. var valFloat = parseFloat(val);
  7423. return valFloat == val // eslint-disable-line eqeqeq
  7424. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7425. ? valFloat : NaN;
  7426. }
  7427. /**
  7428. * Definition of "numeric": see `numericToNumber`.
  7429. */
  7430. function isNumeric(val) {
  7431. return !isNaN(numericToNumber(val));
  7432. }
  7433. /**
  7434. * Use random base to prevent users hard code depending on
  7435. * this auto generated marker id.
  7436. * @return An positive integer.
  7437. */
  7438. function getRandomIdBase() {
  7439. return Math.round(Math.random() * 9);
  7440. }
  7441. /**
  7442. * Get the greatest common dividor
  7443. *
  7444. * @param {number} a one number
  7445. * @param {number} b the other number
  7446. */
  7447. function getGreatestCommonDividor(a, b) {
  7448. if (b === 0) {
  7449. return a;
  7450. }
  7451. return getGreatestCommonDividor(b, a % b);
  7452. }
  7453. /**
  7454. * Get the least common multiple
  7455. *
  7456. * @param {number} a one number
  7457. * @param {number} b the other number
  7458. */
  7459. function getLeastCommonMultiple(a, b) {
  7460. if (a == null) {
  7461. return b;
  7462. }
  7463. if (b == null) {
  7464. return a;
  7465. }
  7466. return a * b / getGreatestCommonDividor(a, b);
  7467. }
  7468. var ECHARTS_PREFIX = '[ECharts] ';
  7469. var storedLogs = {};
  7470. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  7471. && console.warn && console.log;
  7472. function outputLog(type, str, onlyOnce) {
  7473. if (hasConsole) {
  7474. if (onlyOnce) {
  7475. if (storedLogs[str]) {
  7476. return;
  7477. }
  7478. storedLogs[str] = true;
  7479. } // eslint-disable-next-line
  7480. console[type](ECHARTS_PREFIX + str);
  7481. }
  7482. }
  7483. function log(str, onlyOnce) {
  7484. outputLog('log', str, onlyOnce);
  7485. }
  7486. function warn(str, onlyOnce) {
  7487. outputLog('warn', str, onlyOnce);
  7488. }
  7489. function error(str, onlyOnce) {
  7490. outputLog('error', str, onlyOnce);
  7491. }
  7492. function deprecateLog(str) {
  7493. if ("development" !== 'production') {
  7494. // Not display duplicate message.
  7495. outputLog('warn', 'DEPRECATED: ' + str, true);
  7496. }
  7497. }
  7498. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7499. if ("development" !== 'production') {
  7500. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7501. }
  7502. }
  7503. /**
  7504. * If in __DEV__ environment, get console printable message for users hint.
  7505. * Parameters are separated by ' '.
  7506. * @usuage
  7507. * makePrintable('This is an error on', someVar, someObj);
  7508. *
  7509. * @param hintInfo anything about the current execution context to hint users.
  7510. * @throws Error
  7511. */
  7512. function makePrintable() {
  7513. var hintInfo = [];
  7514. for (var _i = 0; _i < arguments.length; _i++) {
  7515. hintInfo[_i] = arguments[_i];
  7516. }
  7517. var msg = '';
  7518. if ("development" !== 'production') {
  7519. // Fuzzy stringify for print.
  7520. // This code only exist in dev environment.
  7521. var makePrintableStringIfPossible_1 = function (val) {
  7522. 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;
  7523. };
  7524. msg = map(hintInfo, function (arg) {
  7525. if (isString(arg)) {
  7526. // Print without quotation mark for some statement.
  7527. return arg;
  7528. } else {
  7529. var printableStr = makePrintableStringIfPossible_1(arg);
  7530. if (printableStr != null) {
  7531. return printableStr;
  7532. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7533. try {
  7534. return JSON.stringify(arg, function (n, val) {
  7535. var printableStr = makePrintableStringIfPossible_1(val);
  7536. return printableStr == null ? val : printableStr;
  7537. }); // In most cases the info object is small, so do not line break.
  7538. } catch (err) {
  7539. return '?';
  7540. }
  7541. } else {
  7542. return '?';
  7543. }
  7544. }
  7545. }).join(' ');
  7546. }
  7547. return msg;
  7548. }
  7549. /**
  7550. * @throws Error
  7551. */
  7552. function throwError(msg) {
  7553. throw new Error(msg);
  7554. }
  7555. function interpolateNumber$1(p0, p1, percent) {
  7556. return (p1 - p0) * percent + p0;
  7557. }
  7558. /**
  7559. * Make the name displayable. But we should
  7560. * make sure it is not duplicated with user
  7561. * specified name, so use '\0';
  7562. */
  7563. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7564. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7565. /**
  7566. * If value is not array, then translate it to array.
  7567. * @param {*} value
  7568. * @return {Array} [value] or value
  7569. */
  7570. function normalizeToArray(value) {
  7571. return value instanceof Array ? value : value == null ? [] : [value];
  7572. }
  7573. /**
  7574. * Sync default option between normal and emphasis like `position` and `show`
  7575. * In case some one will write code like
  7576. * label: {
  7577. * show: false,
  7578. * position: 'outside',
  7579. * fontSize: 18
  7580. * },
  7581. * emphasis: {
  7582. * label: { show: true }
  7583. * }
  7584. */
  7585. function defaultEmphasis(opt, key, subOpts) {
  7586. // Caution: performance sensitive.
  7587. if (opt) {
  7588. opt[key] = opt[key] || {};
  7589. opt.emphasis = opt.emphasis || {};
  7590. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7591. for (var i = 0, len = subOpts.length; i < len; i++) {
  7592. var subOptName = subOpts[i];
  7593. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7594. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7595. }
  7596. }
  7597. }
  7598. }
  7599. var TEXT_STYLE_OPTIONS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding']; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  7600. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7601. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7602. // // FIXME: deprecated, check and remove it.
  7603. // 'textStyle'
  7604. // ]);
  7605. /**
  7606. * The method do not ensure performance.
  7607. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7608. * This helper method retieves value from data.
  7609. */
  7610. function getDataItemValue(dataItem) {
  7611. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7612. }
  7613. /**
  7614. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7615. * This helper method determine if dataItem has extra option besides value
  7616. */
  7617. function isDataItemOption(dataItem) {
  7618. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7619. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7620. }
  7621. /**
  7622. * Mapping to existings for merge.
  7623. *
  7624. * Mode "normalMege":
  7625. * The mapping result (merge result) will keep the order of the existing
  7626. * component, rather than the order of new option. Because we should ensure
  7627. * some specified index reference (like xAxisIndex) keep work.
  7628. * And in most cases, "merge option" is used to update partial option but not
  7629. * be expected to change the order.
  7630. *
  7631. * Mode "replaceMege":
  7632. * (1) Only the id mapped components will be merged.
  7633. * (2) Other existing components (except internal compoonets) will be removed.
  7634. * (3) Other new options will be used to create new component.
  7635. * (4) The index of the existing compoents will not be modified.
  7636. * That means their might be "hole" after the removal.
  7637. * The new components are created first at those available index.
  7638. *
  7639. * Mode "replaceAll":
  7640. * This mode try to support that reproduce an echarts instance from another
  7641. * echarts instance (via `getOption`) in some simple cases.
  7642. * In this senario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7643. * which ensures the compoennt index referring (like `xAxisIndex: ?`) corrent. That is,
  7644. * the "hole" in `newCmptOptions` will also be kept.
  7645. * On the contrary, other modes try best to eliminate holes.
  7646. * PENDING: This is an experimental mode yet.
  7647. *
  7648. * @return See the comment of <MappingResult>.
  7649. */
  7650. function mappingToExists(existings, newCmptOptions, mode) {
  7651. var isNormalMergeMode = mode === 'normalMerge';
  7652. var isReplaceMergeMode = mode === 'replaceMerge';
  7653. var isReplaceAllMode = mode === 'replaceAll';
  7654. existings = existings || [];
  7655. newCmptOptions = (newCmptOptions || []).slice();
  7656. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7657. each(newCmptOptions, function (cmptOption, index) {
  7658. if (!isObject(cmptOption)) {
  7659. newCmptOptions[index] = null;
  7660. return;
  7661. }
  7662. if ("development" !== 'production') {
  7663. // There is some legacy case that name is set as `false`.
  7664. // But should work normally rather than throw error.
  7665. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7666. warnInvalidateIdOrName(cmptOption.id);
  7667. }
  7668. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7669. warnInvalidateIdOrName(cmptOption.name);
  7670. }
  7671. }
  7672. });
  7673. var result = prepareResult(existings, existingIdIdxMap, mode);
  7674. if (isNormalMergeMode || isReplaceMergeMode) {
  7675. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7676. }
  7677. if (isNormalMergeMode) {
  7678. mappingByName(result, newCmptOptions);
  7679. }
  7680. if (isNormalMergeMode || isReplaceMergeMode) {
  7681. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7682. } else if (isReplaceAllMode) {
  7683. mappingInReplaceAllMode(result, newCmptOptions);
  7684. }
  7685. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7686. // forEach will ommit those items and result in incorrect result.
  7687. return result;
  7688. }
  7689. function prepareResult(existings, existingIdIdxMap, mode) {
  7690. var result = [];
  7691. if (mode === 'replaceAll') {
  7692. return result;
  7693. } // Do not use native `map` to in case that the array `existings`
  7694. // contains elided items, which will be ommited.
  7695. for (var index = 0; index < existings.length; index++) {
  7696. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7697. if (existing && existing.id != null) {
  7698. existingIdIdxMap.set(existing.id, index);
  7699. } // For non-internal-componnets:
  7700. // Mode "normalMerge": all existings kept.
  7701. // Mode "replaceMerge": all existing removed unless mapped by id.
  7702. // For internal-components:
  7703. // go with "replaceMerge" approach in both mode.
  7704. result.push({
  7705. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7706. newOption: null,
  7707. keyInfo: null,
  7708. brandNew: null
  7709. });
  7710. }
  7711. return result;
  7712. }
  7713. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7714. // Mapping by id if specified.
  7715. each(newCmptOptions, function (cmptOption, index) {
  7716. if (!cmptOption || cmptOption.id == null) {
  7717. return;
  7718. }
  7719. var optionId = makeComparableKey(cmptOption.id);
  7720. var existingIdx = existingIdIdxMap.get(optionId);
  7721. if (existingIdx != null) {
  7722. var resultItem = result[existingIdx];
  7723. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7724. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7725. // the existings rather than creating new component model.
  7726. resultItem.existing = existings[existingIdx];
  7727. newCmptOptions[index] = null;
  7728. }
  7729. });
  7730. }
  7731. function mappingByName(result, newCmptOptions) {
  7732. // Mapping by name if specified.
  7733. each(newCmptOptions, function (cmptOption, index) {
  7734. if (!cmptOption || cmptOption.name == null) {
  7735. return;
  7736. }
  7737. for (var i = 0; i < result.length; i++) {
  7738. var existing = result[i].existing;
  7739. if (!result[i].newOption // Consider name: two map to one.
  7740. // Can not match when both ids existing but different.
  7741. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  7742. result[i].newOption = cmptOption;
  7743. newCmptOptions[index] = null;
  7744. return;
  7745. }
  7746. }
  7747. });
  7748. }
  7749. function mappingByIndex(result, newCmptOptions, brandNew) {
  7750. each(newCmptOptions, function (cmptOption) {
  7751. if (!cmptOption) {
  7752. return;
  7753. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  7754. var resultItem;
  7755. var nextIdx = 0;
  7756. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  7757. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  7758. // after mapping performed, model will always be assigned with an id if user not given.
  7759. // After that all models have id.
  7760. // (2) If new option has id, it can only set to a hole or append to the last. It should
  7761. // not be merged to the existings with different id. Because id should not be overwritten.
  7762. // (3) Name can be overwritten, because axis use name as 'show label text'.
  7763. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  7764. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  7765. nextIdx++;
  7766. }
  7767. if (resultItem) {
  7768. resultItem.newOption = cmptOption;
  7769. resultItem.brandNew = brandNew;
  7770. } else {
  7771. result.push({
  7772. newOption: cmptOption,
  7773. brandNew: brandNew,
  7774. existing: null,
  7775. keyInfo: null
  7776. });
  7777. }
  7778. nextIdx++;
  7779. });
  7780. }
  7781. function mappingInReplaceAllMode(result, newCmptOptions) {
  7782. each(newCmptOptions, function (cmptOption) {
  7783. // The feature "reproduce" requires "hole" will also reproduced
  7784. // in case that compoennt index referring are broken.
  7785. result.push({
  7786. newOption: cmptOption,
  7787. brandNew: true,
  7788. existing: null,
  7789. keyInfo: null
  7790. });
  7791. });
  7792. }
  7793. /**
  7794. * Make id and name for mapping result (result of mappingToExists)
  7795. * into `keyInfo` field.
  7796. */
  7797. function makeIdAndName(mapResult) {
  7798. // We use this id to hash component models and view instances
  7799. // in echarts. id can be specified by user, or auto generated.
  7800. // The id generation rule ensures new view instance are able
  7801. // to mapped to old instance when setOption are called in
  7802. // no-merge mode. So we generate model id by name and plus
  7803. // type in view id.
  7804. // name can be duplicated among components, which is convenient
  7805. // to specify multi components (like series) by one name.
  7806. // Ensure that each id is distinct.
  7807. var idMap = createHashMap();
  7808. each(mapResult, function (item) {
  7809. var existing = item.existing;
  7810. existing && idMap.set(existing.id, item);
  7811. });
  7812. each(mapResult, function (item) {
  7813. var opt = item.newOption; // Force ensure id not duplicated.
  7814. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  7815. opt && opt.id != null && idMap.set(opt.id, item);
  7816. !item.keyInfo && (item.keyInfo = {});
  7817. }); // Make name and id.
  7818. each(mapResult, function (item, index) {
  7819. var existing = item.existing;
  7820. var opt = item.newOption;
  7821. var keyInfo = item.keyInfo;
  7822. if (!isObject(opt)) {
  7823. return;
  7824. } // name can be overwitten. Consider case: axis.name = '20km'.
  7825. // But id generated by name will not be changed, which affect
  7826. // only in that case: setOption with 'not merge mode' and view
  7827. // instance will be recreated, which can be accepted.
  7828. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid diffferent series has the same name,
  7829. // because name may be used like in color pallet.
  7830. : DUMMY_COMPONENT_NAME_PREFIX + index;
  7831. if (existing) {
  7832. keyInfo.id = makeComparableKey(existing.id);
  7833. } else if (opt.id != null) {
  7834. keyInfo.id = makeComparableKey(opt.id);
  7835. } else {
  7836. // Consider this situatoin:
  7837. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  7838. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  7839. // Series with the same name between optionA and optionB
  7840. // should be mapped.
  7841. var idNum = 0;
  7842. do {
  7843. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  7844. } while (idMap.get(keyInfo.id));
  7845. }
  7846. idMap.set(keyInfo.id, item);
  7847. });
  7848. }
  7849. function keyExistAndEqual(attr, obj1, obj2) {
  7850. var key1 = convertOptionIdName(obj1[attr], null);
  7851. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  7852. return key1 != null && key2 != null && key1 === key2;
  7853. }
  7854. /**
  7855. * @return return null if not exist.
  7856. */
  7857. function makeComparableKey(val) {
  7858. if ("development" !== 'production') {
  7859. if (val == null) {
  7860. throw new Error();
  7861. }
  7862. }
  7863. return convertOptionIdName(val, '');
  7864. }
  7865. function convertOptionIdName(idOrName, defaultValue) {
  7866. if (idOrName == null) {
  7867. return defaultValue;
  7868. }
  7869. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  7870. }
  7871. function warnInvalidateIdOrName(idOrName) {
  7872. if ("development" !== 'production') {
  7873. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  7874. }
  7875. }
  7876. function isValidIdOrName(idOrName) {
  7877. return isStringSafe(idOrName) || isNumeric(idOrName);
  7878. }
  7879. function isNameSpecified(componentModel) {
  7880. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  7881. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  7882. }
  7883. /**
  7884. * @public
  7885. * @param {Object} cmptOption
  7886. * @return {boolean}
  7887. */
  7888. function isComponentIdInternal(cmptOption) {
  7889. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  7890. }
  7891. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  7892. // Set mainType and complete subType.
  7893. each(mappingResult, function (item) {
  7894. var newOption = item.newOption;
  7895. if (isObject(newOption)) {
  7896. item.keyInfo.mainType = mainType;
  7897. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  7898. }
  7899. });
  7900. }
  7901. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  7902. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  7903. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  7904. return subType;
  7905. }
  7906. /**
  7907. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  7908. * each of which can be Array or primary type.
  7909. * @return dataIndex If not found, return undefined/null.
  7910. */
  7911. function queryDataIndex(data, payload) {
  7912. if (payload.dataIndexInside != null) {
  7913. return payload.dataIndexInside;
  7914. } else if (payload.dataIndex != null) {
  7915. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  7916. return data.indexOfRawIndex(value);
  7917. }) : data.indexOfRawIndex(payload.dataIndex);
  7918. } else if (payload.name != null) {
  7919. return isArray(payload.name) ? map(payload.name, function (value) {
  7920. return data.indexOfName(value);
  7921. }) : data.indexOfName(payload.name);
  7922. }
  7923. }
  7924. /**
  7925. * Enable property storage to any host object.
  7926. * Notice: Serialization is not supported.
  7927. *
  7928. * For example:
  7929. * let inner = zrUitl.makeInner();
  7930. *
  7931. * function some1(hostObj) {
  7932. * inner(hostObj).someProperty = 1212;
  7933. * ...
  7934. * }
  7935. * function some2() {
  7936. * let fields = inner(this);
  7937. * fields.someProperty1 = 1212;
  7938. * fields.someProperty2 = 'xx';
  7939. * ...
  7940. * }
  7941. *
  7942. * @return {Function}
  7943. */
  7944. function makeInner() {
  7945. var key = '__ec_inner_' + innerUniqueIndex++;
  7946. return function (hostObj) {
  7947. return hostObj[key] || (hostObj[key] = {});
  7948. };
  7949. }
  7950. var innerUniqueIndex = getRandomIdBase();
  7951. /**
  7952. * The same behavior as `component.getReferringComponents`.
  7953. */
  7954. function parseFinder(ecModel, finderInput, opt) {
  7955. var _a = preParseFinder(finderInput, opt),
  7956. mainTypeSpecified = _a.mainTypeSpecified,
  7957. queryOptionMap = _a.queryOptionMap,
  7958. others = _a.others;
  7959. var result = others;
  7960. var defaultMainType = opt ? opt.defaultMainType : null;
  7961. if (!mainTypeSpecified && defaultMainType) {
  7962. queryOptionMap.set(defaultMainType, {});
  7963. }
  7964. queryOptionMap.each(function (queryOption, mainType) {
  7965. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  7966. useDefault: defaultMainType === mainType,
  7967. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  7968. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  7969. });
  7970. result[mainType + 'Models'] = queryResult.models;
  7971. result[mainType + 'Model'] = queryResult.models[0];
  7972. });
  7973. return result;
  7974. }
  7975. function preParseFinder(finderInput, opt) {
  7976. var finder;
  7977. if (isString(finderInput)) {
  7978. var obj = {};
  7979. obj[finderInput + 'Index'] = 0;
  7980. finder = obj;
  7981. } else {
  7982. finder = finderInput;
  7983. }
  7984. var queryOptionMap = createHashMap();
  7985. var others = {};
  7986. var mainTypeSpecified = false;
  7987. each(finder, function (value, key) {
  7988. // Exclude 'dataIndex' and other illgal keys.
  7989. if (key === 'dataIndex' || key === 'dataIndexInside') {
  7990. others[key] = value;
  7991. return;
  7992. }
  7993. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  7994. var mainType = parsedKey[1];
  7995. var queryType = (parsedKey[2] || '').toLowerCase();
  7996. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  7997. return;
  7998. }
  7999. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8000. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8001. queryOption[queryType] = value;
  8002. });
  8003. return {
  8004. mainTypeSpecified: mainTypeSpecified,
  8005. queryOptionMap: queryOptionMap,
  8006. others: others
  8007. };
  8008. }
  8009. var SINGLE_REFERRING = {
  8010. useDefault: true,
  8011. enableAll: false,
  8012. enableNone: false
  8013. };
  8014. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8015. opt = opt || SINGLE_REFERRING;
  8016. var indexOption = userOption.index;
  8017. var idOption = userOption.id;
  8018. var nameOption = userOption.name;
  8019. var result = {
  8020. models: null,
  8021. specified: indexOption != null || idOption != null || nameOption != null
  8022. };
  8023. if (!result.specified) {
  8024. // Use the first as default if `useDefault`.
  8025. var firstCmpt = void 0;
  8026. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8027. return result;
  8028. }
  8029. if (indexOption === 'none' || indexOption === false) {
  8030. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8031. result.models = [];
  8032. return result;
  8033. } // `queryComponents` will return all components if
  8034. // both all of index/id/name are null/undefined.
  8035. if (indexOption === 'all') {
  8036. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8037. indexOption = idOption = nameOption = null;
  8038. }
  8039. result.models = ecModel.queryComponents({
  8040. mainType: mainType,
  8041. index: indexOption,
  8042. id: idOption,
  8043. name: nameOption
  8044. });
  8045. return result;
  8046. }
  8047. function setAttribute(dom, key, value) {
  8048. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8049. }
  8050. function getAttribute(dom, key) {
  8051. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8052. }
  8053. /**
  8054. * Interpolate raw values of a series with percent
  8055. *
  8056. * @param data data
  8057. * @param labelModel label model of the text element
  8058. * @param sourceValue start value. May be null/undefined when init.
  8059. * @param targetValue end value
  8060. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8061. * @return interpolated values
  8062. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8063. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8064. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8065. * Other cases do not supported.
  8066. */
  8067. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8068. var isAutoPrecision = precision == null || precision === 'auto';
  8069. if (targetValue == null) {
  8070. return targetValue;
  8071. }
  8072. if (isNumber(targetValue)) {
  8073. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8074. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8075. } else if (isString(targetValue)) {
  8076. return percent < 1 ? sourceValue : targetValue;
  8077. } else {
  8078. var interpolated = [];
  8079. var leftArr = sourceValue;
  8080. var rightArr = targetValue;
  8081. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8082. for (var i = 0; i < length_1; ++i) {
  8083. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  8084. if (info && info.type === 'ordinal') {
  8085. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8086. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8087. } else {
  8088. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8089. var rightVal = rightArr[i];
  8090. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8091. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8092. }
  8093. }
  8094. return interpolated;
  8095. }
  8096. }
  8097. var TYPE_DELIMITER = '.';
  8098. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8099. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8100. /**
  8101. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8102. * @public
  8103. */
  8104. function parseClassType(componentType) {
  8105. var ret = {
  8106. main: '',
  8107. sub: ''
  8108. };
  8109. if (componentType) {
  8110. var typeArr = componentType.split(TYPE_DELIMITER);
  8111. ret.main = typeArr[0] || '';
  8112. ret.sub = typeArr[1] || '';
  8113. }
  8114. return ret;
  8115. }
  8116. /**
  8117. * @public
  8118. */
  8119. function checkClassType(componentType) {
  8120. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8121. }
  8122. function isExtendedClass(clz) {
  8123. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8124. }
  8125. /**
  8126. * Implements `ExtendableConstructor` for `rootClz`.
  8127. *
  8128. * @usage
  8129. * ```ts
  8130. * class Xxx {}
  8131. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8132. * enableClassExtend(Xxx as XxxConstructor);
  8133. * ```
  8134. */
  8135. function enableClassExtend(rootClz, mandatoryMethods) {
  8136. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8137. rootClz.extend = function (proto) {
  8138. if ("development" !== 'production') {
  8139. each(mandatoryMethods, function (method) {
  8140. if (!proto[method]) {
  8141. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8142. }
  8143. });
  8144. }
  8145. var superClass = this;
  8146. var ExtendedClass;
  8147. if (isESClass(superClass)) {
  8148. ExtendedClass =
  8149. /** @class */
  8150. function (_super) {
  8151. __extends(class_1, _super);
  8152. function class_1() {
  8153. return _super.apply(this, arguments) || this;
  8154. }
  8155. return class_1;
  8156. }(superClass);
  8157. } else {
  8158. // For backward compat, we both support ts class inheritance and this
  8159. // "extend" approach.
  8160. // The constructor should keep the same behavior as ts class inheritance:
  8161. // If this constructor/$constructor is not declared, auto invoke the super
  8162. // constructor.
  8163. // If this constructor/$constructor is declared, it is responsible for
  8164. // calling the super constructor.
  8165. ExtendedClass = function () {
  8166. (proto.$constructor || superClass).apply(this, arguments);
  8167. };
  8168. inherits(ExtendedClass, this);
  8169. }
  8170. extend(ExtendedClass.prototype, proto);
  8171. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8172. ExtendedClass.extend = this.extend;
  8173. ExtendedClass.superCall = superCall;
  8174. ExtendedClass.superApply = superApply;
  8175. ExtendedClass.superClass = superClass;
  8176. return ExtendedClass;
  8177. };
  8178. }
  8179. function isESClass(fn) {
  8180. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8181. }
  8182. /**
  8183. * A work around to both support ts extend and this extend mechanism.
  8184. * on sub-class.
  8185. * @usage
  8186. * ```ts
  8187. * class Component { ... }
  8188. * classUtil.enableClassExtend(Component);
  8189. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8190. *
  8191. * class Series extends Component { ... }
  8192. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8193. * Component.markExtend(Series);
  8194. * ```
  8195. */
  8196. function mountExtend(SubClz, SupperClz) {
  8197. SubClz.extend = SupperClz.extend;
  8198. } // A random offset.
  8199. var classBase = Math.round(Math.random() * 10);
  8200. /**
  8201. * Implements `CheckableConstructor` for `target`.
  8202. * Can not use instanceof, consider different scope by
  8203. * cross domain or es module import in ec extensions.
  8204. * Mount a method "isInstance()" to Clz.
  8205. *
  8206. * @usage
  8207. * ```ts
  8208. * class Xxx {}
  8209. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8210. * enableClassCheck(Xxx as XxxConstructor)
  8211. * ```
  8212. */
  8213. function enableClassCheck(target) {
  8214. var classAttr = ['__\0is_clz', classBase++].join('_');
  8215. target.prototype[classAttr] = true;
  8216. if ("development" !== 'production') {
  8217. assert(!target.isInstance, 'The method "is" can not be defined.');
  8218. }
  8219. target.isInstance = function (obj) {
  8220. return !!(obj && obj[classAttr]);
  8221. };
  8222. } // superCall should have class info, which can not be fetch from 'this'.
  8223. // Consider this case:
  8224. // class A has method f,
  8225. // class B inherits class A, overrides method f, f call superApply('f'),
  8226. // class C inherits class B, do not overrides method f,
  8227. // then when method of class C is called, dead loop occured.
  8228. function superCall(context, methodName) {
  8229. var args = [];
  8230. for (var _i = 2; _i < arguments.length; _i++) {
  8231. args[_i - 2] = arguments[_i];
  8232. }
  8233. return this.superClass.prototype[methodName].apply(context, args);
  8234. }
  8235. function superApply(context, methodName, args) {
  8236. return this.superClass.prototype[methodName].apply(context, args);
  8237. }
  8238. /**
  8239. * Implements `ClassManager` for `target`
  8240. *
  8241. * @usage
  8242. * ```ts
  8243. * class Xxx {}
  8244. * type XxxConstructor = typeof Xxx & ClassManager
  8245. * enableClassManagement(Xxx as XxxConstructor);
  8246. * ```
  8247. */
  8248. function enableClassManagement(target) {
  8249. /**
  8250. * Component model classes
  8251. * key: componentType,
  8252. * value:
  8253. * componentClass, when componentType is 'a'
  8254. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8255. */
  8256. var storage = {};
  8257. target.registerClass = function (clz) {
  8258. // `type` should not be a "instance memeber".
  8259. // If using TS class, should better declared as `static type = 'series.pie'`.
  8260. // otherwise users have to mount `type` on prototype manually.
  8261. // For backward compat and enable instance visit type via `this.type`,
  8262. // we stil support fetch `type` from prototype.
  8263. var componentFullType = clz.type || clz.prototype.type;
  8264. if (componentFullType) {
  8265. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  8266. clz.prototype.type = componentFullType;
  8267. var componentTypeInfo = parseClassType(componentFullType);
  8268. if (!componentTypeInfo.sub) {
  8269. if ("development" !== 'production') {
  8270. if (storage[componentTypeInfo.main]) {
  8271. console.warn(componentTypeInfo.main + ' exists.');
  8272. }
  8273. }
  8274. storage[componentTypeInfo.main] = clz;
  8275. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8276. var container = makeContainer(componentTypeInfo);
  8277. container[componentTypeInfo.sub] = clz;
  8278. }
  8279. }
  8280. return clz;
  8281. };
  8282. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8283. var clz = storage[mainType];
  8284. if (clz && clz[IS_CONTAINER]) {
  8285. clz = subType ? clz[subType] : null;
  8286. }
  8287. if (throwWhenNotFound && !clz) {
  8288. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8289. }
  8290. return clz;
  8291. };
  8292. target.getClassesByMainType = function (componentType) {
  8293. var componentTypeInfo = parseClassType(componentType);
  8294. var result = [];
  8295. var obj = storage[componentTypeInfo.main];
  8296. if (obj && obj[IS_CONTAINER]) {
  8297. each(obj, function (o, type) {
  8298. type !== IS_CONTAINER && result.push(o);
  8299. });
  8300. } else {
  8301. result.push(obj);
  8302. }
  8303. return result;
  8304. };
  8305. target.hasClass = function (componentType) {
  8306. // Just consider componentType.main.
  8307. var componentTypeInfo = parseClassType(componentType);
  8308. return !!storage[componentTypeInfo.main];
  8309. };
  8310. /**
  8311. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8312. */
  8313. target.getAllClassMainTypes = function () {
  8314. var types = [];
  8315. each(storage, function (obj, type) {
  8316. types.push(type);
  8317. });
  8318. return types;
  8319. };
  8320. /**
  8321. * If a main type is container and has sub types
  8322. */
  8323. target.hasSubTypes = function (componentType) {
  8324. var componentTypeInfo = parseClassType(componentType);
  8325. var obj = storage[componentTypeInfo.main];
  8326. return obj && obj[IS_CONTAINER];
  8327. };
  8328. function makeContainer(componentTypeInfo) {
  8329. var container = storage[componentTypeInfo.main];
  8330. if (!container || !container[IS_CONTAINER]) {
  8331. container = storage[componentTypeInfo.main] = {};
  8332. container[IS_CONTAINER] = true;
  8333. }
  8334. return container;
  8335. }
  8336. } // /**
  8337. // * @param {string|Array.<string>} properties
  8338. // */
  8339. // export function setReadOnly(obj, properties) {
  8340. // FIXME It seems broken in IE8 simulation of IE11
  8341. // if (!zrUtil.isArray(properties)) {
  8342. // properties = properties != null ? [properties] : [];
  8343. // }
  8344. // zrUtil.each(properties, function (prop) {
  8345. // let value = obj[prop];
  8346. // Object.defineProperty
  8347. // && Object.defineProperty(obj, prop, {
  8348. // value: value, writable: false
  8349. // });
  8350. // zrUtil.isArray(obj[prop])
  8351. // && Object.freeze
  8352. // && Object.freeze(obj[prop]);
  8353. // });
  8354. // }
  8355. function makeStyleMapper(properties, ignoreParent) {
  8356. // Normalize
  8357. for (var i = 0; i < properties.length; i++) {
  8358. if (!properties[i][1]) {
  8359. properties[i][1] = properties[i][0];
  8360. }
  8361. }
  8362. ignoreParent = ignoreParent || false;
  8363. return function (model, excludes, includes) {
  8364. var style = {};
  8365. for (var i = 0; i < properties.length; i++) {
  8366. var propName = properties[i][1];
  8367. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8368. continue;
  8369. }
  8370. var val = model.getShallow(propName, ignoreParent);
  8371. if (val != null) {
  8372. style[properties[i][0]] = val;
  8373. }
  8374. } // TODO Text or image?
  8375. return style;
  8376. };
  8377. }
  8378. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8379. // So do not transfer decal directly.
  8380. ];
  8381. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8382. var AreaStyleMixin =
  8383. /** @class */
  8384. function () {
  8385. function AreaStyleMixin() {}
  8386. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8387. return getAreaStyle(this, excludes, includes);
  8388. };
  8389. return AreaStyleMixin;
  8390. }();
  8391. var globalImageCache = new LRU(50);
  8392. function findExistImage(newImageOrSrc) {
  8393. if (typeof newImageOrSrc === 'string') {
  8394. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8395. return cachedImgObj && cachedImgObj.image;
  8396. }
  8397. else {
  8398. return newImageOrSrc;
  8399. }
  8400. }
  8401. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8402. if (!newImageOrSrc) {
  8403. return image;
  8404. }
  8405. else if (typeof newImageOrSrc === 'string') {
  8406. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8407. return image;
  8408. }
  8409. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8410. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8411. if (cachedImgObj) {
  8412. image = cachedImgObj.image;
  8413. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8414. }
  8415. else {
  8416. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8417. image.__zrImageSrc = newImageOrSrc;
  8418. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8419. image: image,
  8420. pending: [pendingWrap]
  8421. });
  8422. }
  8423. return image;
  8424. }
  8425. else {
  8426. return newImageOrSrc;
  8427. }
  8428. }
  8429. function imageOnLoad() {
  8430. var cachedImgObj = this.__cachedImgObj;
  8431. this.onload = this.onerror = this.__cachedImgObj = null;
  8432. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8433. var pendingWrap = cachedImgObj.pending[i];
  8434. var cb = pendingWrap.cb;
  8435. cb && cb(this, pendingWrap.cbPayload);
  8436. pendingWrap.hostEl.dirty();
  8437. }
  8438. cachedImgObj.pending.length = 0;
  8439. }
  8440. function isImageReady(image) {
  8441. return image && image.width && image.height;
  8442. }
  8443. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8444. function truncateText(text, containerWidth, font, ellipsis, options) {
  8445. if (!containerWidth) {
  8446. return '';
  8447. }
  8448. var textLines = (text + '').split('\n');
  8449. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8450. for (var i = 0, len = textLines.length; i < len; i++) {
  8451. textLines[i] = truncateSingleLine(textLines[i], options);
  8452. }
  8453. return textLines.join('\n');
  8454. }
  8455. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8456. options = options || {};
  8457. var preparedOpts = extend({}, options);
  8458. preparedOpts.font = font;
  8459. ellipsis = retrieve2(ellipsis, '...');
  8460. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8461. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8462. preparedOpts.cnCharWidth = getWidth('国', font);
  8463. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8464. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8465. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8466. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8467. contentWidth -= ascCharWidth;
  8468. }
  8469. var ellipsisWidth = getWidth(ellipsis, font);
  8470. if (ellipsisWidth > contentWidth) {
  8471. ellipsis = '';
  8472. ellipsisWidth = 0;
  8473. }
  8474. contentWidth = containerWidth - ellipsisWidth;
  8475. preparedOpts.ellipsis = ellipsis;
  8476. preparedOpts.ellipsisWidth = ellipsisWidth;
  8477. preparedOpts.contentWidth = contentWidth;
  8478. preparedOpts.containerWidth = containerWidth;
  8479. return preparedOpts;
  8480. }
  8481. function truncateSingleLine(textLine, options) {
  8482. var containerWidth = options.containerWidth;
  8483. var font = options.font;
  8484. var contentWidth = options.contentWidth;
  8485. if (!containerWidth) {
  8486. return '';
  8487. }
  8488. var lineWidth = getWidth(textLine, font);
  8489. if (lineWidth <= containerWidth) {
  8490. return textLine;
  8491. }
  8492. for (var j = 0;; j++) {
  8493. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8494. textLine += options.ellipsis;
  8495. break;
  8496. }
  8497. var subLength = j === 0
  8498. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8499. : lineWidth > 0
  8500. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8501. : 0;
  8502. textLine = textLine.substr(0, subLength);
  8503. lineWidth = getWidth(textLine, font);
  8504. }
  8505. if (textLine === '') {
  8506. textLine = options.placeholder;
  8507. }
  8508. return textLine;
  8509. }
  8510. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8511. var width = 0;
  8512. var i = 0;
  8513. for (var len = text.length; i < len && width < contentWidth; i++) {
  8514. var charCode = text.charCodeAt(i);
  8515. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8516. }
  8517. return i;
  8518. }
  8519. function parsePlainText(text, style) {
  8520. text != null && (text += '');
  8521. var overflow = style.overflow;
  8522. var padding = style.padding;
  8523. var font = style.font;
  8524. var truncate = overflow === 'truncate';
  8525. var calculatedLineHeight = getLineHeight(font);
  8526. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8527. var bgColorDrawn = !!(style.backgroundColor);
  8528. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8529. var width = style.width;
  8530. var lines;
  8531. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8532. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8533. }
  8534. else {
  8535. lines = text ? text.split('\n') : [];
  8536. }
  8537. var contentHeight = lines.length * lineHeight;
  8538. var height = retrieve2(style.height, contentHeight);
  8539. if (contentHeight > height && truncateLineOverflow) {
  8540. var lineCount = Math.floor(height / lineHeight);
  8541. lines = lines.slice(0, lineCount);
  8542. }
  8543. if (text && truncate && width != null) {
  8544. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8545. minChar: style.truncateMinChar,
  8546. placeholder: style.placeholder
  8547. });
  8548. for (var i = 0; i < lines.length; i++) {
  8549. lines[i] = truncateSingleLine(lines[i], options);
  8550. }
  8551. }
  8552. var outerHeight = height;
  8553. var contentWidth = 0;
  8554. for (var i = 0; i < lines.length; i++) {
  8555. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8556. }
  8557. if (width == null) {
  8558. width = contentWidth;
  8559. }
  8560. var outerWidth = contentWidth;
  8561. if (padding) {
  8562. outerHeight += padding[0] + padding[2];
  8563. outerWidth += padding[1] + padding[3];
  8564. width += padding[1] + padding[3];
  8565. }
  8566. if (bgColorDrawn) {
  8567. outerWidth = width;
  8568. }
  8569. return {
  8570. lines: lines,
  8571. height: height,
  8572. outerWidth: outerWidth,
  8573. outerHeight: outerHeight,
  8574. lineHeight: lineHeight,
  8575. calculatedLineHeight: calculatedLineHeight,
  8576. contentWidth: contentWidth,
  8577. contentHeight: contentHeight,
  8578. width: width
  8579. };
  8580. }
  8581. var RichTextToken = (function () {
  8582. function RichTextToken() {
  8583. }
  8584. return RichTextToken;
  8585. }());
  8586. var RichTextLine = (function () {
  8587. function RichTextLine(tokens) {
  8588. this.tokens = [];
  8589. if (tokens) {
  8590. this.tokens = tokens;
  8591. }
  8592. }
  8593. return RichTextLine;
  8594. }());
  8595. var RichTextContentBlock = (function () {
  8596. function RichTextContentBlock() {
  8597. this.width = 0;
  8598. this.height = 0;
  8599. this.contentWidth = 0;
  8600. this.contentHeight = 0;
  8601. this.outerWidth = 0;
  8602. this.outerHeight = 0;
  8603. this.lines = [];
  8604. }
  8605. return RichTextContentBlock;
  8606. }());
  8607. function parseRichText(text, style) {
  8608. var contentBlock = new RichTextContentBlock();
  8609. text != null && (text += '');
  8610. if (!text) {
  8611. return contentBlock;
  8612. }
  8613. var topWidth = style.width;
  8614. var topHeight = style.height;
  8615. var overflow = style.overflow;
  8616. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8617. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8618. : null;
  8619. var lastIndex = STYLE_REG.lastIndex = 0;
  8620. var result;
  8621. while ((result = STYLE_REG.exec(text)) != null) {
  8622. var matchedIndex = result.index;
  8623. if (matchedIndex > lastIndex) {
  8624. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8625. }
  8626. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8627. lastIndex = STYLE_REG.lastIndex;
  8628. }
  8629. if (lastIndex < text.length) {
  8630. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8631. }
  8632. var pendingList = [];
  8633. var calculatedHeight = 0;
  8634. var calculatedWidth = 0;
  8635. var stlPadding = style.padding;
  8636. var truncate = overflow === 'truncate';
  8637. var truncateLine = style.lineOverflow === 'truncate';
  8638. function finishLine(line, lineWidth, lineHeight) {
  8639. line.width = lineWidth;
  8640. line.lineHeight = lineHeight;
  8641. calculatedHeight += lineHeight;
  8642. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8643. }
  8644. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8645. var line = contentBlock.lines[i];
  8646. var lineHeight = 0;
  8647. var lineWidth = 0;
  8648. for (var j = 0; j < line.tokens.length; j++) {
  8649. var token = line.tokens[j];
  8650. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8651. var textPadding = token.textPadding = tokenStyle.padding;
  8652. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8653. var font = token.font = tokenStyle.font || style.font;
  8654. token.contentHeight = getLineHeight(font);
  8655. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8656. token.innerHeight = tokenHeight;
  8657. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8658. token.height = tokenHeight;
  8659. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8660. token.align = tokenStyle && tokenStyle.align || style.align;
  8661. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8662. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8663. if (j > 0) {
  8664. line.tokens = line.tokens.slice(0, j);
  8665. finishLine(line, lineWidth, lineHeight);
  8666. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8667. }
  8668. else {
  8669. contentBlock.lines = contentBlock.lines.slice(0, i);
  8670. }
  8671. break outer;
  8672. }
  8673. var styleTokenWidth = tokenStyle.width;
  8674. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8675. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8676. token.percentWidth = styleTokenWidth;
  8677. pendingList.push(token);
  8678. token.contentWidth = getWidth(token.text, font);
  8679. }
  8680. else {
  8681. if (tokenWidthNotSpecified) {
  8682. var textBackgroundColor = tokenStyle.backgroundColor;
  8683. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8684. if (bgImg) {
  8685. bgImg = findExistImage(bgImg);
  8686. if (isImageReady(bgImg)) {
  8687. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8688. }
  8689. }
  8690. }
  8691. var remainTruncWidth = truncate && topWidth != null
  8692. ? topWidth - lineWidth : null;
  8693. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8694. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8695. token.text = '';
  8696. token.width = token.contentWidth = 0;
  8697. }
  8698. else {
  8699. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8700. token.width = token.contentWidth = getWidth(token.text, font);
  8701. }
  8702. }
  8703. else {
  8704. token.contentWidth = getWidth(token.text, font);
  8705. }
  8706. }
  8707. token.width += paddingH;
  8708. lineWidth += token.width;
  8709. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8710. }
  8711. finishLine(line, lineWidth, lineHeight);
  8712. }
  8713. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8714. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8715. contentBlock.contentHeight = calculatedHeight;
  8716. contentBlock.contentWidth = calculatedWidth;
  8717. if (stlPadding) {
  8718. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  8719. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  8720. }
  8721. for (var i = 0; i < pendingList.length; i++) {
  8722. var token = pendingList[i];
  8723. var percentWidth = token.percentWidth;
  8724. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  8725. }
  8726. return contentBlock;
  8727. }
  8728. function pushTokens(block, str, style, wrapInfo, styleName) {
  8729. var isEmptyStr = str === '';
  8730. var tokenStyle = styleName && style.rich[styleName] || {};
  8731. var lines = block.lines;
  8732. var font = tokenStyle.font || style.font;
  8733. var newLine = false;
  8734. var strLines;
  8735. var linesWidths;
  8736. if (wrapInfo) {
  8737. var tokenPadding = tokenStyle.padding;
  8738. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  8739. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  8740. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  8741. if (lines.length > 0) {
  8742. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  8743. strLines = str.split('\n');
  8744. newLine = true;
  8745. }
  8746. }
  8747. wrapInfo.accumWidth = outerWidth_1;
  8748. }
  8749. else {
  8750. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  8751. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  8752. linesWidths = res.linesWidths;
  8753. strLines = res.lines;
  8754. }
  8755. }
  8756. else {
  8757. strLines = str.split('\n');
  8758. }
  8759. for (var i = 0; i < strLines.length; i++) {
  8760. var text = strLines[i];
  8761. var token = new RichTextToken();
  8762. token.styleName = styleName;
  8763. token.text = text;
  8764. token.isLineHolder = !text && !isEmptyStr;
  8765. if (typeof tokenStyle.width === 'number') {
  8766. token.width = tokenStyle.width;
  8767. }
  8768. else {
  8769. token.width = linesWidths
  8770. ? linesWidths[i]
  8771. : getWidth(text, font);
  8772. }
  8773. if (!i && !newLine) {
  8774. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  8775. var tokensLen = tokens.length;
  8776. (tokensLen === 1 && tokens[0].isLineHolder)
  8777. ? (tokens[0] = token)
  8778. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  8779. }
  8780. else {
  8781. lines.push(new RichTextLine([token]));
  8782. }
  8783. }
  8784. }
  8785. function isLatin(ch) {
  8786. var code = ch.charCodeAt(0);
  8787. return code >= 0x21 && code <= 0x17F;
  8788. }
  8789. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  8790. obj[ch] = true;
  8791. return obj;
  8792. }, {});
  8793. function isWordBreakChar(ch) {
  8794. if (isLatin(ch)) {
  8795. if (breakCharMap[ch]) {
  8796. return true;
  8797. }
  8798. return false;
  8799. }
  8800. return true;
  8801. }
  8802. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  8803. var lines = [];
  8804. var linesWidths = [];
  8805. var line = '';
  8806. var currentWord = '';
  8807. var currentWordWidth = 0;
  8808. var accumWidth = 0;
  8809. for (var i = 0; i < text.length; i++) {
  8810. var ch = text.charAt(i);
  8811. if (ch === '\n') {
  8812. if (currentWord) {
  8813. line += currentWord;
  8814. accumWidth += currentWordWidth;
  8815. }
  8816. lines.push(line);
  8817. linesWidths.push(accumWidth);
  8818. line = '';
  8819. currentWord = '';
  8820. currentWordWidth = 0;
  8821. accumWidth = 0;
  8822. continue;
  8823. }
  8824. var chWidth = getWidth(ch, font);
  8825. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  8826. if (!lines.length
  8827. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  8828. : accumWidth + chWidth > lineWidth) {
  8829. if (!accumWidth) {
  8830. if (inWord) {
  8831. lines.push(currentWord);
  8832. linesWidths.push(currentWordWidth);
  8833. currentWord = ch;
  8834. currentWordWidth = chWidth;
  8835. }
  8836. else {
  8837. lines.push(ch);
  8838. linesWidths.push(chWidth);
  8839. }
  8840. }
  8841. else if (line || currentWord) {
  8842. if (inWord) {
  8843. if (!line) {
  8844. line = currentWord;
  8845. currentWord = '';
  8846. currentWordWidth = 0;
  8847. accumWidth = currentWordWidth;
  8848. }
  8849. lines.push(line);
  8850. linesWidths.push(accumWidth - currentWordWidth);
  8851. currentWord += ch;
  8852. currentWordWidth += chWidth;
  8853. line = '';
  8854. accumWidth = currentWordWidth;
  8855. }
  8856. else {
  8857. if (currentWord) {
  8858. line += currentWord;
  8859. currentWord = '';
  8860. currentWordWidth = 0;
  8861. }
  8862. lines.push(line);
  8863. linesWidths.push(accumWidth);
  8864. line = ch;
  8865. accumWidth = chWidth;
  8866. }
  8867. }
  8868. continue;
  8869. }
  8870. accumWidth += chWidth;
  8871. if (inWord) {
  8872. currentWord += ch;
  8873. currentWordWidth += chWidth;
  8874. }
  8875. else {
  8876. if (currentWord) {
  8877. line += currentWord;
  8878. currentWord = '';
  8879. currentWordWidth = 0;
  8880. }
  8881. line += ch;
  8882. }
  8883. }
  8884. if (!lines.length && !line) {
  8885. line = text;
  8886. currentWord = '';
  8887. currentWordWidth = 0;
  8888. }
  8889. if (currentWord) {
  8890. line += currentWord;
  8891. }
  8892. if (line) {
  8893. lines.push(line);
  8894. linesWidths.push(accumWidth);
  8895. }
  8896. if (lines.length === 1) {
  8897. accumWidth += lastAccumWidth;
  8898. }
  8899. return {
  8900. accumWidth: accumWidth,
  8901. lines: lines,
  8902. linesWidths: linesWidths
  8903. };
  8904. }
  8905. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  8906. var DEFAULT_COMMON_STYLE = {
  8907. shadowBlur: 0,
  8908. shadowOffsetX: 0,
  8909. shadowOffsetY: 0,
  8910. shadowColor: '#000',
  8911. opacity: 1,
  8912. blend: 'source-over'
  8913. };
  8914. var DEFAULT_COMMON_ANIMATION_PROPS = {
  8915. style: {
  8916. shadowBlur: true,
  8917. shadowOffsetX: true,
  8918. shadowOffsetY: true,
  8919. shadowColor: true,
  8920. opacity: true
  8921. }
  8922. };
  8923. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  8924. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  8925. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  8926. var Displayable = (function (_super) {
  8927. __extends(Displayable, _super);
  8928. function Displayable(props) {
  8929. return _super.call(this, props) || this;
  8930. }
  8931. Displayable.prototype._init = function (props) {
  8932. var keysArr = keys(props);
  8933. for (var i = 0; i < keysArr.length; i++) {
  8934. var key = keysArr[i];
  8935. if (key === 'style') {
  8936. this.useStyle(props[key]);
  8937. }
  8938. else {
  8939. _super.prototype.attrKV.call(this, key, props[key]);
  8940. }
  8941. }
  8942. if (!this.style) {
  8943. this.useStyle({});
  8944. }
  8945. };
  8946. Displayable.prototype.beforeBrush = function () { };
  8947. Displayable.prototype.afterBrush = function () { };
  8948. Displayable.prototype.innerBeforeBrush = function () { };
  8949. Displayable.prototype.innerAfterBrush = function () { };
  8950. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  8951. var m = this.transform;
  8952. if (this.ignore
  8953. || this.invisible
  8954. || this.style.opacity === 0
  8955. || (this.culling
  8956. && isDisplayableCulled(this, viewWidth, viewHeight))
  8957. || (m && !m[0] && !m[3])) {
  8958. return false;
  8959. }
  8960. if (considerClipPath && this.__clipPaths) {
  8961. for (var i = 0; i < this.__clipPaths.length; ++i) {
  8962. if (this.__clipPaths[i].isZeroArea()) {
  8963. return false;
  8964. }
  8965. }
  8966. }
  8967. if (considerAncestors && this.parent) {
  8968. var parent_1 = this.parent;
  8969. while (parent_1) {
  8970. if (parent_1.ignore) {
  8971. return false;
  8972. }
  8973. parent_1 = parent_1.parent;
  8974. }
  8975. }
  8976. return true;
  8977. };
  8978. Displayable.prototype.contain = function (x, y) {
  8979. return this.rectContain(x, y);
  8980. };
  8981. Displayable.prototype.traverse = function (cb, context) {
  8982. cb.call(context, this);
  8983. };
  8984. Displayable.prototype.rectContain = function (x, y) {
  8985. var coord = this.transformCoordToLocal(x, y);
  8986. var rect = this.getBoundingRect();
  8987. return rect.contain(coord[0], coord[1]);
  8988. };
  8989. Displayable.prototype.getPaintRect = function () {
  8990. var rect = this._paintRect;
  8991. if (!this._paintRect || this.__dirty) {
  8992. var transform = this.transform;
  8993. var elRect = this.getBoundingRect();
  8994. var style = this.style;
  8995. var shadowSize = style.shadowBlur || 0;
  8996. var shadowOffsetX = style.shadowOffsetX || 0;
  8997. var shadowOffsetY = style.shadowOffsetY || 0;
  8998. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  8999. if (transform) {
  9000. BoundingRect.applyTransform(rect, elRect, transform);
  9001. }
  9002. else {
  9003. rect.copy(elRect);
  9004. }
  9005. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9006. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9007. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9008. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9009. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9010. }
  9011. var tolerance = this.dirtyRectTolerance;
  9012. if (!rect.isZero()) {
  9013. rect.x = Math.floor(rect.x - tolerance);
  9014. rect.y = Math.floor(rect.y - tolerance);
  9015. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9016. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9017. }
  9018. }
  9019. return rect;
  9020. };
  9021. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9022. if (paintRect) {
  9023. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9024. this._prevPaintRect.copy(paintRect);
  9025. }
  9026. else {
  9027. this._prevPaintRect = null;
  9028. }
  9029. };
  9030. Displayable.prototype.getPrevPaintRect = function () {
  9031. return this._prevPaintRect;
  9032. };
  9033. Displayable.prototype.animateStyle = function (loop) {
  9034. return this.animate('style', loop);
  9035. };
  9036. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9037. if (targetKey === 'style') {
  9038. this.dirtyStyle();
  9039. }
  9040. else {
  9041. this.markRedraw();
  9042. }
  9043. };
  9044. Displayable.prototype.attrKV = function (key, value) {
  9045. if (key !== 'style') {
  9046. _super.prototype.attrKV.call(this, key, value);
  9047. }
  9048. else {
  9049. if (!this.style) {
  9050. this.useStyle(value);
  9051. }
  9052. else {
  9053. this.setStyle(value);
  9054. }
  9055. }
  9056. };
  9057. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9058. if (typeof keyOrObj === 'string') {
  9059. this.style[keyOrObj] = value;
  9060. }
  9061. else {
  9062. extend(this.style, keyOrObj);
  9063. }
  9064. this.dirtyStyle();
  9065. return this;
  9066. };
  9067. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9068. if (!notRedraw) {
  9069. this.markRedraw();
  9070. }
  9071. this.__dirty |= STYLE_CHANGED_BIT;
  9072. if (this._rect) {
  9073. this._rect = null;
  9074. }
  9075. };
  9076. Displayable.prototype.dirty = function () {
  9077. this.dirtyStyle();
  9078. };
  9079. Displayable.prototype.styleChanged = function () {
  9080. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9081. };
  9082. Displayable.prototype.styleUpdated = function () {
  9083. this.__dirty &= ~STYLE_CHANGED_BIT;
  9084. };
  9085. Displayable.prototype.createStyle = function (obj) {
  9086. return createObject(DEFAULT_COMMON_STYLE, obj);
  9087. };
  9088. Displayable.prototype.useStyle = function (obj) {
  9089. if (!obj[STYLE_MAGIC_KEY]) {
  9090. obj = this.createStyle(obj);
  9091. }
  9092. if (this.__inHover) {
  9093. this.__hoverStyle = obj;
  9094. }
  9095. else {
  9096. this.style = obj;
  9097. }
  9098. this.dirtyStyle();
  9099. };
  9100. Displayable.prototype.isStyleObject = function (obj) {
  9101. return obj[STYLE_MAGIC_KEY];
  9102. };
  9103. Displayable.prototype._innerSaveToNormal = function (toState) {
  9104. _super.prototype._innerSaveToNormal.call(this, toState);
  9105. var normalState = this._normalState;
  9106. if (toState.style && !normalState.style) {
  9107. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9108. }
  9109. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9110. };
  9111. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9112. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9113. var needsRestoreToNormal = !(state && keepCurrentStates);
  9114. var targetStyle;
  9115. if (state && state.style) {
  9116. if (transition) {
  9117. if (keepCurrentStates) {
  9118. targetStyle = state.style;
  9119. }
  9120. else {
  9121. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9122. this._mergeStyle(targetStyle, state.style);
  9123. }
  9124. }
  9125. else {
  9126. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9127. this._mergeStyle(targetStyle, state.style);
  9128. }
  9129. }
  9130. else if (needsRestoreToNormal) {
  9131. targetStyle = normalState.style;
  9132. }
  9133. if (targetStyle) {
  9134. if (transition) {
  9135. var sourceStyle = this.style;
  9136. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9137. if (needsRestoreToNormal) {
  9138. var changedKeys = keys(sourceStyle);
  9139. for (var i = 0; i < changedKeys.length; i++) {
  9140. var key = changedKeys[i];
  9141. if (key in targetStyle) {
  9142. targetStyle[key] = targetStyle[key];
  9143. this.style[key] = sourceStyle[key];
  9144. }
  9145. }
  9146. }
  9147. var targetKeys = keys(targetStyle);
  9148. for (var i = 0; i < targetKeys.length; i++) {
  9149. var key = targetKeys[i];
  9150. this.style[key] = this.style[key];
  9151. }
  9152. this._transitionState(stateName, {
  9153. style: targetStyle
  9154. }, animationCfg, this.getAnimationStyleProps());
  9155. }
  9156. else {
  9157. this.useStyle(targetStyle);
  9158. }
  9159. }
  9160. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9161. for (var i = 0; i < statesKeys.length; i++) {
  9162. var key = statesKeys[i];
  9163. if (state && state[key] != null) {
  9164. this[key] = state[key];
  9165. }
  9166. else if (needsRestoreToNormal) {
  9167. if (normalState[key] != null) {
  9168. this[key] = normalState[key];
  9169. }
  9170. }
  9171. }
  9172. };
  9173. Displayable.prototype._mergeStates = function (states) {
  9174. var mergedState = _super.prototype._mergeStates.call(this, states);
  9175. var mergedStyle;
  9176. for (var i = 0; i < states.length; i++) {
  9177. var state = states[i];
  9178. if (state.style) {
  9179. mergedStyle = mergedStyle || {};
  9180. this._mergeStyle(mergedStyle, state.style);
  9181. }
  9182. }
  9183. if (mergedStyle) {
  9184. mergedState.style = mergedStyle;
  9185. }
  9186. return mergedState;
  9187. };
  9188. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9189. extend(targetStyle, sourceStyle);
  9190. return targetStyle;
  9191. };
  9192. Displayable.prototype.getAnimationStyleProps = function () {
  9193. return DEFAULT_COMMON_ANIMATION_PROPS;
  9194. };
  9195. Displayable.initDefaultProps = (function () {
  9196. var dispProto = Displayable.prototype;
  9197. dispProto.type = 'displayable';
  9198. dispProto.invisible = false;
  9199. dispProto.z = 0;
  9200. dispProto.z2 = 0;
  9201. dispProto.zlevel = 0;
  9202. dispProto.culling = false;
  9203. dispProto.cursor = 'pointer';
  9204. dispProto.rectHover = false;
  9205. dispProto.incremental = false;
  9206. dispProto._rect = null;
  9207. dispProto.dirtyRectTolerance = 0;
  9208. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9209. })();
  9210. return Displayable;
  9211. }(Element));
  9212. var tmpRect = new BoundingRect(0, 0, 0, 0);
  9213. var viewRect = new BoundingRect(0, 0, 0, 0);
  9214. function isDisplayableCulled(el, width, height) {
  9215. tmpRect.copy(el.getBoundingRect());
  9216. if (el.transform) {
  9217. tmpRect.applyTransform(el.transform);
  9218. }
  9219. viewRect.width = width;
  9220. viewRect.height = height;
  9221. return !tmpRect.intersect(viewRect);
  9222. }
  9223. var mathMin$1 = Math.min;
  9224. var mathMax$1 = Math.max;
  9225. var mathSin = Math.sin;
  9226. var mathCos = Math.cos;
  9227. var PI2 = Math.PI * 2;
  9228. var start = create();
  9229. var end = create();
  9230. var extremity = create();
  9231. function fromLine(x0, y0, x1, y1, min, max) {
  9232. min[0] = mathMin$1(x0, x1);
  9233. min[1] = mathMin$1(y0, y1);
  9234. max[0] = mathMax$1(x0, x1);
  9235. max[1] = mathMax$1(y0, y1);
  9236. }
  9237. var xDim = [];
  9238. var yDim = [];
  9239. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9240. var cubicExtrema$1 = cubicExtrema;
  9241. var cubicAt$1 = cubicAt;
  9242. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9243. min[0] = Infinity;
  9244. min[1] = Infinity;
  9245. max[0] = -Infinity;
  9246. max[1] = -Infinity;
  9247. for (var i = 0; i < n; i++) {
  9248. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9249. min[0] = mathMin$1(x, min[0]);
  9250. max[0] = mathMax$1(x, max[0]);
  9251. }
  9252. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9253. for (var i = 0; i < n; i++) {
  9254. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9255. min[1] = mathMin$1(y, min[1]);
  9256. max[1] = mathMax$1(y, max[1]);
  9257. }
  9258. min[0] = mathMin$1(x0, min[0]);
  9259. max[0] = mathMax$1(x0, max[0]);
  9260. min[0] = mathMin$1(x3, min[0]);
  9261. max[0] = mathMax$1(x3, max[0]);
  9262. min[1] = mathMin$1(y0, min[1]);
  9263. max[1] = mathMax$1(y0, max[1]);
  9264. min[1] = mathMin$1(y3, min[1]);
  9265. max[1] = mathMax$1(y3, max[1]);
  9266. }
  9267. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9268. var quadraticExtremum$1 = quadraticExtremum;
  9269. var quadraticAt$1 = quadraticAt;
  9270. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9271. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9272. var x = quadraticAt$1(x0, x1, x2, tx);
  9273. var y = quadraticAt$1(y0, y1, y2, ty);
  9274. min[0] = mathMin$1(x0, x2, x);
  9275. min[1] = mathMin$1(y0, y2, y);
  9276. max[0] = mathMax$1(x0, x2, x);
  9277. max[1] = mathMax$1(y0, y2, y);
  9278. }
  9279. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9280. var vec2Min = min;
  9281. var vec2Max = max;
  9282. var diff = Math.abs(startAngle - endAngle);
  9283. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9284. min$1[0] = x - rx;
  9285. min$1[1] = y - ry;
  9286. max$1[0] = x + rx;
  9287. max$1[1] = y + ry;
  9288. return;
  9289. }
  9290. start[0] = mathCos(startAngle) * rx + x;
  9291. start[1] = mathSin(startAngle) * ry + y;
  9292. end[0] = mathCos(endAngle) * rx + x;
  9293. end[1] = mathSin(endAngle) * ry + y;
  9294. vec2Min(min$1, start, end);
  9295. vec2Max(max$1, start, end);
  9296. startAngle = startAngle % (PI2);
  9297. if (startAngle < 0) {
  9298. startAngle = startAngle + PI2;
  9299. }
  9300. endAngle = endAngle % (PI2);
  9301. if (endAngle < 0) {
  9302. endAngle = endAngle + PI2;
  9303. }
  9304. if (startAngle > endAngle && !anticlockwise) {
  9305. endAngle += PI2;
  9306. }
  9307. else if (startAngle < endAngle && anticlockwise) {
  9308. startAngle += PI2;
  9309. }
  9310. if (anticlockwise) {
  9311. var tmp = endAngle;
  9312. endAngle = startAngle;
  9313. startAngle = tmp;
  9314. }
  9315. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9316. if (angle > startAngle) {
  9317. extremity[0] = mathCos(angle) * rx + x;
  9318. extremity[1] = mathSin(angle) * ry + y;
  9319. vec2Min(min$1, extremity, min$1);
  9320. vec2Max(max$1, extremity, max$1);
  9321. }
  9322. }
  9323. }
  9324. var CMD = {
  9325. M: 1,
  9326. L: 2,
  9327. C: 3,
  9328. Q: 4,
  9329. A: 5,
  9330. Z: 6,
  9331. R: 7
  9332. };
  9333. var tmpOutX = [];
  9334. var tmpOutY = [];
  9335. var min$1 = [];
  9336. var max$1 = [];
  9337. var min2 = [];
  9338. var max2 = [];
  9339. var mathMin$2 = Math.min;
  9340. var mathMax$2 = Math.max;
  9341. var mathCos$1 = Math.cos;
  9342. var mathSin$1 = Math.sin;
  9343. var mathAbs = Math.abs;
  9344. var PI = Math.PI;
  9345. var PI2$1 = PI * 2;
  9346. var hasTypedArray = typeof Float32Array !== 'undefined';
  9347. var tmpAngles = [];
  9348. function modPI2(radian) {
  9349. var n = Math.round(radian / PI * 1e8) / 1e8;
  9350. return (n % 2) * PI;
  9351. }
  9352. function normalizeArcAngles(angles, anticlockwise) {
  9353. var newStartAngle = modPI2(angles[0]);
  9354. if (newStartAngle < 0) {
  9355. newStartAngle += PI2$1;
  9356. }
  9357. var delta = newStartAngle - angles[0];
  9358. var newEndAngle = angles[1];
  9359. newEndAngle += delta;
  9360. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9361. newEndAngle = newStartAngle + PI2$1;
  9362. }
  9363. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9364. newEndAngle = newStartAngle - PI2$1;
  9365. }
  9366. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9367. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9368. }
  9369. else if (anticlockwise && newStartAngle < newEndAngle) {
  9370. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9371. }
  9372. angles[0] = newStartAngle;
  9373. angles[1] = newEndAngle;
  9374. }
  9375. var PathProxy = (function () {
  9376. function PathProxy(notSaveData) {
  9377. this.dpr = 1;
  9378. this._xi = 0;
  9379. this._yi = 0;
  9380. this._x0 = 0;
  9381. this._y0 = 0;
  9382. this._len = 0;
  9383. if (notSaveData) {
  9384. this._saveData = false;
  9385. }
  9386. if (this._saveData) {
  9387. this.data = [];
  9388. }
  9389. }
  9390. PathProxy.prototype.increaseVersion = function () {
  9391. this._version++;
  9392. };
  9393. PathProxy.prototype.getVersion = function () {
  9394. return this._version;
  9395. };
  9396. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9397. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9398. if (segmentIgnoreThreshold > 0) {
  9399. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9400. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9401. }
  9402. };
  9403. PathProxy.prototype.setDPR = function (dpr) {
  9404. this.dpr = dpr;
  9405. };
  9406. PathProxy.prototype.setContext = function (ctx) {
  9407. this._ctx = ctx;
  9408. };
  9409. PathProxy.prototype.getContext = function () {
  9410. return this._ctx;
  9411. };
  9412. PathProxy.prototype.beginPath = function () {
  9413. this._ctx && this._ctx.beginPath();
  9414. this.reset();
  9415. return this;
  9416. };
  9417. PathProxy.prototype.reset = function () {
  9418. if (this._saveData) {
  9419. this._len = 0;
  9420. }
  9421. if (this._pathSegLen) {
  9422. this._pathSegLen = null;
  9423. this._pathLen = 0;
  9424. }
  9425. this._version++;
  9426. };
  9427. PathProxy.prototype.moveTo = function (x, y) {
  9428. this._drawPendingPt();
  9429. this.addData(CMD.M, x, y);
  9430. this._ctx && this._ctx.moveTo(x, y);
  9431. this._x0 = x;
  9432. this._y0 = y;
  9433. this._xi = x;
  9434. this._yi = y;
  9435. return this;
  9436. };
  9437. PathProxy.prototype.lineTo = function (x, y) {
  9438. var dx = mathAbs(x - this._xi);
  9439. var dy = mathAbs(y - this._yi);
  9440. var exceedUnit = dx > this._ux || dy > this._uy;
  9441. this.addData(CMD.L, x, y);
  9442. if (this._ctx && exceedUnit) {
  9443. this._ctx.lineTo(x, y);
  9444. }
  9445. if (exceedUnit) {
  9446. this._xi = x;
  9447. this._yi = y;
  9448. this._pendingPtDist = 0;
  9449. }
  9450. else {
  9451. var d2 = dx * dx + dy * dy;
  9452. if (d2 > this._pendingPtDist) {
  9453. this._pendingPtX = x;
  9454. this._pendingPtY = y;
  9455. this._pendingPtDist = d2;
  9456. }
  9457. }
  9458. return this;
  9459. };
  9460. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9461. this._drawPendingPt();
  9462. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9463. if (this._ctx) {
  9464. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9465. }
  9466. this._xi = x3;
  9467. this._yi = y3;
  9468. return this;
  9469. };
  9470. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9471. this._drawPendingPt();
  9472. this.addData(CMD.Q, x1, y1, x2, y2);
  9473. if (this._ctx) {
  9474. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9475. }
  9476. this._xi = x2;
  9477. this._yi = y2;
  9478. return this;
  9479. };
  9480. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9481. this._drawPendingPt();
  9482. tmpAngles[0] = startAngle;
  9483. tmpAngles[1] = endAngle;
  9484. normalizeArcAngles(tmpAngles, anticlockwise);
  9485. startAngle = tmpAngles[0];
  9486. endAngle = tmpAngles[1];
  9487. var delta = endAngle - startAngle;
  9488. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9489. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9490. this._xi = mathCos$1(endAngle) * r + cx;
  9491. this._yi = mathSin$1(endAngle) * r + cy;
  9492. return this;
  9493. };
  9494. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9495. this._drawPendingPt();
  9496. if (this._ctx) {
  9497. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9498. }
  9499. return this;
  9500. };
  9501. PathProxy.prototype.rect = function (x, y, w, h) {
  9502. this._drawPendingPt();
  9503. this._ctx && this._ctx.rect(x, y, w, h);
  9504. this.addData(CMD.R, x, y, w, h);
  9505. return this;
  9506. };
  9507. PathProxy.prototype.closePath = function () {
  9508. this._drawPendingPt();
  9509. this.addData(CMD.Z);
  9510. var ctx = this._ctx;
  9511. var x0 = this._x0;
  9512. var y0 = this._y0;
  9513. if (ctx) {
  9514. ctx.closePath();
  9515. }
  9516. this._xi = x0;
  9517. this._yi = y0;
  9518. return this;
  9519. };
  9520. PathProxy.prototype.fill = function (ctx) {
  9521. ctx && ctx.fill();
  9522. this.toStatic();
  9523. };
  9524. PathProxy.prototype.stroke = function (ctx) {
  9525. ctx && ctx.stroke();
  9526. this.toStatic();
  9527. };
  9528. PathProxy.prototype.len = function () {
  9529. return this._len;
  9530. };
  9531. PathProxy.prototype.setData = function (data) {
  9532. var len = data.length;
  9533. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9534. this.data = new Float32Array(len);
  9535. }
  9536. for (var i = 0; i < len; i++) {
  9537. this.data[i] = data[i];
  9538. }
  9539. this._len = len;
  9540. };
  9541. PathProxy.prototype.appendPath = function (path) {
  9542. if (!(path instanceof Array)) {
  9543. path = [path];
  9544. }
  9545. var len = path.length;
  9546. var appendSize = 0;
  9547. var offset = this._len;
  9548. for (var i = 0; i < len; i++) {
  9549. appendSize += path[i].len();
  9550. }
  9551. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9552. this.data = new Float32Array(offset + appendSize);
  9553. }
  9554. for (var i = 0; i < len; i++) {
  9555. var appendPathData = path[i].data;
  9556. for (var k = 0; k < appendPathData.length; k++) {
  9557. this.data[offset++] = appendPathData[k];
  9558. }
  9559. }
  9560. this._len = offset;
  9561. };
  9562. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9563. if (!this._saveData) {
  9564. return;
  9565. }
  9566. var data = this.data;
  9567. if (this._len + arguments.length > data.length) {
  9568. this._expandData();
  9569. data = this.data;
  9570. }
  9571. for (var i = 0; i < arguments.length; i++) {
  9572. data[this._len++] = arguments[i];
  9573. }
  9574. };
  9575. PathProxy.prototype._drawPendingPt = function () {
  9576. if (this._pendingPtDist > 0) {
  9577. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9578. this._pendingPtDist = 0;
  9579. }
  9580. };
  9581. PathProxy.prototype._expandData = function () {
  9582. if (!(this.data instanceof Array)) {
  9583. var newData = [];
  9584. for (var i = 0; i < this._len; i++) {
  9585. newData[i] = this.data[i];
  9586. }
  9587. this.data = newData;
  9588. }
  9589. };
  9590. PathProxy.prototype.toStatic = function () {
  9591. if (!this._saveData) {
  9592. return;
  9593. }
  9594. this._drawPendingPt();
  9595. var data = this.data;
  9596. if (data instanceof Array) {
  9597. data.length = this._len;
  9598. if (hasTypedArray && this._len > 11) {
  9599. this.data = new Float32Array(data);
  9600. }
  9601. }
  9602. };
  9603. PathProxy.prototype.getBoundingRect = function () {
  9604. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9605. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9606. var data = this.data;
  9607. var xi = 0;
  9608. var yi = 0;
  9609. var x0 = 0;
  9610. var y0 = 0;
  9611. var i;
  9612. for (i = 0; i < this._len;) {
  9613. var cmd = data[i++];
  9614. var isFirst = i === 1;
  9615. if (isFirst) {
  9616. xi = data[i];
  9617. yi = data[i + 1];
  9618. x0 = xi;
  9619. y0 = yi;
  9620. }
  9621. switch (cmd) {
  9622. case CMD.M:
  9623. xi = x0 = data[i++];
  9624. yi = y0 = data[i++];
  9625. min2[0] = x0;
  9626. min2[1] = y0;
  9627. max2[0] = x0;
  9628. max2[1] = y0;
  9629. break;
  9630. case CMD.L:
  9631. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9632. xi = data[i++];
  9633. yi = data[i++];
  9634. break;
  9635. case CMD.C:
  9636. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9637. xi = data[i++];
  9638. yi = data[i++];
  9639. break;
  9640. case CMD.Q:
  9641. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9642. xi = data[i++];
  9643. yi = data[i++];
  9644. break;
  9645. case CMD.A:
  9646. var cx = data[i++];
  9647. var cy = data[i++];
  9648. var rx = data[i++];
  9649. var ry = data[i++];
  9650. var startAngle = data[i++];
  9651. var endAngle = data[i++] + startAngle;
  9652. i += 1;
  9653. var anticlockwise = !data[i++];
  9654. if (isFirst) {
  9655. x0 = mathCos$1(startAngle) * rx + cx;
  9656. y0 = mathSin$1(startAngle) * ry + cy;
  9657. }
  9658. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9659. xi = mathCos$1(endAngle) * rx + cx;
  9660. yi = mathSin$1(endAngle) * ry + cy;
  9661. break;
  9662. case CMD.R:
  9663. x0 = xi = data[i++];
  9664. y0 = yi = data[i++];
  9665. var width = data[i++];
  9666. var height = data[i++];
  9667. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9668. break;
  9669. case CMD.Z:
  9670. xi = x0;
  9671. yi = y0;
  9672. break;
  9673. }
  9674. min(min$1, min$1, min2);
  9675. max(max$1, max$1, max2);
  9676. }
  9677. if (i === 0) {
  9678. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9679. }
  9680. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9681. };
  9682. PathProxy.prototype._calculateLength = function () {
  9683. var data = this.data;
  9684. var len = this._len;
  9685. var ux = this._ux;
  9686. var uy = this._uy;
  9687. var xi = 0;
  9688. var yi = 0;
  9689. var x0 = 0;
  9690. var y0 = 0;
  9691. if (!this._pathSegLen) {
  9692. this._pathSegLen = [];
  9693. }
  9694. var pathSegLen = this._pathSegLen;
  9695. var pathTotalLen = 0;
  9696. var segCount = 0;
  9697. for (var i = 0; i < len;) {
  9698. var cmd = data[i++];
  9699. var isFirst = i === 1;
  9700. if (isFirst) {
  9701. xi = data[i];
  9702. yi = data[i + 1];
  9703. x0 = xi;
  9704. y0 = yi;
  9705. }
  9706. var l = -1;
  9707. switch (cmd) {
  9708. case CMD.M:
  9709. xi = x0 = data[i++];
  9710. yi = y0 = data[i++];
  9711. break;
  9712. case CMD.L: {
  9713. var x2 = data[i++];
  9714. var y2 = data[i++];
  9715. var dx = x2 - xi;
  9716. var dy = y2 - yi;
  9717. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  9718. l = Math.sqrt(dx * dx + dy * dy);
  9719. xi = x2;
  9720. yi = y2;
  9721. }
  9722. break;
  9723. }
  9724. case CMD.C: {
  9725. var x1 = data[i++];
  9726. var y1 = data[i++];
  9727. var x2 = data[i++];
  9728. var y2 = data[i++];
  9729. var x3 = data[i++];
  9730. var y3 = data[i++];
  9731. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  9732. xi = x3;
  9733. yi = y3;
  9734. break;
  9735. }
  9736. case CMD.Q: {
  9737. var x1 = data[i++];
  9738. var y1 = data[i++];
  9739. var x2 = data[i++];
  9740. var y2 = data[i++];
  9741. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  9742. xi = x2;
  9743. yi = y2;
  9744. break;
  9745. }
  9746. case CMD.A:
  9747. var cx = data[i++];
  9748. var cy = data[i++];
  9749. var rx = data[i++];
  9750. var ry = data[i++];
  9751. var startAngle = data[i++];
  9752. var delta = data[i++];
  9753. var endAngle = delta + startAngle;
  9754. i += 1;
  9755. var anticlockwise = !data[i++];
  9756. if (isFirst) {
  9757. x0 = mathCos$1(startAngle) * rx + cx;
  9758. y0 = mathSin$1(startAngle) * ry + cy;
  9759. }
  9760. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  9761. xi = mathCos$1(endAngle) * rx + cx;
  9762. yi = mathSin$1(endAngle) * ry + cy;
  9763. break;
  9764. case CMD.R: {
  9765. x0 = xi = data[i++];
  9766. y0 = yi = data[i++];
  9767. var width = data[i++];
  9768. var height = data[i++];
  9769. l = width * 2 + height * 2;
  9770. break;
  9771. }
  9772. case CMD.Z: {
  9773. var dx = x0 - xi;
  9774. var dy = y0 - yi;
  9775. l = Math.sqrt(dx * dx + dy * dy);
  9776. xi = x0;
  9777. yi = y0;
  9778. break;
  9779. }
  9780. }
  9781. if (l >= 0) {
  9782. pathSegLen[segCount++] = l;
  9783. pathTotalLen += l;
  9784. }
  9785. }
  9786. this._pathLen = pathTotalLen;
  9787. return pathTotalLen;
  9788. };
  9789. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  9790. var d = this.data;
  9791. var ux = this._ux;
  9792. var uy = this._uy;
  9793. var len = this._len;
  9794. var x0;
  9795. var y0;
  9796. var xi;
  9797. var yi;
  9798. var x;
  9799. var y;
  9800. var drawPart = percent < 1;
  9801. var pathSegLen;
  9802. var pathTotalLen;
  9803. var accumLength = 0;
  9804. var segCount = 0;
  9805. var displayedLength;
  9806. var pendingPtDist = 0;
  9807. var pendingPtX;
  9808. var pendingPtY;
  9809. if (drawPart) {
  9810. if (!this._pathSegLen) {
  9811. this._calculateLength();
  9812. }
  9813. pathSegLen = this._pathSegLen;
  9814. pathTotalLen = this._pathLen;
  9815. displayedLength = percent * pathTotalLen;
  9816. if (!displayedLength) {
  9817. return;
  9818. }
  9819. }
  9820. lo: for (var i = 0; i < len;) {
  9821. var cmd = d[i++];
  9822. var isFirst = i === 1;
  9823. if (isFirst) {
  9824. xi = d[i];
  9825. yi = d[i + 1];
  9826. x0 = xi;
  9827. y0 = yi;
  9828. }
  9829. if (cmd !== CMD.L && pendingPtDist > 0) {
  9830. ctx.lineTo(pendingPtX, pendingPtY);
  9831. pendingPtDist = 0;
  9832. }
  9833. switch (cmd) {
  9834. case CMD.M:
  9835. x0 = xi = d[i++];
  9836. y0 = yi = d[i++];
  9837. ctx.moveTo(xi, yi);
  9838. break;
  9839. case CMD.L: {
  9840. x = d[i++];
  9841. y = d[i++];
  9842. var dx = mathAbs(x - xi);
  9843. var dy = mathAbs(y - yi);
  9844. if (dx > ux || dy > uy) {
  9845. if (drawPart) {
  9846. var l = pathSegLen[segCount++];
  9847. if (accumLength + l > displayedLength) {
  9848. var t = (displayedLength - accumLength) / l;
  9849. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  9850. break lo;
  9851. }
  9852. accumLength += l;
  9853. }
  9854. ctx.lineTo(x, y);
  9855. xi = x;
  9856. yi = y;
  9857. pendingPtDist = 0;
  9858. }
  9859. else {
  9860. var d2 = dx * dx + dy * dy;
  9861. if (d2 > pendingPtDist) {
  9862. pendingPtX = x;
  9863. pendingPtY = y;
  9864. pendingPtDist = d2;
  9865. }
  9866. }
  9867. break;
  9868. }
  9869. case CMD.C: {
  9870. var x1 = d[i++];
  9871. var y1 = d[i++];
  9872. var x2 = d[i++];
  9873. var y2 = d[i++];
  9874. var x3 = d[i++];
  9875. var y3 = d[i++];
  9876. if (drawPart) {
  9877. var l = pathSegLen[segCount++];
  9878. if (accumLength + l > displayedLength) {
  9879. var t = (displayedLength - accumLength) / l;
  9880. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  9881. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  9882. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  9883. break lo;
  9884. }
  9885. accumLength += l;
  9886. }
  9887. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9888. xi = x3;
  9889. yi = y3;
  9890. break;
  9891. }
  9892. case CMD.Q: {
  9893. var x1 = d[i++];
  9894. var y1 = d[i++];
  9895. var x2 = d[i++];
  9896. var y2 = d[i++];
  9897. if (drawPart) {
  9898. var l = pathSegLen[segCount++];
  9899. if (accumLength + l > displayedLength) {
  9900. var t = (displayedLength - accumLength) / l;
  9901. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  9902. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  9903. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  9904. break lo;
  9905. }
  9906. accumLength += l;
  9907. }
  9908. ctx.quadraticCurveTo(x1, y1, x2, y2);
  9909. xi = x2;
  9910. yi = y2;
  9911. break;
  9912. }
  9913. case CMD.A:
  9914. var cx = d[i++];
  9915. var cy = d[i++];
  9916. var rx = d[i++];
  9917. var ry = d[i++];
  9918. var startAngle = d[i++];
  9919. var delta = d[i++];
  9920. var psi = d[i++];
  9921. var anticlockwise = !d[i++];
  9922. var r = (rx > ry) ? rx : ry;
  9923. var isEllipse = mathAbs(rx - ry) > 1e-3;
  9924. var endAngle = startAngle + delta;
  9925. var breakBuild = false;
  9926. if (drawPart) {
  9927. var l = pathSegLen[segCount++];
  9928. if (accumLength + l > displayedLength) {
  9929. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  9930. breakBuild = true;
  9931. }
  9932. accumLength += l;
  9933. }
  9934. if (isEllipse && ctx.ellipse) {
  9935. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  9936. }
  9937. else {
  9938. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9939. }
  9940. if (breakBuild) {
  9941. break lo;
  9942. }
  9943. if (isFirst) {
  9944. x0 = mathCos$1(startAngle) * rx + cx;
  9945. y0 = mathSin$1(startAngle) * ry + cy;
  9946. }
  9947. xi = mathCos$1(endAngle) * rx + cx;
  9948. yi = mathSin$1(endAngle) * ry + cy;
  9949. break;
  9950. case CMD.R:
  9951. x0 = xi = d[i];
  9952. y0 = yi = d[i + 1];
  9953. x = d[i++];
  9954. y = d[i++];
  9955. var width = d[i++];
  9956. var height = d[i++];
  9957. if (drawPart) {
  9958. var l = pathSegLen[segCount++];
  9959. if (accumLength + l > displayedLength) {
  9960. var d_1 = displayedLength - accumLength;
  9961. ctx.moveTo(x, y);
  9962. ctx.lineTo(x + mathMin$2(d_1, width), y);
  9963. d_1 -= width;
  9964. if (d_1 > 0) {
  9965. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  9966. }
  9967. d_1 -= height;
  9968. if (d_1 > 0) {
  9969. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  9970. }
  9971. d_1 -= width;
  9972. if (d_1 > 0) {
  9973. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  9974. }
  9975. break lo;
  9976. }
  9977. accumLength += l;
  9978. }
  9979. ctx.rect(x, y, width, height);
  9980. break;
  9981. case CMD.Z:
  9982. if (drawPart) {
  9983. var l = pathSegLen[segCount++];
  9984. if (accumLength + l > displayedLength) {
  9985. var t = (displayedLength - accumLength) / l;
  9986. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  9987. break lo;
  9988. }
  9989. accumLength += l;
  9990. }
  9991. ctx.closePath();
  9992. xi = x0;
  9993. yi = y0;
  9994. }
  9995. }
  9996. };
  9997. PathProxy.prototype.clone = function () {
  9998. var newProxy = new PathProxy();
  9999. var data = this.data;
  10000. newProxy.data = data.slice ? data.slice()
  10001. : Array.prototype.slice.call(data);
  10002. newProxy._len = this._len;
  10003. return newProxy;
  10004. };
  10005. PathProxy.CMD = CMD;
  10006. PathProxy.initDefaultProps = (function () {
  10007. var proto = PathProxy.prototype;
  10008. proto._saveData = true;
  10009. proto._ux = 0;
  10010. proto._uy = 0;
  10011. proto._pendingPtDist = 0;
  10012. proto._version = 0;
  10013. })();
  10014. return PathProxy;
  10015. }());
  10016. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10017. if (lineWidth === 0) {
  10018. return false;
  10019. }
  10020. var _l = lineWidth;
  10021. var _a = 0;
  10022. var _b = x0;
  10023. if ((y > y0 + _l && y > y1 + _l)
  10024. || (y < y0 - _l && y < y1 - _l)
  10025. || (x > x0 + _l && x > x1 + _l)
  10026. || (x < x0 - _l && x < x1 - _l)) {
  10027. return false;
  10028. }
  10029. if (x0 !== x1) {
  10030. _a = (y0 - y1) / (x0 - x1);
  10031. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10032. }
  10033. else {
  10034. return Math.abs(x - x0) <= _l / 2;
  10035. }
  10036. var tmp = _a * x - y + _b;
  10037. var _s = tmp * tmp / (_a * _a + 1);
  10038. return _s <= _l / 2 * _l / 2;
  10039. }
  10040. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10041. if (lineWidth === 0) {
  10042. return false;
  10043. }
  10044. var _l = lineWidth;
  10045. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10046. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10047. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10048. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10049. return false;
  10050. }
  10051. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10052. return d <= _l / 2;
  10053. }
  10054. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10055. if (lineWidth === 0) {
  10056. return false;
  10057. }
  10058. var _l = lineWidth;
  10059. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10060. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10061. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10062. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10063. return false;
  10064. }
  10065. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10066. return d <= _l / 2;
  10067. }
  10068. var PI2$2 = Math.PI * 2;
  10069. function normalizeRadian(angle) {
  10070. angle %= PI2$2;
  10071. if (angle < 0) {
  10072. angle += PI2$2;
  10073. }
  10074. return angle;
  10075. }
  10076. var PI2$3 = Math.PI * 2;
  10077. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10078. if (lineWidth === 0) {
  10079. return false;
  10080. }
  10081. var _l = lineWidth;
  10082. x -= cx;
  10083. y -= cy;
  10084. var d = Math.sqrt(x * x + y * y);
  10085. if ((d - _l > r) || (d + _l < r)) {
  10086. return false;
  10087. }
  10088. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10089. return true;
  10090. }
  10091. if (anticlockwise) {
  10092. var tmp = startAngle;
  10093. startAngle = normalizeRadian(endAngle);
  10094. endAngle = normalizeRadian(tmp);
  10095. }
  10096. else {
  10097. startAngle = normalizeRadian(startAngle);
  10098. endAngle = normalizeRadian(endAngle);
  10099. }
  10100. if (startAngle > endAngle) {
  10101. endAngle += PI2$3;
  10102. }
  10103. var angle = Math.atan2(y, x);
  10104. if (angle < 0) {
  10105. angle += PI2$3;
  10106. }
  10107. return (angle >= startAngle && angle <= endAngle)
  10108. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10109. }
  10110. function windingLine(x0, y0, x1, y1, x, y) {
  10111. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10112. return 0;
  10113. }
  10114. if (y1 === y0) {
  10115. return 0;
  10116. }
  10117. var t = (y - y0) / (y1 - y0);
  10118. var dir = y1 < y0 ? 1 : -1;
  10119. if (t === 1 || t === 0) {
  10120. dir = y1 < y0 ? 0.5 : -0.5;
  10121. }
  10122. var x_ = t * (x1 - x0) + x0;
  10123. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10124. }
  10125. var CMD$1 = PathProxy.CMD;
  10126. var PI2$4 = Math.PI * 2;
  10127. var EPSILON$2 = 1e-4;
  10128. function isAroundEqual(a, b) {
  10129. return Math.abs(a - b) < EPSILON$2;
  10130. }
  10131. var roots = [-1, -1, -1];
  10132. var extrema = [-1, -1];
  10133. function swapExtrema() {
  10134. var tmp = extrema[0];
  10135. extrema[0] = extrema[1];
  10136. extrema[1] = tmp;
  10137. }
  10138. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10139. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10140. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10141. return 0;
  10142. }
  10143. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10144. if (nRoots === 0) {
  10145. return 0;
  10146. }
  10147. else {
  10148. var w = 0;
  10149. var nExtrema = -1;
  10150. var y0_ = void 0;
  10151. var y1_ = void 0;
  10152. for (var i = 0; i < nRoots; i++) {
  10153. var t = roots[i];
  10154. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10155. var x_ = cubicAt(x0, x1, x2, x3, t);
  10156. if (x_ < x) {
  10157. continue;
  10158. }
  10159. if (nExtrema < 0) {
  10160. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10161. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10162. swapExtrema();
  10163. }
  10164. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10165. if (nExtrema > 1) {
  10166. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10167. }
  10168. }
  10169. if (nExtrema === 2) {
  10170. if (t < extrema[0]) {
  10171. w += y0_ < y0 ? unit : -unit;
  10172. }
  10173. else if (t < extrema[1]) {
  10174. w += y1_ < y0_ ? unit : -unit;
  10175. }
  10176. else {
  10177. w += y3 < y1_ ? unit : -unit;
  10178. }
  10179. }
  10180. else {
  10181. if (t < extrema[0]) {
  10182. w += y0_ < y0 ? unit : -unit;
  10183. }
  10184. else {
  10185. w += y3 < y0_ ? unit : -unit;
  10186. }
  10187. }
  10188. }
  10189. return w;
  10190. }
  10191. }
  10192. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10193. if ((y > y0 && y > y1 && y > y2)
  10194. || (y < y0 && y < y1 && y < y2)) {
  10195. return 0;
  10196. }
  10197. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10198. if (nRoots === 0) {
  10199. return 0;
  10200. }
  10201. else {
  10202. var t = quadraticExtremum(y0, y1, y2);
  10203. if (t >= 0 && t <= 1) {
  10204. var w = 0;
  10205. var y_ = quadraticAt(y0, y1, y2, t);
  10206. for (var i = 0; i < nRoots; i++) {
  10207. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10208. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10209. if (x_ < x) {
  10210. continue;
  10211. }
  10212. if (roots[i] < t) {
  10213. w += y_ < y0 ? unit : -unit;
  10214. }
  10215. else {
  10216. w += y2 < y_ ? unit : -unit;
  10217. }
  10218. }
  10219. return w;
  10220. }
  10221. else {
  10222. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10223. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10224. if (x_ < x) {
  10225. return 0;
  10226. }
  10227. return y2 < y0 ? unit : -unit;
  10228. }
  10229. }
  10230. }
  10231. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10232. y -= cy;
  10233. if (y > r || y < -r) {
  10234. return 0;
  10235. }
  10236. var tmp = Math.sqrt(r * r - y * y);
  10237. roots[0] = -tmp;
  10238. roots[1] = tmp;
  10239. var dTheta = Math.abs(startAngle - endAngle);
  10240. if (dTheta < 1e-4) {
  10241. return 0;
  10242. }
  10243. if (dTheta >= PI2$4 - 1e-4) {
  10244. startAngle = 0;
  10245. endAngle = PI2$4;
  10246. var dir = anticlockwise ? 1 : -1;
  10247. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10248. return dir;
  10249. }
  10250. else {
  10251. return 0;
  10252. }
  10253. }
  10254. if (startAngle > endAngle) {
  10255. var tmp_1 = startAngle;
  10256. startAngle = endAngle;
  10257. endAngle = tmp_1;
  10258. }
  10259. if (startAngle < 0) {
  10260. startAngle += PI2$4;
  10261. endAngle += PI2$4;
  10262. }
  10263. var w = 0;
  10264. for (var i = 0; i < 2; i++) {
  10265. var x_ = roots[i];
  10266. if (x_ + cx > x) {
  10267. var angle = Math.atan2(y, x_);
  10268. var dir = anticlockwise ? 1 : -1;
  10269. if (angle < 0) {
  10270. angle = PI2$4 + angle;
  10271. }
  10272. if ((angle >= startAngle && angle <= endAngle)
  10273. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10274. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10275. dir = -dir;
  10276. }
  10277. w += dir;
  10278. }
  10279. }
  10280. }
  10281. return w;
  10282. }
  10283. function containPath(path, lineWidth, isStroke, x, y) {
  10284. var data = path.data;
  10285. var len = path.len();
  10286. var w = 0;
  10287. var xi = 0;
  10288. var yi = 0;
  10289. var x0 = 0;
  10290. var y0 = 0;
  10291. var x1;
  10292. var y1;
  10293. for (var i = 0; i < len;) {
  10294. var cmd = data[i++];
  10295. var isFirst = i === 1;
  10296. if (cmd === CMD$1.M && i > 1) {
  10297. if (!isStroke) {
  10298. w += windingLine(xi, yi, x0, y0, x, y);
  10299. }
  10300. }
  10301. if (isFirst) {
  10302. xi = data[i];
  10303. yi = data[i + 1];
  10304. x0 = xi;
  10305. y0 = yi;
  10306. }
  10307. switch (cmd) {
  10308. case CMD$1.M:
  10309. x0 = data[i++];
  10310. y0 = data[i++];
  10311. xi = x0;
  10312. yi = y0;
  10313. break;
  10314. case CMD$1.L:
  10315. if (isStroke) {
  10316. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10317. return true;
  10318. }
  10319. }
  10320. else {
  10321. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10322. }
  10323. xi = data[i++];
  10324. yi = data[i++];
  10325. break;
  10326. case CMD$1.C:
  10327. if (isStroke) {
  10328. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10329. return true;
  10330. }
  10331. }
  10332. else {
  10333. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10334. }
  10335. xi = data[i++];
  10336. yi = data[i++];
  10337. break;
  10338. case CMD$1.Q:
  10339. if (isStroke) {
  10340. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10341. return true;
  10342. }
  10343. }
  10344. else {
  10345. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10346. }
  10347. xi = data[i++];
  10348. yi = data[i++];
  10349. break;
  10350. case CMD$1.A:
  10351. var cx = data[i++];
  10352. var cy = data[i++];
  10353. var rx = data[i++];
  10354. var ry = data[i++];
  10355. var theta = data[i++];
  10356. var dTheta = data[i++];
  10357. i += 1;
  10358. var anticlockwise = !!(1 - data[i++]);
  10359. x1 = Math.cos(theta) * rx + cx;
  10360. y1 = Math.sin(theta) * ry + cy;
  10361. if (!isFirst) {
  10362. w += windingLine(xi, yi, x1, y1, x, y);
  10363. }
  10364. else {
  10365. x0 = x1;
  10366. y0 = y1;
  10367. }
  10368. var _x = (x - cx) * ry / rx + cx;
  10369. if (isStroke) {
  10370. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10371. return true;
  10372. }
  10373. }
  10374. else {
  10375. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10376. }
  10377. xi = Math.cos(theta + dTheta) * rx + cx;
  10378. yi = Math.sin(theta + dTheta) * ry + cy;
  10379. break;
  10380. case CMD$1.R:
  10381. x0 = xi = data[i++];
  10382. y0 = yi = data[i++];
  10383. var width = data[i++];
  10384. var height = data[i++];
  10385. x1 = x0 + width;
  10386. y1 = y0 + height;
  10387. if (isStroke) {
  10388. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10389. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10390. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10391. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10392. return true;
  10393. }
  10394. }
  10395. else {
  10396. w += windingLine(x1, y0, x1, y1, x, y);
  10397. w += windingLine(x0, y1, x0, y0, x, y);
  10398. }
  10399. break;
  10400. case CMD$1.Z:
  10401. if (isStroke) {
  10402. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10403. return true;
  10404. }
  10405. }
  10406. else {
  10407. w += windingLine(xi, yi, x0, y0, x, y);
  10408. }
  10409. xi = x0;
  10410. yi = y0;
  10411. break;
  10412. }
  10413. }
  10414. if (!isStroke && !isAroundEqual(yi, y0)) {
  10415. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10416. }
  10417. return w !== 0;
  10418. }
  10419. function contain(pathProxy, x, y) {
  10420. return containPath(pathProxy, 0, false, x, y);
  10421. }
  10422. function containStroke$4(pathProxy, lineWidth, x, y) {
  10423. return containPath(pathProxy, lineWidth, true, x, y);
  10424. }
  10425. var DEFAULT_PATH_STYLE = defaults({
  10426. fill: '#000',
  10427. stroke: null,
  10428. strokePercent: 1,
  10429. fillOpacity: 1,
  10430. strokeOpacity: 1,
  10431. lineDashOffset: 0,
  10432. lineWidth: 1,
  10433. lineCap: 'butt',
  10434. miterLimit: 10,
  10435. strokeNoScale: false,
  10436. strokeFirst: false
  10437. }, DEFAULT_COMMON_STYLE);
  10438. var DEFAULT_PATH_ANIMATION_PROPS = {
  10439. style: defaults({
  10440. fill: true,
  10441. stroke: true,
  10442. strokePercent: true,
  10443. fillOpacity: true,
  10444. strokeOpacity: true,
  10445. lineDashOffset: true,
  10446. lineWidth: true,
  10447. miterLimit: true
  10448. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10449. };
  10450. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10451. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10452. ]);
  10453. var Path = (function (_super) {
  10454. __extends(Path, _super);
  10455. function Path(opts) {
  10456. return _super.call(this, opts) || this;
  10457. }
  10458. Path.prototype.update = function () {
  10459. var _this = this;
  10460. _super.prototype.update.call(this);
  10461. var style = this.style;
  10462. if (style.decal) {
  10463. var decalEl = this._decalEl = this._decalEl || new Path();
  10464. if (decalEl.buildPath === Path.prototype.buildPath) {
  10465. decalEl.buildPath = function (ctx) {
  10466. _this.buildPath(ctx, _this.shape);
  10467. };
  10468. }
  10469. decalEl.silent = true;
  10470. var decalElStyle = decalEl.style;
  10471. for (var key in style) {
  10472. if (decalElStyle[key] !== style[key]) {
  10473. decalElStyle[key] = style[key];
  10474. }
  10475. }
  10476. decalElStyle.fill = style.fill ? style.decal : null;
  10477. decalElStyle.decal = null;
  10478. decalElStyle.shadowColor = null;
  10479. style.strokeFirst && (decalElStyle.stroke = null);
  10480. for (var i = 0; i < pathCopyParams.length; ++i) {
  10481. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10482. }
  10483. decalEl.__dirty |= REDRAW_BIT;
  10484. }
  10485. else if (this._decalEl) {
  10486. this._decalEl = null;
  10487. }
  10488. };
  10489. Path.prototype.getDecalElement = function () {
  10490. return this._decalEl;
  10491. };
  10492. Path.prototype._init = function (props) {
  10493. var keysArr = keys(props);
  10494. this.shape = this.getDefaultShape();
  10495. var defaultStyle = this.getDefaultStyle();
  10496. if (defaultStyle) {
  10497. this.useStyle(defaultStyle);
  10498. }
  10499. for (var i = 0; i < keysArr.length; i++) {
  10500. var key = keysArr[i];
  10501. var value = props[key];
  10502. if (key === 'style') {
  10503. if (!this.style) {
  10504. this.useStyle(value);
  10505. }
  10506. else {
  10507. extend(this.style, value);
  10508. }
  10509. }
  10510. else if (key === 'shape') {
  10511. extend(this.shape, value);
  10512. }
  10513. else {
  10514. _super.prototype.attrKV.call(this, key, value);
  10515. }
  10516. }
  10517. if (!this.style) {
  10518. this.useStyle({});
  10519. }
  10520. };
  10521. Path.prototype.getDefaultStyle = function () {
  10522. return null;
  10523. };
  10524. Path.prototype.getDefaultShape = function () {
  10525. return {};
  10526. };
  10527. Path.prototype.canBeInsideText = function () {
  10528. return this.hasFill();
  10529. };
  10530. Path.prototype.getInsideTextFill = function () {
  10531. var pathFill = this.style.fill;
  10532. if (pathFill !== 'none') {
  10533. if (isString(pathFill)) {
  10534. var fillLum = lum(pathFill, 0);
  10535. if (fillLum > 0.5) {
  10536. return DARK_LABEL_COLOR;
  10537. }
  10538. else if (fillLum > 0.2) {
  10539. return LIGHTER_LABEL_COLOR;
  10540. }
  10541. return LIGHT_LABEL_COLOR;
  10542. }
  10543. else if (pathFill) {
  10544. return LIGHT_LABEL_COLOR;
  10545. }
  10546. }
  10547. return DARK_LABEL_COLOR;
  10548. };
  10549. Path.prototype.getInsideTextStroke = function (textFill) {
  10550. var pathFill = this.style.fill;
  10551. if (isString(pathFill)) {
  10552. var zr = this.__zr;
  10553. var isDarkMode = !!(zr && zr.isDarkMode());
  10554. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10555. if (isDarkMode === isDarkLabel) {
  10556. return pathFill;
  10557. }
  10558. }
  10559. };
  10560. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10561. Path.prototype.pathUpdated = function () {
  10562. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10563. };
  10564. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10565. !this.path && this.createPathProxy();
  10566. this.path.beginPath();
  10567. this.buildPath(this.path, this.shape, inBatch);
  10568. return this.path;
  10569. };
  10570. Path.prototype.createPathProxy = function () {
  10571. this.path = new PathProxy(false);
  10572. };
  10573. Path.prototype.hasStroke = function () {
  10574. var style = this.style;
  10575. var stroke = style.stroke;
  10576. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10577. };
  10578. Path.prototype.hasFill = function () {
  10579. var style = this.style;
  10580. var fill = style.fill;
  10581. return fill != null && fill !== 'none';
  10582. };
  10583. Path.prototype.getBoundingRect = function () {
  10584. var rect = this._rect;
  10585. var style = this.style;
  10586. var needsUpdateRect = !rect;
  10587. if (needsUpdateRect) {
  10588. var firstInvoke = false;
  10589. if (!this.path) {
  10590. firstInvoke = true;
  10591. this.createPathProxy();
  10592. }
  10593. var path = this.path;
  10594. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10595. path.beginPath();
  10596. this.buildPath(path, this.shape, false);
  10597. this.pathUpdated();
  10598. }
  10599. rect = path.getBoundingRect();
  10600. }
  10601. this._rect = rect;
  10602. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10603. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  10604. if (this.__dirty || needsUpdateRect) {
  10605. rectStroke.copy(rect);
  10606. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10607. var w = style.lineWidth;
  10608. if (!this.hasFill()) {
  10609. var strokeContainThreshold = this.strokeContainThreshold;
  10610. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10611. }
  10612. if (lineScale > 1e-10) {
  10613. rectStroke.width += w / lineScale;
  10614. rectStroke.height += w / lineScale;
  10615. rectStroke.x -= w / lineScale / 2;
  10616. rectStroke.y -= w / lineScale / 2;
  10617. }
  10618. }
  10619. return rectStroke;
  10620. }
  10621. return rect;
  10622. };
  10623. Path.prototype.contain = function (x, y) {
  10624. var localPos = this.transformCoordToLocal(x, y);
  10625. var rect = this.getBoundingRect();
  10626. var style = this.style;
  10627. x = localPos[0];
  10628. y = localPos[1];
  10629. if (rect.contain(x, y)) {
  10630. var pathProxy = this.path;
  10631. if (this.hasStroke()) {
  10632. var lineWidth = style.lineWidth;
  10633. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10634. if (lineScale > 1e-10) {
  10635. if (!this.hasFill()) {
  10636. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10637. }
  10638. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10639. return true;
  10640. }
  10641. }
  10642. }
  10643. if (this.hasFill()) {
  10644. return contain(pathProxy, x, y);
  10645. }
  10646. }
  10647. return false;
  10648. };
  10649. Path.prototype.dirtyShape = function () {
  10650. this.__dirty |= SHAPE_CHANGED_BIT;
  10651. if (this._rect) {
  10652. this._rect = null;
  10653. }
  10654. if (this._decalEl) {
  10655. this._decalEl.dirtyShape();
  10656. }
  10657. this.markRedraw();
  10658. };
  10659. Path.prototype.dirty = function () {
  10660. this.dirtyStyle();
  10661. this.dirtyShape();
  10662. };
  10663. Path.prototype.animateShape = function (loop) {
  10664. return this.animate('shape', loop);
  10665. };
  10666. Path.prototype.updateDuringAnimation = function (targetKey) {
  10667. if (targetKey === 'style') {
  10668. this.dirtyStyle();
  10669. }
  10670. else if (targetKey === 'shape') {
  10671. this.dirtyShape();
  10672. }
  10673. else {
  10674. this.markRedraw();
  10675. }
  10676. };
  10677. Path.prototype.attrKV = function (key, value) {
  10678. if (key === 'shape') {
  10679. this.setShape(value);
  10680. }
  10681. else {
  10682. _super.prototype.attrKV.call(this, key, value);
  10683. }
  10684. };
  10685. Path.prototype.setShape = function (keyOrObj, value) {
  10686. var shape = this.shape;
  10687. if (!shape) {
  10688. shape = this.shape = {};
  10689. }
  10690. if (typeof keyOrObj === 'string') {
  10691. shape[keyOrObj] = value;
  10692. }
  10693. else {
  10694. extend(shape, keyOrObj);
  10695. }
  10696. this.dirtyShape();
  10697. return this;
  10698. };
  10699. Path.prototype.shapeChanged = function () {
  10700. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  10701. };
  10702. Path.prototype.createStyle = function (obj) {
  10703. return createObject(DEFAULT_PATH_STYLE, obj);
  10704. };
  10705. Path.prototype._innerSaveToNormal = function (toState) {
  10706. _super.prototype._innerSaveToNormal.call(this, toState);
  10707. var normalState = this._normalState;
  10708. if (toState.shape && !normalState.shape) {
  10709. normalState.shape = extend({}, this.shape);
  10710. }
  10711. };
  10712. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10713. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10714. var needsRestoreToNormal = !(state && keepCurrentStates);
  10715. var targetShape;
  10716. if (state && state.shape) {
  10717. if (transition) {
  10718. if (keepCurrentStates) {
  10719. targetShape = state.shape;
  10720. }
  10721. else {
  10722. targetShape = extend({}, normalState.shape);
  10723. extend(targetShape, state.shape);
  10724. }
  10725. }
  10726. else {
  10727. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  10728. extend(targetShape, state.shape);
  10729. }
  10730. }
  10731. else if (needsRestoreToNormal) {
  10732. targetShape = normalState.shape;
  10733. }
  10734. if (targetShape) {
  10735. if (transition) {
  10736. this.shape = extend({}, this.shape);
  10737. var targetShapePrimaryProps = {};
  10738. var shapeKeys = keys(targetShape);
  10739. for (var i = 0; i < shapeKeys.length; i++) {
  10740. var key = shapeKeys[i];
  10741. if (typeof targetShape[key] === 'object') {
  10742. this.shape[key] = targetShape[key];
  10743. }
  10744. else {
  10745. targetShapePrimaryProps[key] = targetShape[key];
  10746. }
  10747. }
  10748. this._transitionState(stateName, {
  10749. shape: targetShapePrimaryProps
  10750. }, animationCfg);
  10751. }
  10752. else {
  10753. this.shape = targetShape;
  10754. this.dirtyShape();
  10755. }
  10756. }
  10757. };
  10758. Path.prototype._mergeStates = function (states) {
  10759. var mergedState = _super.prototype._mergeStates.call(this, states);
  10760. var mergedShape;
  10761. for (var i = 0; i < states.length; i++) {
  10762. var state = states[i];
  10763. if (state.shape) {
  10764. mergedShape = mergedShape || {};
  10765. this._mergeStyle(mergedShape, state.shape);
  10766. }
  10767. }
  10768. if (mergedShape) {
  10769. mergedState.shape = mergedShape;
  10770. }
  10771. return mergedState;
  10772. };
  10773. Path.prototype.getAnimationStyleProps = function () {
  10774. return DEFAULT_PATH_ANIMATION_PROPS;
  10775. };
  10776. Path.prototype.isZeroArea = function () {
  10777. return false;
  10778. };
  10779. Path.extend = function (defaultProps) {
  10780. var Sub = (function (_super) {
  10781. __extends(Sub, _super);
  10782. function Sub(opts) {
  10783. var _this = _super.call(this, opts) || this;
  10784. defaultProps.init && defaultProps.init.call(_this, opts);
  10785. return _this;
  10786. }
  10787. Sub.prototype.getDefaultStyle = function () {
  10788. return clone(defaultProps.style);
  10789. };
  10790. Sub.prototype.getDefaultShape = function () {
  10791. return clone(defaultProps.shape);
  10792. };
  10793. return Sub;
  10794. }(Path));
  10795. for (var key in defaultProps) {
  10796. if (typeof defaultProps[key] === 'function') {
  10797. Sub.prototype[key] = defaultProps[key];
  10798. }
  10799. }
  10800. return Sub;
  10801. };
  10802. Path.initDefaultProps = (function () {
  10803. var pathProto = Path.prototype;
  10804. pathProto.type = 'path';
  10805. pathProto.strokeContainThreshold = 5;
  10806. pathProto.segmentIgnoreThreshold = 0;
  10807. pathProto.subPixelOptimize = false;
  10808. pathProto.autoBatch = false;
  10809. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  10810. })();
  10811. return Path;
  10812. }(Displayable));
  10813. var DEFAULT_TSPAN_STYLE = defaults({
  10814. strokeFirst: true,
  10815. font: DEFAULT_FONT,
  10816. x: 0,
  10817. y: 0,
  10818. textAlign: 'left',
  10819. textBaseline: 'top',
  10820. miterLimit: 2
  10821. }, DEFAULT_PATH_STYLE);
  10822. var TSpan = (function (_super) {
  10823. __extends(TSpan, _super);
  10824. function TSpan() {
  10825. return _super !== null && _super.apply(this, arguments) || this;
  10826. }
  10827. TSpan.prototype.hasStroke = function () {
  10828. var style = this.style;
  10829. var stroke = style.stroke;
  10830. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  10831. };
  10832. TSpan.prototype.hasFill = function () {
  10833. var style = this.style;
  10834. var fill = style.fill;
  10835. return fill != null && fill !== 'none';
  10836. };
  10837. TSpan.prototype.createStyle = function (obj) {
  10838. return createObject(DEFAULT_TSPAN_STYLE, obj);
  10839. };
  10840. TSpan.prototype.setBoundingRect = function (rect) {
  10841. this._rect = rect;
  10842. };
  10843. TSpan.prototype.getBoundingRect = function () {
  10844. var style = this.style;
  10845. if (!this._rect) {
  10846. var text = style.text;
  10847. text != null ? (text += '') : (text = '');
  10848. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  10849. rect.x += style.x || 0;
  10850. rect.y += style.y || 0;
  10851. if (this.hasStroke()) {
  10852. var w = style.lineWidth;
  10853. rect.x -= w / 2;
  10854. rect.y -= w / 2;
  10855. rect.width += w;
  10856. rect.height += w;
  10857. }
  10858. this._rect = rect;
  10859. }
  10860. return this._rect;
  10861. };
  10862. TSpan.initDefaultProps = (function () {
  10863. var tspanProto = TSpan.prototype;
  10864. tspanProto.dirtyRectTolerance = 10;
  10865. })();
  10866. return TSpan;
  10867. }(Displayable));
  10868. TSpan.prototype.type = 'tspan';
  10869. var DEFAULT_IMAGE_STYLE = defaults({
  10870. x: 0,
  10871. y: 0
  10872. }, DEFAULT_COMMON_STYLE);
  10873. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  10874. style: defaults({
  10875. x: true,
  10876. y: true,
  10877. width: true,
  10878. height: true,
  10879. sx: true,
  10880. sy: true,
  10881. sWidth: true,
  10882. sHeight: true
  10883. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10884. };
  10885. function isImageLike(source) {
  10886. return !!(source
  10887. && typeof source !== 'string'
  10888. && source.width && source.height);
  10889. }
  10890. var ZRImage = (function (_super) {
  10891. __extends(ZRImage, _super);
  10892. function ZRImage() {
  10893. return _super !== null && _super.apply(this, arguments) || this;
  10894. }
  10895. ZRImage.prototype.createStyle = function (obj) {
  10896. return createObject(DEFAULT_IMAGE_STYLE, obj);
  10897. };
  10898. ZRImage.prototype._getSize = function (dim) {
  10899. var style = this.style;
  10900. var size = style[dim];
  10901. if (size != null) {
  10902. return size;
  10903. }
  10904. var imageSource = isImageLike(style.image)
  10905. ? style.image : this.__image;
  10906. if (!imageSource) {
  10907. return 0;
  10908. }
  10909. var otherDim = dim === 'width' ? 'height' : 'width';
  10910. var otherDimSize = style[otherDim];
  10911. if (otherDimSize == null) {
  10912. return imageSource[dim];
  10913. }
  10914. else {
  10915. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  10916. }
  10917. };
  10918. ZRImage.prototype.getWidth = function () {
  10919. return this._getSize('width');
  10920. };
  10921. ZRImage.prototype.getHeight = function () {
  10922. return this._getSize('height');
  10923. };
  10924. ZRImage.prototype.getAnimationStyleProps = function () {
  10925. return DEFAULT_IMAGE_ANIMATION_PROPS;
  10926. };
  10927. ZRImage.prototype.getBoundingRect = function () {
  10928. var style = this.style;
  10929. if (!this._rect) {
  10930. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  10931. }
  10932. return this._rect;
  10933. };
  10934. return ZRImage;
  10935. }(Displayable));
  10936. ZRImage.prototype.type = 'image';
  10937. function buildPath(ctx, shape) {
  10938. var x = shape.x;
  10939. var y = shape.y;
  10940. var width = shape.width;
  10941. var height = shape.height;
  10942. var r = shape.r;
  10943. var r1;
  10944. var r2;
  10945. var r3;
  10946. var r4;
  10947. if (width < 0) {
  10948. x = x + width;
  10949. width = -width;
  10950. }
  10951. if (height < 0) {
  10952. y = y + height;
  10953. height = -height;
  10954. }
  10955. if (typeof r === 'number') {
  10956. r1 = r2 = r3 = r4 = r;
  10957. }
  10958. else if (r instanceof Array) {
  10959. if (r.length === 1) {
  10960. r1 = r2 = r3 = r4 = r[0];
  10961. }
  10962. else if (r.length === 2) {
  10963. r1 = r3 = r[0];
  10964. r2 = r4 = r[1];
  10965. }
  10966. else if (r.length === 3) {
  10967. r1 = r[0];
  10968. r2 = r4 = r[1];
  10969. r3 = r[2];
  10970. }
  10971. else {
  10972. r1 = r[0];
  10973. r2 = r[1];
  10974. r3 = r[2];
  10975. r4 = r[3];
  10976. }
  10977. }
  10978. else {
  10979. r1 = r2 = r3 = r4 = 0;
  10980. }
  10981. var total;
  10982. if (r1 + r2 > width) {
  10983. total = r1 + r2;
  10984. r1 *= width / total;
  10985. r2 *= width / total;
  10986. }
  10987. if (r3 + r4 > width) {
  10988. total = r3 + r4;
  10989. r3 *= width / total;
  10990. r4 *= width / total;
  10991. }
  10992. if (r2 + r3 > height) {
  10993. total = r2 + r3;
  10994. r2 *= height / total;
  10995. r3 *= height / total;
  10996. }
  10997. if (r1 + r4 > height) {
  10998. total = r1 + r4;
  10999. r1 *= height / total;
  11000. r4 *= height / total;
  11001. }
  11002. ctx.moveTo(x + r1, y);
  11003. ctx.lineTo(x + width - r2, y);
  11004. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11005. ctx.lineTo(x + width, y + height - r3);
  11006. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11007. ctx.lineTo(x + r4, y + height);
  11008. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11009. ctx.lineTo(x, y + r1);
  11010. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11011. }
  11012. var round$1 = Math.round;
  11013. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11014. if (!inputShape) {
  11015. return;
  11016. }
  11017. var x1 = inputShape.x1;
  11018. var x2 = inputShape.x2;
  11019. var y1 = inputShape.y1;
  11020. var y2 = inputShape.y2;
  11021. outputShape.x1 = x1;
  11022. outputShape.x2 = x2;
  11023. outputShape.y1 = y1;
  11024. outputShape.y2 = y2;
  11025. var lineWidth = style && style.lineWidth;
  11026. if (!lineWidth) {
  11027. return outputShape;
  11028. }
  11029. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11030. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11031. }
  11032. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11033. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11034. }
  11035. return outputShape;
  11036. }
  11037. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11038. if (!inputShape) {
  11039. return;
  11040. }
  11041. var originX = inputShape.x;
  11042. var originY = inputShape.y;
  11043. var originWidth = inputShape.width;
  11044. var originHeight = inputShape.height;
  11045. outputShape.x = originX;
  11046. outputShape.y = originY;
  11047. outputShape.width = originWidth;
  11048. outputShape.height = originHeight;
  11049. var lineWidth = style && style.lineWidth;
  11050. if (!lineWidth) {
  11051. return outputShape;
  11052. }
  11053. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11054. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11055. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11056. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11057. return outputShape;
  11058. }
  11059. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11060. if (!lineWidth) {
  11061. return position;
  11062. }
  11063. var doubledPosition = round$1(position * 2);
  11064. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11065. ? doubledPosition / 2
  11066. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11067. }
  11068. var RectShape = (function () {
  11069. function RectShape() {
  11070. this.x = 0;
  11071. this.y = 0;
  11072. this.width = 0;
  11073. this.height = 0;
  11074. }
  11075. return RectShape;
  11076. }());
  11077. var subPixelOptimizeOutputShape = {};
  11078. var Rect = (function (_super) {
  11079. __extends(Rect, _super);
  11080. function Rect(opts) {
  11081. return _super.call(this, opts) || this;
  11082. }
  11083. Rect.prototype.getDefaultShape = function () {
  11084. return new RectShape();
  11085. };
  11086. Rect.prototype.buildPath = function (ctx, shape) {
  11087. var x;
  11088. var y;
  11089. var width;
  11090. var height;
  11091. if (this.subPixelOptimize) {
  11092. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11093. x = optimizedShape.x;
  11094. y = optimizedShape.y;
  11095. width = optimizedShape.width;
  11096. height = optimizedShape.height;
  11097. optimizedShape.r = shape.r;
  11098. shape = optimizedShape;
  11099. }
  11100. else {
  11101. x = shape.x;
  11102. y = shape.y;
  11103. width = shape.width;
  11104. height = shape.height;
  11105. }
  11106. if (!shape.r) {
  11107. ctx.rect(x, y, width, height);
  11108. }
  11109. else {
  11110. buildPath(ctx, shape);
  11111. }
  11112. };
  11113. Rect.prototype.isZeroArea = function () {
  11114. return !this.shape.width || !this.shape.height;
  11115. };
  11116. return Rect;
  11117. }(Path));
  11118. Rect.prototype.type = 'rect';
  11119. var DEFAULT_RICH_TEXT_COLOR = {
  11120. fill: '#000'
  11121. };
  11122. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11123. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11124. style: defaults({
  11125. fill: true,
  11126. stroke: true,
  11127. fillOpacity: true,
  11128. strokeOpacity: true,
  11129. lineWidth: true,
  11130. fontSize: true,
  11131. lineHeight: true,
  11132. width: true,
  11133. height: true,
  11134. textShadowColor: true,
  11135. textShadowBlur: true,
  11136. textShadowOffsetX: true,
  11137. textShadowOffsetY: true,
  11138. backgroundColor: true,
  11139. padding: true,
  11140. borderColor: true,
  11141. borderWidth: true,
  11142. borderRadius: true
  11143. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11144. };
  11145. var ZRText = (function (_super) {
  11146. __extends(ZRText, _super);
  11147. function ZRText(opts) {
  11148. var _this = _super.call(this) || this;
  11149. _this.type = 'text';
  11150. _this._children = [];
  11151. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11152. _this.attr(opts);
  11153. return _this;
  11154. }
  11155. ZRText.prototype.childrenRef = function () {
  11156. return this._children;
  11157. };
  11158. ZRText.prototype.update = function () {
  11159. _super.prototype.update.call(this);
  11160. if (this.styleChanged()) {
  11161. this._updateSubTexts();
  11162. }
  11163. for (var i = 0; i < this._children.length; i++) {
  11164. var child = this._children[i];
  11165. child.zlevel = this.zlevel;
  11166. child.z = this.z;
  11167. child.z2 = this.z2;
  11168. child.culling = this.culling;
  11169. child.cursor = this.cursor;
  11170. child.invisible = this.invisible;
  11171. }
  11172. };
  11173. ZRText.prototype.updateTransform = function () {
  11174. var innerTransformable = this.innerTransformable;
  11175. if (innerTransformable) {
  11176. innerTransformable.updateTransform();
  11177. if (innerTransformable.transform) {
  11178. this.transform = innerTransformable.transform;
  11179. }
  11180. }
  11181. else {
  11182. _super.prototype.updateTransform.call(this);
  11183. }
  11184. };
  11185. ZRText.prototype.getLocalTransform = function (m) {
  11186. var innerTransformable = this.innerTransformable;
  11187. return innerTransformable
  11188. ? innerTransformable.getLocalTransform(m)
  11189. : _super.prototype.getLocalTransform.call(this, m);
  11190. };
  11191. ZRText.prototype.getComputedTransform = function () {
  11192. if (this.__hostTarget) {
  11193. this.__hostTarget.getComputedTransform();
  11194. this.__hostTarget.updateInnerText(true);
  11195. }
  11196. return _super.prototype.getComputedTransform.call(this);
  11197. };
  11198. ZRText.prototype._updateSubTexts = function () {
  11199. this._childCursor = 0;
  11200. normalizeTextStyle(this.style);
  11201. this.style.rich
  11202. ? this._updateRichTexts()
  11203. : this._updatePlainTexts();
  11204. this._children.length = this._childCursor;
  11205. this.styleUpdated();
  11206. };
  11207. ZRText.prototype.addSelfToZr = function (zr) {
  11208. _super.prototype.addSelfToZr.call(this, zr);
  11209. for (var i = 0; i < this._children.length; i++) {
  11210. this._children[i].__zr = zr;
  11211. }
  11212. };
  11213. ZRText.prototype.removeSelfFromZr = function (zr) {
  11214. _super.prototype.removeSelfFromZr.call(this, zr);
  11215. for (var i = 0; i < this._children.length; i++) {
  11216. this._children[i].__zr = null;
  11217. }
  11218. };
  11219. ZRText.prototype.getBoundingRect = function () {
  11220. if (this.styleChanged()) {
  11221. this._updateSubTexts();
  11222. }
  11223. if (!this._rect) {
  11224. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11225. var children = this._children;
  11226. var tmpMat = [];
  11227. var rect = null;
  11228. for (var i = 0; i < children.length; i++) {
  11229. var child = children[i];
  11230. var childRect = child.getBoundingRect();
  11231. var transform = child.getLocalTransform(tmpMat);
  11232. if (transform) {
  11233. tmpRect.copy(childRect);
  11234. tmpRect.applyTransform(transform);
  11235. rect = rect || tmpRect.clone();
  11236. rect.union(tmpRect);
  11237. }
  11238. else {
  11239. rect = rect || childRect.clone();
  11240. rect.union(childRect);
  11241. }
  11242. }
  11243. this._rect = rect || tmpRect;
  11244. }
  11245. return this._rect;
  11246. };
  11247. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11248. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11249. };
  11250. ZRText.prototype.setTextContent = function (textContent) {
  11251. if ("development" !== 'production') {
  11252. throw new Error('Can\'t attach text on another text');
  11253. }
  11254. };
  11255. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11256. if (!sourceStyle) {
  11257. return targetStyle;
  11258. }
  11259. var sourceRich = sourceStyle.rich;
  11260. var targetRich = targetStyle.rich || (sourceRich && {});
  11261. extend(targetStyle, sourceStyle);
  11262. if (sourceRich && targetRich) {
  11263. this._mergeRich(targetRich, sourceRich);
  11264. targetStyle.rich = targetRich;
  11265. }
  11266. else if (targetRich) {
  11267. targetStyle.rich = targetRich;
  11268. }
  11269. return targetStyle;
  11270. };
  11271. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11272. var richNames = keys(sourceRich);
  11273. for (var i = 0; i < richNames.length; i++) {
  11274. var richName = richNames[i];
  11275. targetRich[richName] = targetRich[richName] || {};
  11276. extend(targetRich[richName], sourceRich[richName]);
  11277. }
  11278. };
  11279. ZRText.prototype.getAnimationStyleProps = function () {
  11280. return DEFAULT_TEXT_ANIMATION_PROPS;
  11281. };
  11282. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11283. var child = this._children[this._childCursor];
  11284. if (!child || !(child instanceof Ctor)) {
  11285. child = new Ctor();
  11286. }
  11287. this._children[this._childCursor++] = child;
  11288. child.__zr = this.__zr;
  11289. child.parent = this;
  11290. return child;
  11291. };
  11292. ZRText.prototype._updatePlainTexts = function () {
  11293. var style = this.style;
  11294. var textFont = style.font || DEFAULT_FONT;
  11295. var textPadding = style.padding;
  11296. var text = getStyleText(style);
  11297. var contentBlock = parsePlainText(text, style);
  11298. var needDrawBg = needDrawBackground(style);
  11299. var bgColorDrawn = !!(style.backgroundColor);
  11300. var outerHeight = contentBlock.outerHeight;
  11301. var outerWidth = contentBlock.outerWidth;
  11302. var contentWidth = contentBlock.contentWidth;
  11303. var textLines = contentBlock.lines;
  11304. var lineHeight = contentBlock.lineHeight;
  11305. var defaultStyle = this._defaultStyle;
  11306. var baseX = style.x || 0;
  11307. var baseY = style.y || 0;
  11308. var textAlign = style.align || defaultStyle.align || 'left';
  11309. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11310. var textX = baseX;
  11311. var textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign);
  11312. if (needDrawBg || textPadding) {
  11313. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11314. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11315. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11316. }
  11317. textY += lineHeight / 2;
  11318. if (textPadding) {
  11319. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11320. if (verticalAlign === 'top') {
  11321. textY += textPadding[0];
  11322. }
  11323. else if (verticalAlign === 'bottom') {
  11324. textY -= textPadding[2];
  11325. }
  11326. }
  11327. var defaultLineWidth = 0;
  11328. var useDefaultFill = false;
  11329. var textFill = getFill('fill' in style
  11330. ? style.fill
  11331. : (useDefaultFill = true, defaultStyle.fill));
  11332. var textStroke = getStroke('stroke' in style
  11333. ? style.stroke
  11334. : (!bgColorDrawn
  11335. && (!defaultStyle.autoStroke || useDefaultFill))
  11336. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11337. : null);
  11338. var hasShadow = style.textShadowBlur > 0;
  11339. var fixedBoundingRect = style.width != null
  11340. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11341. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11342. for (var i = 0; i < textLines.length; i++) {
  11343. var el = this._getOrCreateChild(TSpan);
  11344. var subElStyle = el.createStyle();
  11345. el.useStyle(subElStyle);
  11346. subElStyle.text = textLines[i];
  11347. subElStyle.x = textX;
  11348. subElStyle.y = textY;
  11349. if (textAlign) {
  11350. subElStyle.textAlign = textAlign;
  11351. }
  11352. subElStyle.textBaseline = 'middle';
  11353. subElStyle.opacity = style.opacity;
  11354. subElStyle.strokeFirst = true;
  11355. if (hasShadow) {
  11356. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11357. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11358. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11359. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11360. }
  11361. subElStyle.stroke = textStroke;
  11362. subElStyle.fill = textFill;
  11363. if (textStroke) {
  11364. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11365. subElStyle.lineDash = style.lineDash;
  11366. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11367. }
  11368. subElStyle.font = textFont;
  11369. setSeparateFont(subElStyle, style);
  11370. textY += lineHeight;
  11371. if (fixedBoundingRect) {
  11372. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11373. }
  11374. }
  11375. };
  11376. ZRText.prototype._updateRichTexts = function () {
  11377. var style = this.style;
  11378. var text = getStyleText(style);
  11379. var contentBlock = parseRichText(text, style);
  11380. var contentWidth = contentBlock.width;
  11381. var outerWidth = contentBlock.outerWidth;
  11382. var outerHeight = contentBlock.outerHeight;
  11383. var textPadding = style.padding;
  11384. var baseX = style.x || 0;
  11385. var baseY = style.y || 0;
  11386. var defaultStyle = this._defaultStyle;
  11387. var textAlign = style.align || defaultStyle.align;
  11388. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11389. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11390. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11391. var xLeft = boxX;
  11392. var lineTop = boxY;
  11393. if (textPadding) {
  11394. xLeft += textPadding[3];
  11395. lineTop += textPadding[0];
  11396. }
  11397. var xRight = xLeft + contentWidth;
  11398. if (needDrawBackground(style)) {
  11399. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11400. }
  11401. var bgColorDrawn = !!(style.backgroundColor);
  11402. for (var i = 0; i < contentBlock.lines.length; i++) {
  11403. var line = contentBlock.lines[i];
  11404. var tokens = line.tokens;
  11405. var tokenCount = tokens.length;
  11406. var lineHeight = line.lineHeight;
  11407. var remainedWidth = line.width;
  11408. var leftIndex = 0;
  11409. var lineXLeft = xLeft;
  11410. var lineXRight = xRight;
  11411. var rightIndex = tokenCount - 1;
  11412. var token = void 0;
  11413. while (leftIndex < tokenCount
  11414. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11415. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11416. remainedWidth -= token.width;
  11417. lineXLeft += token.width;
  11418. leftIndex++;
  11419. }
  11420. while (rightIndex >= 0
  11421. && (token = tokens[rightIndex], token.align === 'right')) {
  11422. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11423. remainedWidth -= token.width;
  11424. lineXRight -= token.width;
  11425. rightIndex--;
  11426. }
  11427. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11428. while (leftIndex <= rightIndex) {
  11429. token = tokens[leftIndex];
  11430. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11431. lineXLeft += token.width;
  11432. leftIndex++;
  11433. }
  11434. lineTop += lineHeight;
  11435. }
  11436. };
  11437. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11438. var tokenStyle = style.rich[token.styleName] || {};
  11439. tokenStyle.text = token.text;
  11440. var verticalAlign = token.verticalAlign;
  11441. var y = lineTop + lineHeight / 2;
  11442. if (verticalAlign === 'top') {
  11443. y = lineTop + token.height / 2;
  11444. }
  11445. else if (verticalAlign === 'bottom') {
  11446. y = lineTop + lineHeight - token.height / 2;
  11447. }
  11448. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11449. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11450. ? x - token.width
  11451. : textAlign === 'center'
  11452. ? x - token.width / 2
  11453. : x, y - token.height / 2, token.width, token.height);
  11454. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11455. var textPadding = token.textPadding;
  11456. if (textPadding) {
  11457. x = getTextXForPadding(x, textAlign, textPadding);
  11458. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11459. }
  11460. var el = this._getOrCreateChild(TSpan);
  11461. var subElStyle = el.createStyle();
  11462. el.useStyle(subElStyle);
  11463. var defaultStyle = this._defaultStyle;
  11464. var useDefaultFill = false;
  11465. var defaultLineWidth = 0;
  11466. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11467. : 'fill' in style ? style.fill
  11468. : (useDefaultFill = true, defaultStyle.fill));
  11469. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11470. : 'stroke' in style ? style.stroke
  11471. : (!bgColorDrawn
  11472. && !parentBgColorDrawn
  11473. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11474. : null);
  11475. var hasShadow = tokenStyle.textShadowBlur > 0
  11476. || style.textShadowBlur > 0;
  11477. subElStyle.text = token.text;
  11478. subElStyle.x = x;
  11479. subElStyle.y = y;
  11480. if (hasShadow) {
  11481. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11482. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11483. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11484. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11485. }
  11486. subElStyle.textAlign = textAlign;
  11487. subElStyle.textBaseline = 'middle';
  11488. subElStyle.font = token.font || DEFAULT_FONT;
  11489. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11490. setSeparateFont(subElStyle, tokenStyle);
  11491. if (textStroke) {
  11492. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11493. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11494. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11495. subElStyle.stroke = textStroke;
  11496. }
  11497. if (textFill) {
  11498. subElStyle.fill = textFill;
  11499. }
  11500. var textWidth = token.contentWidth;
  11501. var textHeight = token.contentHeight;
  11502. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11503. };
  11504. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11505. var textBackgroundColor = style.backgroundColor;
  11506. var textBorderWidth = style.borderWidth;
  11507. var textBorderColor = style.borderColor;
  11508. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11509. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11510. var textBorderRadius = style.borderRadius;
  11511. var self = this;
  11512. var rectEl;
  11513. var imgEl;
  11514. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11515. rectEl = this._getOrCreateChild(Rect);
  11516. rectEl.useStyle(rectEl.createStyle());
  11517. rectEl.style.fill = null;
  11518. var rectShape = rectEl.shape;
  11519. rectShape.x = x;
  11520. rectShape.y = y;
  11521. rectShape.width = width;
  11522. rectShape.height = height;
  11523. rectShape.r = textBorderRadius;
  11524. rectEl.dirtyShape();
  11525. }
  11526. if (isPlainOrGradientBg) {
  11527. var rectStyle = rectEl.style;
  11528. rectStyle.fill = textBackgroundColor || null;
  11529. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11530. }
  11531. else if (isImageBg) {
  11532. imgEl = this._getOrCreateChild(ZRImage);
  11533. imgEl.onload = function () {
  11534. self.dirtyStyle();
  11535. };
  11536. var imgStyle = imgEl.style;
  11537. imgStyle.image = textBackgroundColor.image;
  11538. imgStyle.x = x;
  11539. imgStyle.y = y;
  11540. imgStyle.width = width;
  11541. imgStyle.height = height;
  11542. }
  11543. if (textBorderWidth && textBorderColor) {
  11544. var rectStyle = rectEl.style;
  11545. rectStyle.lineWidth = textBorderWidth;
  11546. rectStyle.stroke = textBorderColor;
  11547. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11548. rectStyle.lineDash = style.borderDash;
  11549. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11550. rectEl.strokeContainThreshold = 0;
  11551. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11552. rectStyle.strokeFirst = true;
  11553. rectStyle.lineWidth *= 2;
  11554. }
  11555. }
  11556. var commonStyle = (rectEl || imgEl).style;
  11557. commonStyle.shadowBlur = style.shadowBlur || 0;
  11558. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11559. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11560. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11561. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11562. };
  11563. ZRText.makeFont = function (style) {
  11564. var font = '';
  11565. if (hasSeparateFont(style)) {
  11566. font = [
  11567. style.fontStyle,
  11568. style.fontWeight,
  11569. parseFontSize(style.fontSize),
  11570. style.fontFamily || 'sans-serif'
  11571. ].join(' ');
  11572. }
  11573. return font && trim(font) || style.textFont || style.font;
  11574. };
  11575. return ZRText;
  11576. }(Displayable));
  11577. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11578. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11579. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  11580. function parseFontSize(fontSize) {
  11581. if (typeof fontSize === 'string'
  11582. && (fontSize.indexOf('px') !== -1
  11583. || fontSize.indexOf('rem') !== -1
  11584. || fontSize.indexOf('em') !== -1)) {
  11585. return fontSize;
  11586. }
  11587. else if (!isNaN(+fontSize)) {
  11588. return fontSize + 'px';
  11589. }
  11590. else {
  11591. return DEFAULT_FONT_SIZE + 'px';
  11592. }
  11593. }
  11594. function setSeparateFont(targetStyle, sourceStyle) {
  11595. for (var i = 0; i < FONT_PARTS.length; i++) {
  11596. var fontProp = FONT_PARTS[i];
  11597. var val = sourceStyle[fontProp];
  11598. if (val != null) {
  11599. targetStyle[fontProp] = val;
  11600. }
  11601. }
  11602. }
  11603. function hasSeparateFont(style) {
  11604. return style.fontSize != null || style.fontFamily || style.fontWeight;
  11605. }
  11606. function normalizeTextStyle(style) {
  11607. normalizeStyle(style);
  11608. each(style.rich, normalizeStyle);
  11609. return style;
  11610. }
  11611. function normalizeStyle(style) {
  11612. if (style) {
  11613. style.font = ZRText.makeFont(style);
  11614. var textAlign = style.align;
  11615. textAlign === 'middle' && (textAlign = 'center');
  11616. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11617. var verticalAlign = style.verticalAlign;
  11618. verticalAlign === 'center' && (verticalAlign = 'middle');
  11619. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11620. var textPadding = style.padding;
  11621. if (textPadding) {
  11622. style.padding = normalizeCssArray(style.padding);
  11623. }
  11624. }
  11625. }
  11626. function getStroke(stroke, lineWidth) {
  11627. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11628. ? null
  11629. : (stroke.image || stroke.colorStops)
  11630. ? '#000'
  11631. : stroke;
  11632. }
  11633. function getFill(fill) {
  11634. return (fill == null || fill === 'none')
  11635. ? null
  11636. : (fill.image || fill.colorStops)
  11637. ? '#000'
  11638. : fill;
  11639. }
  11640. function getTextXForPadding(x, textAlign, textPadding) {
  11641. return textAlign === 'right'
  11642. ? (x - textPadding[1])
  11643. : textAlign === 'center'
  11644. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11645. : (x + textPadding[3]);
  11646. }
  11647. function getStyleText(style) {
  11648. var text = style.text;
  11649. text != null && (text += '');
  11650. return text;
  11651. }
  11652. function needDrawBackground(style) {
  11653. return !!(style.backgroundColor
  11654. || style.lineHeight
  11655. || (style.borderWidth && style.borderColor));
  11656. }
  11657. var getECData = makeInner();
  11658. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  11659. if (el) {
  11660. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  11661. // Useful in tooltip
  11662. ecData.dataIndex = dataIdx;
  11663. ecData.dataType = dataType;
  11664. ecData.seriesIndex = seriesIndex; // TODO: not store dataIndex on children.
  11665. if (el.type === 'group') {
  11666. el.traverse(function (child) {
  11667. var childECData = getECData(child);
  11668. childECData.seriesIndex = seriesIndex;
  11669. childECData.dataIndex = dataIdx;
  11670. childECData.dataType = dataType;
  11671. });
  11672. }
  11673. }
  11674. };
  11675. var _highlightNextDigit = 1;
  11676. var _highlightKeyMap = {};
  11677. var getSavedStates = makeInner();
  11678. var getComponentStates = makeInner();
  11679. var HOVER_STATE_NORMAL = 0;
  11680. var HOVER_STATE_BLUR = 1;
  11681. var HOVER_STATE_EMPHASIS = 2;
  11682. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11683. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11684. var Z2_EMPHASIS_LIFT = 10;
  11685. var Z2_SELECT_LIFT = 9;
  11686. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11687. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11688. var SELECT_ACTION_TYPE = 'select';
  11689. var UNSELECT_ACTION_TYPE = 'unselect';
  11690. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11691. function hasFillOrStroke(fillOrStroke) {
  11692. return fillOrStroke != null && fillOrStroke !== 'none';
  11693. } // Most lifted color are duplicated.
  11694. var liftedColorCache = new LRU(100);
  11695. function liftColor(color$1) {
  11696. if (isString(color$1)) {
  11697. var liftedColor = liftedColorCache.get(color$1);
  11698. if (!liftedColor) {
  11699. liftedColor = lift(color$1, -0.1);
  11700. liftedColorCache.put(color$1, liftedColor);
  11701. }
  11702. return liftedColor;
  11703. } else if (isGradientObject(color$1)) {
  11704. var ret = extend({}, color$1);
  11705. ret.colorStops = map(color$1.colorStops, function (stop) {
  11706. return {
  11707. offset: stop.offset,
  11708. color: lift(stop.color, -0.1)
  11709. };
  11710. });
  11711. return ret;
  11712. } // Change nothing.
  11713. return color$1;
  11714. }
  11715. function doChangeHoverState(el, stateName, hoverStateEnum) {
  11716. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  11717. el.onHoverStateChange(stateName);
  11718. }
  11719. el.hoverState = hoverStateEnum;
  11720. }
  11721. function singleEnterEmphasis(el) {
  11722. // Only mark the flag.
  11723. // States will be applied in the echarts.ts in next frame.
  11724. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  11725. }
  11726. function singleLeaveEmphasis(el) {
  11727. // Only mark the flag.
  11728. // States will be applied in the echarts.ts in next frame.
  11729. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  11730. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11731. }
  11732. }
  11733. function singleEnterBlur(el) {
  11734. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  11735. }
  11736. function singleLeaveBlur(el) {
  11737. if (el.hoverState === HOVER_STATE_BLUR) {
  11738. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11739. }
  11740. }
  11741. function singleEnterSelect(el) {
  11742. el.selected = true;
  11743. }
  11744. function singleLeaveSelect(el) {
  11745. el.selected = false;
  11746. }
  11747. function updateElementState(el, updater, commonParam) {
  11748. updater(el, commonParam);
  11749. }
  11750. function traverseUpdateState(el, updater, commonParam) {
  11751. updateElementState(el, updater, commonParam);
  11752. el.isGroup && el.traverse(function (child) {
  11753. updateElementState(child, updater, commonParam);
  11754. });
  11755. }
  11756. function setStatesFlag(el, stateName) {
  11757. switch (stateName) {
  11758. case 'emphasis':
  11759. el.hoverState = HOVER_STATE_EMPHASIS;
  11760. break;
  11761. case 'normal':
  11762. el.hoverState = HOVER_STATE_NORMAL;
  11763. break;
  11764. case 'blur':
  11765. el.hoverState = HOVER_STATE_BLUR;
  11766. break;
  11767. case 'select':
  11768. el.selected = true;
  11769. }
  11770. }
  11771. function getFromStateStyle(el, props, toStateName, defaultValue) {
  11772. var style = el.style;
  11773. var fromState = {};
  11774. for (var i = 0; i < props.length; i++) {
  11775. var propName = props[i];
  11776. var val = style[propName];
  11777. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  11778. }
  11779. for (var i = 0; i < el.animators.length; i++) {
  11780. var animator = el.animators[i];
  11781. if (animator.__fromStateTransition // Dont consider the animation to emphasis state.
  11782. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  11783. animator.saveTo(fromState, props);
  11784. }
  11785. }
  11786. return fromState;
  11787. }
  11788. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  11789. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  11790. var cloned = false;
  11791. if (el instanceof Path) {
  11792. var store = getSavedStates(el);
  11793. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  11794. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  11795. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  11796. state = state || {};
  11797. var emphasisStyle = state.style || {}; // inherit case
  11798. if (emphasisStyle.fill === 'inherit') {
  11799. cloned = true;
  11800. state = extend({}, state);
  11801. emphasisStyle = extend({}, emphasisStyle);
  11802. emphasisStyle.fill = fromFill;
  11803. } // Apply default color lift
  11804. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  11805. cloned = true; // Not modify the original value.
  11806. state = extend({}, state);
  11807. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  11808. emphasisStyle.fill = liftColor(fromFill);
  11809. } // Not highlight stroke if fill has been highlighted.
  11810. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  11811. if (!cloned) {
  11812. state = extend({}, state);
  11813. emphasisStyle = extend({}, emphasisStyle);
  11814. }
  11815. emphasisStyle.stroke = liftColor(fromStroke);
  11816. }
  11817. state.style = emphasisStyle;
  11818. }
  11819. }
  11820. if (state) {
  11821. // TODO Share with textContent?
  11822. if (state.z2 == null) {
  11823. if (!cloned) {
  11824. state = extend({}, state);
  11825. }
  11826. var z2EmphasisLift = el.z2EmphasisLift;
  11827. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  11828. }
  11829. }
  11830. return state;
  11831. }
  11832. function createSelectDefaultState(el, stateName, state) {
  11833. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  11834. if (state) {
  11835. // TODO Share with textContent?
  11836. if (state.z2 == null) {
  11837. state = extend({}, state);
  11838. var z2SelectLift = el.z2SelectLift;
  11839. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  11840. }
  11841. }
  11842. return state;
  11843. }
  11844. function createBlurDefaultState(el, stateName, state) {
  11845. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  11846. var currentOpacity = el.style.opacity;
  11847. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  11848. opacity: 1
  11849. }) : null;
  11850. state = state || {};
  11851. var blurStyle = state.style || {};
  11852. if (blurStyle.opacity == null) {
  11853. // clone state
  11854. state = extend({}, state);
  11855. blurStyle = extend({
  11856. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  11857. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  11858. }, blurStyle);
  11859. state.style = blurStyle;
  11860. }
  11861. return state;
  11862. }
  11863. function elementStateProxy(stateName, targetStates) {
  11864. var state = this.states[stateName];
  11865. if (this.style) {
  11866. if (stateName === 'emphasis') {
  11867. return createEmphasisDefaultState(this, stateName, targetStates, state);
  11868. } else if (stateName === 'blur') {
  11869. return createBlurDefaultState(this, stateName, state);
  11870. } else if (stateName === 'select') {
  11871. return createSelectDefaultState(this, stateName, state);
  11872. }
  11873. }
  11874. return state;
  11875. }
  11876. /**FI
  11877. * Set hover style (namely "emphasis style") of element.
  11878. * @param el Should not be `zrender/graphic/Group`.
  11879. * @param focus 'self' | 'selfInSeries' | 'series'
  11880. */
  11881. function setDefaultStateProxy(el) {
  11882. el.stateProxy = elementStateProxy;
  11883. var textContent = el.getTextContent();
  11884. var textGuide = el.getTextGuideLine();
  11885. if (textContent) {
  11886. textContent.stateProxy = elementStateProxy;
  11887. }
  11888. if (textGuide) {
  11889. textGuide.stateProxy = elementStateProxy;
  11890. }
  11891. }
  11892. function enterEmphasisWhenMouseOver(el, e) {
  11893. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11894. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  11895. }
  11896. function leaveEmphasisWhenMouseOut(el, e) {
  11897. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11898. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  11899. }
  11900. function enterEmphasis(el, highlightDigit) {
  11901. el.__highByOuter |= 1 << (highlightDigit || 0);
  11902. traverseUpdateState(el, singleEnterEmphasis);
  11903. }
  11904. function leaveEmphasis(el, highlightDigit) {
  11905. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  11906. }
  11907. function enterBlur(el) {
  11908. traverseUpdateState(el, singleEnterBlur);
  11909. }
  11910. function leaveBlur(el) {
  11911. traverseUpdateState(el, singleLeaveBlur);
  11912. }
  11913. function enterSelect(el) {
  11914. traverseUpdateState(el, singleEnterSelect);
  11915. }
  11916. function leaveSelect(el) {
  11917. traverseUpdateState(el, singleLeaveSelect);
  11918. }
  11919. function shouldSilent(el, e) {
  11920. return el.__highDownSilentOnTouch && e.zrByTouch;
  11921. }
  11922. function allLeaveBlur(api) {
  11923. var model = api.getModel();
  11924. var leaveBlurredSeries = [];
  11925. var allComponentViews = [];
  11926. model.eachComponent(function (componentType, componentModel) {
  11927. var componentStates = getComponentStates(componentModel);
  11928. var isSeries = componentType === 'series';
  11929. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  11930. !isSeries && allComponentViews.push(view);
  11931. if (componentStates.isBlured) {
  11932. // Leave blur anyway
  11933. view.group.traverse(function (child) {
  11934. singleLeaveBlur(child);
  11935. });
  11936. isSeries && leaveBlurredSeries.push(componentModel);
  11937. }
  11938. componentStates.isBlured = false;
  11939. });
  11940. each(allComponentViews, function (view) {
  11941. if (view && view.toggleBlurSeries) {
  11942. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  11943. }
  11944. });
  11945. }
  11946. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  11947. var ecModel = api.getModel();
  11948. blurScope = blurScope || 'coordinateSystem';
  11949. function leaveBlurOfIndices(data, dataIndices) {
  11950. for (var i = 0; i < dataIndices.length; i++) {
  11951. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  11952. itemEl && leaveBlur(itemEl);
  11953. }
  11954. }
  11955. if (targetSeriesIndex == null) {
  11956. return;
  11957. }
  11958. if (!focus || focus === 'none') {
  11959. return;
  11960. }
  11961. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  11962. var targetCoordSys = targetSeriesModel.coordinateSystem;
  11963. if (targetCoordSys && targetCoordSys.master) {
  11964. targetCoordSys = targetCoordSys.master;
  11965. }
  11966. var blurredSeries = [];
  11967. ecModel.eachSeries(function (seriesModel) {
  11968. var sameSeries = targetSeriesModel === seriesModel;
  11969. var coordSys = seriesModel.coordinateSystem;
  11970. if (coordSys && coordSys.master) {
  11971. coordSys = coordSys.master;
  11972. }
  11973. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  11974. if (!( // Not blur other series if blurScope series
  11975. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  11976. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  11977. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  11978. )) {
  11979. var view = api.getViewOfSeriesModel(seriesModel);
  11980. view.group.traverse(function (child) {
  11981. singleEnterBlur(child);
  11982. });
  11983. if (isArrayLike(focus)) {
  11984. leaveBlurOfIndices(seriesModel.getData(), focus);
  11985. } else if (isObject(focus)) {
  11986. var dataTypes = keys(focus);
  11987. for (var d = 0; d < dataTypes.length; d++) {
  11988. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  11989. }
  11990. }
  11991. blurredSeries.push(seriesModel);
  11992. getComponentStates(seriesModel).isBlured = true;
  11993. }
  11994. });
  11995. ecModel.eachComponent(function (componentType, componentModel) {
  11996. if (componentType === 'series') {
  11997. return;
  11998. }
  11999. var view = api.getViewOfComponentModel(componentModel);
  12000. if (view && view.toggleBlurSeries) {
  12001. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12002. }
  12003. });
  12004. }
  12005. function blurComponent(componentMainType, componentIndex, api) {
  12006. if (componentMainType == null || componentIndex == null) {
  12007. return;
  12008. }
  12009. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12010. if (!componentModel) {
  12011. return;
  12012. }
  12013. getComponentStates(componentModel).isBlured = true;
  12014. var view = api.getViewOfComponentModel(componentModel);
  12015. if (!view || !view.focusBlurEnabled) {
  12016. return;
  12017. }
  12018. view.group.traverse(function (child) {
  12019. singleEnterBlur(child);
  12020. });
  12021. }
  12022. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12023. var seriesIndex = seriesModel.seriesIndex;
  12024. var data = seriesModel.getData(payload.dataType);
  12025. if (!data) {
  12026. if ("development" !== 'production') {
  12027. error("Unknown dataType " + payload.dataType);
  12028. }
  12029. return;
  12030. }
  12031. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  12032. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12033. var el = data.getItemGraphicEl(dataIndex);
  12034. if (!el) {
  12035. var count = data.count();
  12036. var current = 0; // If data on dataIndex is NaN.
  12037. while (!el && current < count) {
  12038. el = data.getItemGraphicEl(current++);
  12039. }
  12040. }
  12041. if (el) {
  12042. var ecData = getECData(el);
  12043. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12044. } else {
  12045. // If there is no element put on the data. Try getting it from raw option
  12046. // TODO Should put it on seriesModel?
  12047. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12048. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12049. if (focus_1 != null) {
  12050. blurSeries(seriesIndex, focus_1, blurScope, api);
  12051. }
  12052. }
  12053. }
  12054. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12055. var ret = {
  12056. focusSelf: false,
  12057. dispatchers: null
  12058. };
  12059. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12060. return ret;
  12061. }
  12062. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12063. if (!componentModel) {
  12064. return ret;
  12065. }
  12066. var view = api.getViewOfComponentModel(componentModel);
  12067. if (!view || !view.findHighDownDispatchers) {
  12068. return ret;
  12069. }
  12070. var dispatchers = view.findHighDownDispatchers(name); // At presnet, the component (like Geo) only blur inside itself.
  12071. // So we do not use `blurScope` in component.
  12072. var focusSelf;
  12073. for (var i = 0; i < dispatchers.length; i++) {
  12074. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12075. error('param should be highDownDispatcher');
  12076. }
  12077. if (getECData(dispatchers[i]).focus === 'self') {
  12078. focusSelf = true;
  12079. break;
  12080. }
  12081. }
  12082. return {
  12083. focusSelf: focusSelf,
  12084. dispatchers: dispatchers
  12085. };
  12086. }
  12087. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12088. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12089. error('param should be highDownDispatcher');
  12090. }
  12091. var ecData = getECData(dispatcher);
  12092. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12093. dispatchers = _a.dispatchers,
  12094. focusSelf = _a.focusSelf; // If `findHighDownDispatchers` is supported on the component,
  12095. // highlight/downplay elements with the same name.
  12096. if (dispatchers) {
  12097. if (focusSelf) {
  12098. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12099. }
  12100. each(dispatchers, function (dispatcher) {
  12101. return enterEmphasisWhenMouseOver(dispatcher, e);
  12102. });
  12103. } else {
  12104. // Try blur all in the related series. Then emphasis the hoverred.
  12105. // TODO. progressive mode.
  12106. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12107. if (ecData.focus === 'self') {
  12108. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12109. } // Other than series, component that not support `findHighDownDispatcher` will
  12110. // also use it. But in this case, highlight/downplay are only supported in
  12111. // mouse hover but not in dispatchAction.
  12112. enterEmphasisWhenMouseOver(dispatcher, e);
  12113. }
  12114. }
  12115. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12116. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12117. error('param should be highDownDispatcher');
  12118. }
  12119. allLeaveBlur(api);
  12120. var ecData = getECData(dispatcher);
  12121. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12122. if (dispatchers) {
  12123. each(dispatchers, function (dispatcher) {
  12124. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12125. });
  12126. } else {
  12127. leaveEmphasisWhenMouseOut(dispatcher, e);
  12128. }
  12129. }
  12130. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12131. if (!isSelectChangePayload(payload)) {
  12132. return;
  12133. }
  12134. var dataType = payload.dataType;
  12135. var data = seriesModel.getData(dataType);
  12136. var dataIndex = queryDataIndex(data, payload);
  12137. if (!isArray(dataIndex)) {
  12138. dataIndex = [dataIndex];
  12139. }
  12140. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12141. }
  12142. function updateSeriesElementSelection(seriesModel) {
  12143. var allData = seriesModel.getAllData();
  12144. each(allData, function (_a) {
  12145. var data = _a.data,
  12146. type = _a.type;
  12147. data.eachItemGraphicEl(function (el, idx) {
  12148. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12149. });
  12150. });
  12151. }
  12152. function getAllSelectedIndices(ecModel) {
  12153. var ret = [];
  12154. ecModel.eachSeries(function (seriesModel) {
  12155. var allData = seriesModel.getAllData();
  12156. each(allData, function (_a) {
  12157. var data = _a.data,
  12158. type = _a.type;
  12159. var dataIndices = seriesModel.getSelectedDataIndices();
  12160. if (dataIndices.length > 0) {
  12161. var item = {
  12162. dataIndex: dataIndices,
  12163. seriesIndex: seriesModel.seriesIndex
  12164. };
  12165. if (type != null) {
  12166. item.dataType = type;
  12167. }
  12168. ret.push(item);
  12169. }
  12170. });
  12171. });
  12172. return ret;
  12173. }
  12174. /**
  12175. * Enable the function that mouseover will trigger the emphasis state.
  12176. *
  12177. * NOTE:
  12178. * This function should be used on the element with dataIndex, seriesIndex.
  12179. *
  12180. */
  12181. function enableHoverEmphasis(el, focus, blurScope) {
  12182. setAsHighDownDispatcher(el, true);
  12183. traverseUpdateState(el, setDefaultStateProxy);
  12184. enableHoverFocus(el, focus, blurScope);
  12185. }
  12186. function disableHoverEmphasis(el) {
  12187. setAsHighDownDispatcher(el, false);
  12188. }
  12189. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12190. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12191. }
  12192. function enableHoverFocus(el, focus, blurScope) {
  12193. var ecData = getECData(el);
  12194. if (focus != null) {
  12195. // TODO dataIndex may be set after this function. This check is not useful.
  12196. // if (ecData.dataIndex == null) {
  12197. // if (__DEV__) {
  12198. // console.warn('focus can only been set on element with dataIndex');
  12199. // }
  12200. // }
  12201. // else {
  12202. ecData.focus = focus;
  12203. ecData.blurScope = blurScope; // }
  12204. } else if (ecData.focus) {
  12205. ecData.focus = null;
  12206. }
  12207. }
  12208. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12209. var defaultStyleGetterMap = {
  12210. itemStyle: 'getItemStyle',
  12211. lineStyle: 'getLineStyle',
  12212. areaStyle: 'getAreaStyle'
  12213. };
  12214. /**
  12215. * Set emphasis/blur/selected states of element.
  12216. */
  12217. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12218. getter) {
  12219. styleType = styleType || 'itemStyle';
  12220. for (var i = 0; i < OTHER_STATES.length; i++) {
  12221. var stateName = OTHER_STATES[i];
  12222. var model = itemModel.getModel([stateName, styleType]);
  12223. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12224. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12225. }
  12226. }
  12227. /**
  12228. *
  12229. * Set element as highlight / downplay dispatcher.
  12230. * It will be checked when element recieved mouseover event or from highlight action.
  12231. * It's in change of all highlight/downplay behavior of it's children.
  12232. *
  12233. * @param el
  12234. * @param el.highDownSilentOnTouch
  12235. * In touch device, mouseover event will be trigger on touchstart event
  12236. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12237. * conveniently use hoverStyle when tap on touch screen without additional
  12238. * code for compatibility.
  12239. * But if the chart/component has select feature, which usually also use
  12240. * hoverStyle, there might be conflict between 'select-highlight' and
  12241. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12242. * In this case, `highDownSilentOnTouch` should be used to disable
  12243. * hover-highlight on touch device.
  12244. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12245. */
  12246. function setAsHighDownDispatcher(el, asDispatcher) {
  12247. var disable = asDispatcher === false;
  12248. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12249. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12250. if (el.highDownSilentOnTouch) {
  12251. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12252. } // Simple optimize, since this method might be
  12253. // called for each elements of a group in some cases.
  12254. if (!disable || extendedEl.__highDownDispatcher) {
  12255. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12256. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12257. // Also keep previous record.
  12258. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12259. extendedEl.__highDownDispatcher = !disable;
  12260. }
  12261. }
  12262. function isHighDownDispatcher(el) {
  12263. return !!(el && el.__highDownDispatcher);
  12264. }
  12265. /**
  12266. * Support hightlight/downplay record on each elements.
  12267. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12268. * user triggerred hightlight/downplay should not conflict.
  12269. * Only all of the highlightDigit cleared, return to normal.
  12270. * @param {string} highlightKey
  12271. * @return {number} highlightDigit
  12272. */
  12273. function getHighlightDigit(highlightKey) {
  12274. var highlightDigit = _highlightKeyMap[highlightKey];
  12275. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12276. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12277. }
  12278. return highlightDigit;
  12279. }
  12280. function isSelectChangePayload(payload) {
  12281. var payloadType = payload.type;
  12282. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12283. }
  12284. function isHighDownPayload(payload) {
  12285. var payloadType = payload.type;
  12286. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12287. }
  12288. function savePathStates(el) {
  12289. var store = getSavedStates(el);
  12290. store.normalFill = el.style.fill;
  12291. store.normalStroke = el.style.stroke;
  12292. var selectState = el.states.select || {};
  12293. store.selectFill = selectState.style && selectState.style.fill || null;
  12294. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12295. }
  12296. var CMD$2 = PathProxy.CMD;
  12297. var points = [[], [], []];
  12298. var mathSqrt$1 = Math.sqrt;
  12299. var mathAtan2 = Math.atan2;
  12300. function transformPath(path, m) {
  12301. if (!m) {
  12302. return;
  12303. }
  12304. var data = path.data;
  12305. var len = path.len();
  12306. var cmd;
  12307. var nPoint;
  12308. var i;
  12309. var j;
  12310. var k;
  12311. var p;
  12312. var M = CMD$2.M;
  12313. var C = CMD$2.C;
  12314. var L = CMD$2.L;
  12315. var R = CMD$2.R;
  12316. var A = CMD$2.A;
  12317. var Q = CMD$2.Q;
  12318. for (i = 0, j = 0; i < len;) {
  12319. cmd = data[i++];
  12320. j = i;
  12321. nPoint = 0;
  12322. switch (cmd) {
  12323. case M:
  12324. nPoint = 1;
  12325. break;
  12326. case L:
  12327. nPoint = 1;
  12328. break;
  12329. case C:
  12330. nPoint = 3;
  12331. break;
  12332. case Q:
  12333. nPoint = 2;
  12334. break;
  12335. case A:
  12336. var x = m[4];
  12337. var y = m[5];
  12338. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12339. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12340. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12341. data[i] *= sx;
  12342. data[i++] += x;
  12343. data[i] *= sy;
  12344. data[i++] += y;
  12345. data[i++] *= sx;
  12346. data[i++] *= sy;
  12347. data[i++] += angle;
  12348. data[i++] += angle;
  12349. i += 2;
  12350. j = i;
  12351. break;
  12352. case R:
  12353. p[0] = data[i++];
  12354. p[1] = data[i++];
  12355. applyTransform(p, p, m);
  12356. data[j++] = p[0];
  12357. data[j++] = p[1];
  12358. p[0] += data[i++];
  12359. p[1] += data[i++];
  12360. applyTransform(p, p, m);
  12361. data[j++] = p[0];
  12362. data[j++] = p[1];
  12363. }
  12364. for (k = 0; k < nPoint; k++) {
  12365. var p_1 = points[k];
  12366. p_1[0] = data[i++];
  12367. p_1[1] = data[i++];
  12368. applyTransform(p_1, p_1, m);
  12369. data[j++] = p_1[0];
  12370. data[j++] = p_1[1];
  12371. }
  12372. }
  12373. path.increaseVersion();
  12374. }
  12375. var mathSqrt$2 = Math.sqrt;
  12376. var mathSin$2 = Math.sin;
  12377. var mathCos$2 = Math.cos;
  12378. var PI$1 = Math.PI;
  12379. function vMag(v) {
  12380. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12381. }
  12382. function vRatio(u, v) {
  12383. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12384. }
  12385. function vAngle(u, v) {
  12386. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12387. * Math.acos(vRatio(u, v));
  12388. }
  12389. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12390. var psi = psiDeg * (PI$1 / 180.0);
  12391. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12392. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12393. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12394. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12395. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12396. if (lambda > 1) {
  12397. rx *= mathSqrt$2(lambda);
  12398. ry *= mathSqrt$2(lambda);
  12399. }
  12400. var f = (fa === fs ? -1 : 1)
  12401. * mathSqrt$2((((rx * rx) * (ry * ry))
  12402. - ((rx * rx) * (yp * yp))
  12403. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12404. + (ry * ry) * (xp * xp))) || 0;
  12405. var cxp = f * rx * yp / ry;
  12406. var cyp = f * -ry * xp / rx;
  12407. var cx = (x1 + x2) / 2.0
  12408. + mathCos$2(psi) * cxp
  12409. - mathSin$2(psi) * cyp;
  12410. var cy = (y1 + y2) / 2.0
  12411. + mathSin$2(psi) * cxp
  12412. + mathCos$2(psi) * cyp;
  12413. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12414. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12415. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12416. var dTheta = vAngle(u, v);
  12417. if (vRatio(u, v) <= -1) {
  12418. dTheta = PI$1;
  12419. }
  12420. if (vRatio(u, v) >= 1) {
  12421. dTheta = 0;
  12422. }
  12423. if (dTheta < 0) {
  12424. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12425. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12426. }
  12427. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12428. }
  12429. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12430. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12431. function createPathProxyFromString(data) {
  12432. var path = new PathProxy();
  12433. if (!data) {
  12434. return path;
  12435. }
  12436. var cpx = 0;
  12437. var cpy = 0;
  12438. var subpathX = cpx;
  12439. var subpathY = cpy;
  12440. var prevCmd;
  12441. var CMD = PathProxy.CMD;
  12442. var cmdList = data.match(commandReg);
  12443. if (!cmdList) {
  12444. return path;
  12445. }
  12446. for (var l = 0; l < cmdList.length; l++) {
  12447. var cmdText = cmdList[l];
  12448. var cmdStr = cmdText.charAt(0);
  12449. var cmd = void 0;
  12450. var p = cmdText.match(numberReg) || [];
  12451. var pLen = p.length;
  12452. for (var i = 0; i < pLen; i++) {
  12453. p[i] = parseFloat(p[i]);
  12454. }
  12455. var off = 0;
  12456. while (off < pLen) {
  12457. var ctlPtx = void 0;
  12458. var ctlPty = void 0;
  12459. var rx = void 0;
  12460. var ry = void 0;
  12461. var psi = void 0;
  12462. var fa = void 0;
  12463. var fs = void 0;
  12464. var x1 = cpx;
  12465. var y1 = cpy;
  12466. var len = void 0;
  12467. var pathData = void 0;
  12468. switch (cmdStr) {
  12469. case 'l':
  12470. cpx += p[off++];
  12471. cpy += p[off++];
  12472. cmd = CMD.L;
  12473. path.addData(cmd, cpx, cpy);
  12474. break;
  12475. case 'L':
  12476. cpx = p[off++];
  12477. cpy = p[off++];
  12478. cmd = CMD.L;
  12479. path.addData(cmd, cpx, cpy);
  12480. break;
  12481. case 'm':
  12482. cpx += p[off++];
  12483. cpy += p[off++];
  12484. cmd = CMD.M;
  12485. path.addData(cmd, cpx, cpy);
  12486. subpathX = cpx;
  12487. subpathY = cpy;
  12488. cmdStr = 'l';
  12489. break;
  12490. case 'M':
  12491. cpx = p[off++];
  12492. cpy = p[off++];
  12493. cmd = CMD.M;
  12494. path.addData(cmd, cpx, cpy);
  12495. subpathX = cpx;
  12496. subpathY = cpy;
  12497. cmdStr = 'L';
  12498. break;
  12499. case 'h':
  12500. cpx += p[off++];
  12501. cmd = CMD.L;
  12502. path.addData(cmd, cpx, cpy);
  12503. break;
  12504. case 'H':
  12505. cpx = p[off++];
  12506. cmd = CMD.L;
  12507. path.addData(cmd, cpx, cpy);
  12508. break;
  12509. case 'v':
  12510. cpy += p[off++];
  12511. cmd = CMD.L;
  12512. path.addData(cmd, cpx, cpy);
  12513. break;
  12514. case 'V':
  12515. cpy = p[off++];
  12516. cmd = CMD.L;
  12517. path.addData(cmd, cpx, cpy);
  12518. break;
  12519. case 'C':
  12520. cmd = CMD.C;
  12521. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12522. cpx = p[off - 2];
  12523. cpy = p[off - 1];
  12524. break;
  12525. case 'c':
  12526. cmd = CMD.C;
  12527. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12528. cpx += p[off - 2];
  12529. cpy += p[off - 1];
  12530. break;
  12531. case 'S':
  12532. ctlPtx = cpx;
  12533. ctlPty = cpy;
  12534. len = path.len();
  12535. pathData = path.data;
  12536. if (prevCmd === CMD.C) {
  12537. ctlPtx += cpx - pathData[len - 4];
  12538. ctlPty += cpy - pathData[len - 3];
  12539. }
  12540. cmd = CMD.C;
  12541. x1 = p[off++];
  12542. y1 = p[off++];
  12543. cpx = p[off++];
  12544. cpy = p[off++];
  12545. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12546. break;
  12547. case 's':
  12548. ctlPtx = cpx;
  12549. ctlPty = cpy;
  12550. len = path.len();
  12551. pathData = path.data;
  12552. if (prevCmd === CMD.C) {
  12553. ctlPtx += cpx - pathData[len - 4];
  12554. ctlPty += cpy - pathData[len - 3];
  12555. }
  12556. cmd = CMD.C;
  12557. x1 = cpx + p[off++];
  12558. y1 = cpy + p[off++];
  12559. cpx += p[off++];
  12560. cpy += p[off++];
  12561. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12562. break;
  12563. case 'Q':
  12564. x1 = p[off++];
  12565. y1 = p[off++];
  12566. cpx = p[off++];
  12567. cpy = p[off++];
  12568. cmd = CMD.Q;
  12569. path.addData(cmd, x1, y1, cpx, cpy);
  12570. break;
  12571. case 'q':
  12572. x1 = p[off++] + cpx;
  12573. y1 = p[off++] + cpy;
  12574. cpx += p[off++];
  12575. cpy += p[off++];
  12576. cmd = CMD.Q;
  12577. path.addData(cmd, x1, y1, cpx, cpy);
  12578. break;
  12579. case 'T':
  12580. ctlPtx = cpx;
  12581. ctlPty = cpy;
  12582. len = path.len();
  12583. pathData = path.data;
  12584. if (prevCmd === CMD.Q) {
  12585. ctlPtx += cpx - pathData[len - 4];
  12586. ctlPty += cpy - pathData[len - 3];
  12587. }
  12588. cpx = p[off++];
  12589. cpy = p[off++];
  12590. cmd = CMD.Q;
  12591. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12592. break;
  12593. case 't':
  12594. ctlPtx = cpx;
  12595. ctlPty = cpy;
  12596. len = path.len();
  12597. pathData = path.data;
  12598. if (prevCmd === CMD.Q) {
  12599. ctlPtx += cpx - pathData[len - 4];
  12600. ctlPty += cpy - pathData[len - 3];
  12601. }
  12602. cpx += p[off++];
  12603. cpy += p[off++];
  12604. cmd = CMD.Q;
  12605. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12606. break;
  12607. case 'A':
  12608. rx = p[off++];
  12609. ry = p[off++];
  12610. psi = p[off++];
  12611. fa = p[off++];
  12612. fs = p[off++];
  12613. x1 = cpx, y1 = cpy;
  12614. cpx = p[off++];
  12615. cpy = p[off++];
  12616. cmd = CMD.A;
  12617. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12618. break;
  12619. case 'a':
  12620. rx = p[off++];
  12621. ry = p[off++];
  12622. psi = p[off++];
  12623. fa = p[off++];
  12624. fs = p[off++];
  12625. x1 = cpx, y1 = cpy;
  12626. cpx += p[off++];
  12627. cpy += p[off++];
  12628. cmd = CMD.A;
  12629. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12630. break;
  12631. }
  12632. }
  12633. if (cmdStr === 'z' || cmdStr === 'Z') {
  12634. cmd = CMD.Z;
  12635. path.addData(cmd);
  12636. cpx = subpathX;
  12637. cpy = subpathY;
  12638. }
  12639. prevCmd = cmd;
  12640. }
  12641. path.toStatic();
  12642. return path;
  12643. }
  12644. var SVGPath = (function (_super) {
  12645. __extends(SVGPath, _super);
  12646. function SVGPath() {
  12647. return _super !== null && _super.apply(this, arguments) || this;
  12648. }
  12649. SVGPath.prototype.applyTransform = function (m) { };
  12650. return SVGPath;
  12651. }(Path));
  12652. function isPathProxy(path) {
  12653. return path.setData != null;
  12654. }
  12655. function createPathOptions(str, opts) {
  12656. var pathProxy = createPathProxyFromString(str);
  12657. var innerOpts = extend({}, opts);
  12658. innerOpts.buildPath = function (path) {
  12659. if (isPathProxy(path)) {
  12660. path.setData(pathProxy.data);
  12661. var ctx = path.getContext();
  12662. if (ctx) {
  12663. path.rebuildPath(ctx, 1);
  12664. }
  12665. }
  12666. else {
  12667. var ctx = path;
  12668. pathProxy.rebuildPath(ctx, 1);
  12669. }
  12670. };
  12671. innerOpts.applyTransform = function (m) {
  12672. transformPath(pathProxy, m);
  12673. this.dirtyShape();
  12674. };
  12675. return innerOpts;
  12676. }
  12677. function createFromString(str, opts) {
  12678. return new SVGPath(createPathOptions(str, opts));
  12679. }
  12680. function extendFromString(str, defaultOpts) {
  12681. var innerOpts = createPathOptions(str, defaultOpts);
  12682. var Sub = (function (_super) {
  12683. __extends(Sub, _super);
  12684. function Sub(opts) {
  12685. var _this = _super.call(this, opts) || this;
  12686. _this.applyTransform = innerOpts.applyTransform;
  12687. _this.buildPath = innerOpts.buildPath;
  12688. return _this;
  12689. }
  12690. return Sub;
  12691. }(SVGPath));
  12692. return Sub;
  12693. }
  12694. function mergePath(pathEls, opts) {
  12695. var pathList = [];
  12696. var len = pathEls.length;
  12697. for (var i = 0; i < len; i++) {
  12698. var pathEl = pathEls[i];
  12699. pathList.push(pathEl.getUpdatedPathProxy(true));
  12700. }
  12701. var pathBundle = new Path(opts);
  12702. pathBundle.createPathProxy();
  12703. pathBundle.buildPath = function (path) {
  12704. if (isPathProxy(path)) {
  12705. path.appendPath(pathList);
  12706. var ctx = path.getContext();
  12707. if (ctx) {
  12708. path.rebuildPath(ctx, 1);
  12709. }
  12710. }
  12711. };
  12712. return pathBundle;
  12713. }
  12714. var CircleShape = (function () {
  12715. function CircleShape() {
  12716. this.cx = 0;
  12717. this.cy = 0;
  12718. this.r = 0;
  12719. }
  12720. return CircleShape;
  12721. }());
  12722. var Circle = (function (_super) {
  12723. __extends(Circle, _super);
  12724. function Circle(opts) {
  12725. return _super.call(this, opts) || this;
  12726. }
  12727. Circle.prototype.getDefaultShape = function () {
  12728. return new CircleShape();
  12729. };
  12730. Circle.prototype.buildPath = function (ctx, shape) {
  12731. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12732. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  12733. };
  12734. return Circle;
  12735. }(Path));
  12736. Circle.prototype.type = 'circle';
  12737. var EllipseShape = (function () {
  12738. function EllipseShape() {
  12739. this.cx = 0;
  12740. this.cy = 0;
  12741. this.rx = 0;
  12742. this.ry = 0;
  12743. }
  12744. return EllipseShape;
  12745. }());
  12746. var Ellipse = (function (_super) {
  12747. __extends(Ellipse, _super);
  12748. function Ellipse(opts) {
  12749. return _super.call(this, opts) || this;
  12750. }
  12751. Ellipse.prototype.getDefaultShape = function () {
  12752. return new EllipseShape();
  12753. };
  12754. Ellipse.prototype.buildPath = function (ctx, shape) {
  12755. var k = 0.5522848;
  12756. var x = shape.cx;
  12757. var y = shape.cy;
  12758. var a = shape.rx;
  12759. var b = shape.ry;
  12760. var ox = a * k;
  12761. var oy = b * k;
  12762. ctx.moveTo(x - a, y);
  12763. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  12764. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  12765. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  12766. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  12767. ctx.closePath();
  12768. };
  12769. return Ellipse;
  12770. }(Path));
  12771. Ellipse.prototype.type = 'ellipse';
  12772. var PI$2 = Math.PI;
  12773. var PI2$5 = PI$2 * 2;
  12774. var mathSin$3 = Math.sin;
  12775. var mathCos$3 = Math.cos;
  12776. var mathACos = Math.acos;
  12777. var mathATan2 = Math.atan2;
  12778. var mathAbs$1 = Math.abs;
  12779. var mathSqrt$3 = Math.sqrt;
  12780. var mathMax$3 = Math.max;
  12781. var mathMin$3 = Math.min;
  12782. var e = 1e-4;
  12783. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  12784. var dx10 = x1 - x0;
  12785. var dy10 = y1 - y0;
  12786. var dx32 = x3 - x2;
  12787. var dy32 = y3 - y2;
  12788. var t = dy32 * dx10 - dx32 * dy10;
  12789. if (t * t < e) {
  12790. return;
  12791. }
  12792. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  12793. return [x0 + t * dx10, y0 + t * dy10];
  12794. }
  12795. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  12796. var x01 = x0 - x1;
  12797. var y01 = y0 - y1;
  12798. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  12799. var ox = lo * y01;
  12800. var oy = -lo * x01;
  12801. var x11 = x0 + ox;
  12802. var y11 = y0 + oy;
  12803. var x10 = x1 + ox;
  12804. var y10 = y1 + oy;
  12805. var x00 = (x11 + x10) / 2;
  12806. var y00 = (y11 + y10) / 2;
  12807. var dx = x10 - x11;
  12808. var dy = y10 - y11;
  12809. var d2 = dx * dx + dy * dy;
  12810. var r = radius - cr;
  12811. var s = x11 * y10 - x10 * y11;
  12812. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  12813. var cx0 = (s * dy - dx * d) / d2;
  12814. var cy0 = (-s * dx - dy * d) / d2;
  12815. var cx1 = (s * dy + dx * d) / d2;
  12816. var cy1 = (-s * dx + dy * d) / d2;
  12817. var dx0 = cx0 - x00;
  12818. var dy0 = cy0 - y00;
  12819. var dx1 = cx1 - x00;
  12820. var dy1 = cy1 - y00;
  12821. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  12822. cx0 = cx1;
  12823. cy0 = cy1;
  12824. }
  12825. return {
  12826. cx: cx0,
  12827. cy: cy0,
  12828. x0: -ox,
  12829. y0: -oy,
  12830. x1: cx0 * (radius / r - 1),
  12831. y1: cy0 * (radius / r - 1)
  12832. };
  12833. }
  12834. function normalizeCornerRadius(cr) {
  12835. var arr;
  12836. if (isArray(cr)) {
  12837. var len = cr.length;
  12838. if (!len) {
  12839. return cr;
  12840. }
  12841. if (len === 1) {
  12842. arr = [cr[0], cr[0], 0, 0];
  12843. }
  12844. else if (len === 2) {
  12845. arr = [cr[0], cr[0], cr[1], cr[1]];
  12846. }
  12847. else if (len === 3) {
  12848. arr = cr.concat(cr[2]);
  12849. }
  12850. else {
  12851. arr = cr;
  12852. }
  12853. }
  12854. else {
  12855. arr = [cr, cr, cr, cr];
  12856. }
  12857. return arr;
  12858. }
  12859. function buildPath$1(ctx, shape) {
  12860. var _a;
  12861. var radius = mathMax$3(shape.r, 0);
  12862. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  12863. var hasRadius = radius > 0;
  12864. var hasInnerRadius = innerRadius > 0;
  12865. if (!hasRadius && !hasInnerRadius) {
  12866. return;
  12867. }
  12868. if (!hasRadius) {
  12869. radius = innerRadius;
  12870. innerRadius = 0;
  12871. }
  12872. if (innerRadius > radius) {
  12873. var tmp = radius;
  12874. radius = innerRadius;
  12875. innerRadius = tmp;
  12876. }
  12877. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  12878. if (isNaN(startAngle) || isNaN(endAngle)) {
  12879. return;
  12880. }
  12881. var cx = shape.cx, cy = shape.cy;
  12882. var clockwise = !!shape.clockwise;
  12883. var arc = mathAbs$1(endAngle - startAngle);
  12884. var mod = arc > PI2$5 && arc % PI2$5;
  12885. mod > e && (arc = mod);
  12886. if (!(radius > e)) {
  12887. ctx.moveTo(cx, cy);
  12888. }
  12889. else if (arc > PI2$5 - e) {
  12890. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  12891. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  12892. if (innerRadius > e) {
  12893. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  12894. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  12895. }
  12896. }
  12897. else {
  12898. var icrStart = void 0;
  12899. var icrEnd = void 0;
  12900. var ocrStart = void 0;
  12901. var ocrEnd = void 0;
  12902. var ocrs = void 0;
  12903. var ocre = void 0;
  12904. var icrs = void 0;
  12905. var icre = void 0;
  12906. var ocrMax = void 0;
  12907. var icrMax = void 0;
  12908. var limitedOcrMax = void 0;
  12909. var limitedIcrMax = void 0;
  12910. var xre = void 0;
  12911. var yre = void 0;
  12912. var xirs = void 0;
  12913. var yirs = void 0;
  12914. var xrs = radius * mathCos$3(startAngle);
  12915. var yrs = radius * mathSin$3(startAngle);
  12916. var xire = innerRadius * mathCos$3(endAngle);
  12917. var yire = innerRadius * mathSin$3(endAngle);
  12918. var hasArc = arc > e;
  12919. if (hasArc) {
  12920. var cornerRadius = shape.cornerRadius;
  12921. if (cornerRadius) {
  12922. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  12923. }
  12924. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  12925. ocrs = mathMin$3(halfRd, ocrStart);
  12926. ocre = mathMin$3(halfRd, ocrEnd);
  12927. icrs = mathMin$3(halfRd, icrStart);
  12928. icre = mathMin$3(halfRd, icrEnd);
  12929. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  12930. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  12931. if (ocrMax > e || icrMax > e) {
  12932. xre = radius * mathCos$3(endAngle);
  12933. yre = radius * mathSin$3(endAngle);
  12934. xirs = innerRadius * mathCos$3(startAngle);
  12935. yirs = innerRadius * mathSin$3(startAngle);
  12936. if (arc < PI$2) {
  12937. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  12938. if (it_1) {
  12939. var x0 = xrs - it_1[0];
  12940. var y0 = yrs - it_1[1];
  12941. var x1 = xre - it_1[0];
  12942. var y1 = yre - it_1[1];
  12943. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  12944. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  12945. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  12946. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  12947. }
  12948. }
  12949. }
  12950. }
  12951. if (!hasArc) {
  12952. ctx.moveTo(cx + xrs, cy + yrs);
  12953. }
  12954. else if (limitedOcrMax > e) {
  12955. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  12956. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  12957. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  12958. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  12959. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  12960. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  12961. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  12962. }
  12963. else {
  12964. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  12965. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  12966. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  12967. }
  12968. }
  12969. else {
  12970. ctx.moveTo(cx + xrs, cy + yrs);
  12971. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  12972. }
  12973. if (!(innerRadius > e) || !hasArc) {
  12974. ctx.lineTo(cx + xire, cy + yire);
  12975. }
  12976. else if (limitedIcrMax > e) {
  12977. var crStart = mathMin$3(icrStart, limitedIcrMax);
  12978. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  12979. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  12980. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  12981. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  12982. if (limitedIcrMax < icrMax && crStart === crEnd) {
  12983. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  12984. }
  12985. else {
  12986. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  12987. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  12988. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  12989. }
  12990. }
  12991. else {
  12992. ctx.lineTo(cx + xire, cy + yire);
  12993. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  12994. }
  12995. }
  12996. ctx.closePath();
  12997. }
  12998. var SectorShape = (function () {
  12999. function SectorShape() {
  13000. this.cx = 0;
  13001. this.cy = 0;
  13002. this.r0 = 0;
  13003. this.r = 0;
  13004. this.startAngle = 0;
  13005. this.endAngle = Math.PI * 2;
  13006. this.clockwise = true;
  13007. this.cornerRadius = 0;
  13008. }
  13009. return SectorShape;
  13010. }());
  13011. var Sector = (function (_super) {
  13012. __extends(Sector, _super);
  13013. function Sector(opts) {
  13014. return _super.call(this, opts) || this;
  13015. }
  13016. Sector.prototype.getDefaultShape = function () {
  13017. return new SectorShape();
  13018. };
  13019. Sector.prototype.buildPath = function (ctx, shape) {
  13020. buildPath$1(ctx, shape);
  13021. };
  13022. Sector.prototype.isZeroArea = function () {
  13023. return this.shape.startAngle === this.shape.endAngle
  13024. || this.shape.r === this.shape.r0;
  13025. };
  13026. return Sector;
  13027. }(Path));
  13028. Sector.prototype.type = 'sector';
  13029. var RingShape = (function () {
  13030. function RingShape() {
  13031. this.cx = 0;
  13032. this.cy = 0;
  13033. this.r = 0;
  13034. this.r0 = 0;
  13035. }
  13036. return RingShape;
  13037. }());
  13038. var Ring = (function (_super) {
  13039. __extends(Ring, _super);
  13040. function Ring(opts) {
  13041. return _super.call(this, opts) || this;
  13042. }
  13043. Ring.prototype.getDefaultShape = function () {
  13044. return new RingShape();
  13045. };
  13046. Ring.prototype.buildPath = function (ctx, shape) {
  13047. var x = shape.cx;
  13048. var y = shape.cy;
  13049. var PI2 = Math.PI * 2;
  13050. ctx.moveTo(x + shape.r, y);
  13051. ctx.arc(x, y, shape.r, 0, PI2, false);
  13052. ctx.moveTo(x + shape.r0, y);
  13053. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13054. };
  13055. return Ring;
  13056. }(Path));
  13057. Ring.prototype.type = 'ring';
  13058. function smoothBezier(points, smooth, isLoop, constraint) {
  13059. var cps = [];
  13060. var v = [];
  13061. var v1 = [];
  13062. var v2 = [];
  13063. var prevPoint;
  13064. var nextPoint;
  13065. var min$1;
  13066. var max$1;
  13067. if (constraint) {
  13068. min$1 = [Infinity, Infinity];
  13069. max$1 = [-Infinity, -Infinity];
  13070. for (var i = 0, len = points.length; i < len; i++) {
  13071. min(min$1, min$1, points[i]);
  13072. max(max$1, max$1, points[i]);
  13073. }
  13074. min(min$1, min$1, constraint[0]);
  13075. max(max$1, max$1, constraint[1]);
  13076. }
  13077. for (var i = 0, len = points.length; i < len; i++) {
  13078. var point = points[i];
  13079. if (isLoop) {
  13080. prevPoint = points[i ? i - 1 : len - 1];
  13081. nextPoint = points[(i + 1) % len];
  13082. }
  13083. else {
  13084. if (i === 0 || i === len - 1) {
  13085. cps.push(clone$1(points[i]));
  13086. continue;
  13087. }
  13088. else {
  13089. prevPoint = points[i - 1];
  13090. nextPoint = points[i + 1];
  13091. }
  13092. }
  13093. sub(v, nextPoint, prevPoint);
  13094. scale(v, v, smooth);
  13095. var d0 = distance(point, prevPoint);
  13096. var d1 = distance(point, nextPoint);
  13097. var sum = d0 + d1;
  13098. if (sum !== 0) {
  13099. d0 /= sum;
  13100. d1 /= sum;
  13101. }
  13102. scale(v1, v, -d0);
  13103. scale(v2, v, d1);
  13104. var cp0 = add([], point, v1);
  13105. var cp1 = add([], point, v2);
  13106. if (constraint) {
  13107. max(cp0, cp0, min$1);
  13108. min(cp0, cp0, max$1);
  13109. max(cp1, cp1, min$1);
  13110. min(cp1, cp1, max$1);
  13111. }
  13112. cps.push(cp0);
  13113. cps.push(cp1);
  13114. }
  13115. if (isLoop) {
  13116. cps.push(cps.shift());
  13117. }
  13118. return cps;
  13119. }
  13120. function buildPath$2(ctx, shape, closePath) {
  13121. var smooth = shape.smooth;
  13122. var points = shape.points;
  13123. if (points && points.length >= 2) {
  13124. if (smooth) {
  13125. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13126. ctx.moveTo(points[0][0], points[0][1]);
  13127. var len = points.length;
  13128. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13129. var cp1 = controlPoints[i * 2];
  13130. var cp2 = controlPoints[i * 2 + 1];
  13131. var p = points[(i + 1) % len];
  13132. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13133. }
  13134. }
  13135. else {
  13136. ctx.moveTo(points[0][0], points[0][1]);
  13137. for (var i = 1, l = points.length; i < l; i++) {
  13138. ctx.lineTo(points[i][0], points[i][1]);
  13139. }
  13140. }
  13141. closePath && ctx.closePath();
  13142. }
  13143. }
  13144. var PolygonShape = (function () {
  13145. function PolygonShape() {
  13146. this.points = null;
  13147. this.smooth = 0;
  13148. this.smoothConstraint = null;
  13149. }
  13150. return PolygonShape;
  13151. }());
  13152. var Polygon = (function (_super) {
  13153. __extends(Polygon, _super);
  13154. function Polygon(opts) {
  13155. return _super.call(this, opts) || this;
  13156. }
  13157. Polygon.prototype.getDefaultShape = function () {
  13158. return new PolygonShape();
  13159. };
  13160. Polygon.prototype.buildPath = function (ctx, shape) {
  13161. buildPath$2(ctx, shape, true);
  13162. };
  13163. return Polygon;
  13164. }(Path));
  13165. Polygon.prototype.type = 'polygon';
  13166. var PolylineShape = (function () {
  13167. function PolylineShape() {
  13168. this.points = null;
  13169. this.percent = 1;
  13170. this.smooth = 0;
  13171. this.smoothConstraint = null;
  13172. }
  13173. return PolylineShape;
  13174. }());
  13175. var Polyline = (function (_super) {
  13176. __extends(Polyline, _super);
  13177. function Polyline(opts) {
  13178. return _super.call(this, opts) || this;
  13179. }
  13180. Polyline.prototype.getDefaultStyle = function () {
  13181. return {
  13182. stroke: '#000',
  13183. fill: null
  13184. };
  13185. };
  13186. Polyline.prototype.getDefaultShape = function () {
  13187. return new PolylineShape();
  13188. };
  13189. Polyline.prototype.buildPath = function (ctx, shape) {
  13190. buildPath$2(ctx, shape, false);
  13191. };
  13192. return Polyline;
  13193. }(Path));
  13194. Polyline.prototype.type = 'polyline';
  13195. var subPixelOptimizeOutputShape$1 = {};
  13196. var LineShape = (function () {
  13197. function LineShape() {
  13198. this.x1 = 0;
  13199. this.y1 = 0;
  13200. this.x2 = 0;
  13201. this.y2 = 0;
  13202. this.percent = 1;
  13203. }
  13204. return LineShape;
  13205. }());
  13206. var Line = (function (_super) {
  13207. __extends(Line, _super);
  13208. function Line(opts) {
  13209. return _super.call(this, opts) || this;
  13210. }
  13211. Line.prototype.getDefaultStyle = function () {
  13212. return {
  13213. stroke: '#000',
  13214. fill: null
  13215. };
  13216. };
  13217. Line.prototype.getDefaultShape = function () {
  13218. return new LineShape();
  13219. };
  13220. Line.prototype.buildPath = function (ctx, shape) {
  13221. var x1;
  13222. var y1;
  13223. var x2;
  13224. var y2;
  13225. if (this.subPixelOptimize) {
  13226. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13227. x1 = optimizedShape.x1;
  13228. y1 = optimizedShape.y1;
  13229. x2 = optimizedShape.x2;
  13230. y2 = optimizedShape.y2;
  13231. }
  13232. else {
  13233. x1 = shape.x1;
  13234. y1 = shape.y1;
  13235. x2 = shape.x2;
  13236. y2 = shape.y2;
  13237. }
  13238. var percent = shape.percent;
  13239. if (percent === 0) {
  13240. return;
  13241. }
  13242. ctx.moveTo(x1, y1);
  13243. if (percent < 1) {
  13244. x2 = x1 * (1 - percent) + x2 * percent;
  13245. y2 = y1 * (1 - percent) + y2 * percent;
  13246. }
  13247. ctx.lineTo(x2, y2);
  13248. };
  13249. Line.prototype.pointAt = function (p) {
  13250. var shape = this.shape;
  13251. return [
  13252. shape.x1 * (1 - p) + shape.x2 * p,
  13253. shape.y1 * (1 - p) + shape.y2 * p
  13254. ];
  13255. };
  13256. return Line;
  13257. }(Path));
  13258. Line.prototype.type = 'line';
  13259. var out = [];
  13260. var BezierCurveShape = (function () {
  13261. function BezierCurveShape() {
  13262. this.x1 = 0;
  13263. this.y1 = 0;
  13264. this.x2 = 0;
  13265. this.y2 = 0;
  13266. this.cpx1 = 0;
  13267. this.cpy1 = 0;
  13268. this.percent = 1;
  13269. }
  13270. return BezierCurveShape;
  13271. }());
  13272. function someVectorAt(shape, t, isTangent) {
  13273. var cpx2 = shape.cpx2;
  13274. var cpy2 = shape.cpy2;
  13275. if (cpx2 != null || cpy2 != null) {
  13276. return [
  13277. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13278. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13279. ];
  13280. }
  13281. else {
  13282. return [
  13283. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13284. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13285. ];
  13286. }
  13287. }
  13288. var BezierCurve = (function (_super) {
  13289. __extends(BezierCurve, _super);
  13290. function BezierCurve(opts) {
  13291. return _super.call(this, opts) || this;
  13292. }
  13293. BezierCurve.prototype.getDefaultStyle = function () {
  13294. return {
  13295. stroke: '#000',
  13296. fill: null
  13297. };
  13298. };
  13299. BezierCurve.prototype.getDefaultShape = function () {
  13300. return new BezierCurveShape();
  13301. };
  13302. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13303. var x1 = shape.x1;
  13304. var y1 = shape.y1;
  13305. var x2 = shape.x2;
  13306. var y2 = shape.y2;
  13307. var cpx1 = shape.cpx1;
  13308. var cpy1 = shape.cpy1;
  13309. var cpx2 = shape.cpx2;
  13310. var cpy2 = shape.cpy2;
  13311. var percent = shape.percent;
  13312. if (percent === 0) {
  13313. return;
  13314. }
  13315. ctx.moveTo(x1, y1);
  13316. if (cpx2 == null || cpy2 == null) {
  13317. if (percent < 1) {
  13318. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13319. cpx1 = out[1];
  13320. x2 = out[2];
  13321. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13322. cpy1 = out[1];
  13323. y2 = out[2];
  13324. }
  13325. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13326. }
  13327. else {
  13328. if (percent < 1) {
  13329. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13330. cpx1 = out[1];
  13331. cpx2 = out[2];
  13332. x2 = out[3];
  13333. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13334. cpy1 = out[1];
  13335. cpy2 = out[2];
  13336. y2 = out[3];
  13337. }
  13338. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13339. }
  13340. };
  13341. BezierCurve.prototype.pointAt = function (t) {
  13342. return someVectorAt(this.shape, t, false);
  13343. };
  13344. BezierCurve.prototype.tangentAt = function (t) {
  13345. var p = someVectorAt(this.shape, t, true);
  13346. return normalize(p, p);
  13347. };
  13348. return BezierCurve;
  13349. }(Path));
  13350. BezierCurve.prototype.type = 'bezier-curve';
  13351. var ArcShape = (function () {
  13352. function ArcShape() {
  13353. this.cx = 0;
  13354. this.cy = 0;
  13355. this.r = 0;
  13356. this.startAngle = 0;
  13357. this.endAngle = Math.PI * 2;
  13358. this.clockwise = true;
  13359. }
  13360. return ArcShape;
  13361. }());
  13362. var Arc = (function (_super) {
  13363. __extends(Arc, _super);
  13364. function Arc(opts) {
  13365. return _super.call(this, opts) || this;
  13366. }
  13367. Arc.prototype.getDefaultStyle = function () {
  13368. return {
  13369. stroke: '#000',
  13370. fill: null
  13371. };
  13372. };
  13373. Arc.prototype.getDefaultShape = function () {
  13374. return new ArcShape();
  13375. };
  13376. Arc.prototype.buildPath = function (ctx, shape) {
  13377. var x = shape.cx;
  13378. var y = shape.cy;
  13379. var r = Math.max(shape.r, 0);
  13380. var startAngle = shape.startAngle;
  13381. var endAngle = shape.endAngle;
  13382. var clockwise = shape.clockwise;
  13383. var unitX = Math.cos(startAngle);
  13384. var unitY = Math.sin(startAngle);
  13385. ctx.moveTo(unitX * r + x, unitY * r + y);
  13386. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13387. };
  13388. return Arc;
  13389. }(Path));
  13390. Arc.prototype.type = 'arc';
  13391. var CompoundPath = (function (_super) {
  13392. __extends(CompoundPath, _super);
  13393. function CompoundPath() {
  13394. var _this = _super !== null && _super.apply(this, arguments) || this;
  13395. _this.type = 'compound';
  13396. return _this;
  13397. }
  13398. CompoundPath.prototype._updatePathDirty = function () {
  13399. var paths = this.shape.paths;
  13400. var dirtyPath = this.shapeChanged();
  13401. for (var i = 0; i < paths.length; i++) {
  13402. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13403. }
  13404. if (dirtyPath) {
  13405. this.dirtyShape();
  13406. }
  13407. };
  13408. CompoundPath.prototype.beforeBrush = function () {
  13409. this._updatePathDirty();
  13410. var paths = this.shape.paths || [];
  13411. var scale = this.getGlobalScale();
  13412. for (var i = 0; i < paths.length; i++) {
  13413. if (!paths[i].path) {
  13414. paths[i].createPathProxy();
  13415. }
  13416. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13417. }
  13418. };
  13419. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13420. var paths = shape.paths || [];
  13421. for (var i = 0; i < paths.length; i++) {
  13422. paths[i].buildPath(ctx, paths[i].shape, true);
  13423. }
  13424. };
  13425. CompoundPath.prototype.afterBrush = function () {
  13426. var paths = this.shape.paths || [];
  13427. for (var i = 0; i < paths.length; i++) {
  13428. paths[i].pathUpdated();
  13429. }
  13430. };
  13431. CompoundPath.prototype.getBoundingRect = function () {
  13432. this._updatePathDirty.call(this);
  13433. return Path.prototype.getBoundingRect.call(this);
  13434. };
  13435. return CompoundPath;
  13436. }(Path));
  13437. var Gradient = (function () {
  13438. function Gradient(colorStops) {
  13439. this.colorStops = colorStops || [];
  13440. }
  13441. Gradient.prototype.addColorStop = function (offset, color) {
  13442. this.colorStops.push({
  13443. offset: offset,
  13444. color: color
  13445. });
  13446. };
  13447. return Gradient;
  13448. }());
  13449. var LinearGradient = (function (_super) {
  13450. __extends(LinearGradient, _super);
  13451. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13452. var _this = _super.call(this, colorStops) || this;
  13453. _this.x = x == null ? 0 : x;
  13454. _this.y = y == null ? 0 : y;
  13455. _this.x2 = x2 == null ? 1 : x2;
  13456. _this.y2 = y2 == null ? 0 : y2;
  13457. _this.type = 'linear';
  13458. _this.global = globalCoord || false;
  13459. return _this;
  13460. }
  13461. return LinearGradient;
  13462. }(Gradient));
  13463. var RadialGradient = (function (_super) {
  13464. __extends(RadialGradient, _super);
  13465. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13466. var _this = _super.call(this, colorStops) || this;
  13467. _this.x = x == null ? 0.5 : x;
  13468. _this.y = y == null ? 0.5 : y;
  13469. _this.r = r == null ? 0.5 : r;
  13470. _this.type = 'radial';
  13471. _this.global = globalCoord || false;
  13472. return _this;
  13473. }
  13474. return RadialGradient;
  13475. }(Gradient));
  13476. var extent = [0, 0];
  13477. var extent2 = [0, 0];
  13478. var minTv$1 = new Point();
  13479. var maxTv$1 = new Point();
  13480. var OrientedBoundingRect = (function () {
  13481. function OrientedBoundingRect(rect, transform) {
  13482. this._corners = [];
  13483. this._axes = [];
  13484. this._origin = [0, 0];
  13485. for (var i = 0; i < 4; i++) {
  13486. this._corners[i] = new Point();
  13487. }
  13488. for (var i = 0; i < 2; i++) {
  13489. this._axes[i] = new Point();
  13490. }
  13491. if (rect) {
  13492. this.fromBoundingRect(rect, transform);
  13493. }
  13494. }
  13495. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13496. var corners = this._corners;
  13497. var axes = this._axes;
  13498. var x = rect.x;
  13499. var y = rect.y;
  13500. var x2 = x + rect.width;
  13501. var y2 = y + rect.height;
  13502. corners[0].set(x, y);
  13503. corners[1].set(x2, y);
  13504. corners[2].set(x2, y2);
  13505. corners[3].set(x, y2);
  13506. if (transform) {
  13507. for (var i = 0; i < 4; i++) {
  13508. corners[i].transform(transform);
  13509. }
  13510. }
  13511. Point.sub(axes[0], corners[1], corners[0]);
  13512. Point.sub(axes[1], corners[3], corners[0]);
  13513. axes[0].normalize();
  13514. axes[1].normalize();
  13515. for (var i = 0; i < 2; i++) {
  13516. this._origin[i] = axes[i].dot(corners[0]);
  13517. }
  13518. };
  13519. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13520. var overlapped = true;
  13521. var noMtv = !mtv;
  13522. minTv$1.set(Infinity, Infinity);
  13523. maxTv$1.set(0, 0);
  13524. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13525. overlapped = false;
  13526. if (noMtv) {
  13527. return overlapped;
  13528. }
  13529. }
  13530. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13531. overlapped = false;
  13532. if (noMtv) {
  13533. return overlapped;
  13534. }
  13535. }
  13536. if (!noMtv) {
  13537. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13538. }
  13539. return overlapped;
  13540. };
  13541. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13542. var overlapped = true;
  13543. for (var i = 0; i < 2; i++) {
  13544. var axis = this._axes[i];
  13545. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13546. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13547. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13548. overlapped = false;
  13549. if (noMtv) {
  13550. return overlapped;
  13551. }
  13552. var dist0 = Math.abs(extent2[0] - extent[1]);
  13553. var dist1 = Math.abs(extent[0] - extent2[1]);
  13554. if (Math.min(dist0, dist1) > maxTv.len()) {
  13555. if (dist0 < dist1) {
  13556. Point.scale(maxTv, axis, -dist0 * inverse);
  13557. }
  13558. else {
  13559. Point.scale(maxTv, axis, dist1 * inverse);
  13560. }
  13561. }
  13562. }
  13563. else if (minTv) {
  13564. var dist0 = Math.abs(extent2[0] - extent[1]);
  13565. var dist1 = Math.abs(extent[0] - extent2[1]);
  13566. if (Math.min(dist0, dist1) < minTv.len()) {
  13567. if (dist0 < dist1) {
  13568. Point.scale(minTv, axis, dist0 * inverse);
  13569. }
  13570. else {
  13571. Point.scale(minTv, axis, -dist1 * inverse);
  13572. }
  13573. }
  13574. }
  13575. }
  13576. return overlapped;
  13577. };
  13578. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13579. var axis = this._axes[dim];
  13580. var origin = this._origin;
  13581. var proj = corners[0].dot(axis) + origin[dim];
  13582. var min = proj;
  13583. var max = proj;
  13584. for (var i = 1; i < corners.length; i++) {
  13585. var proj_1 = corners[i].dot(axis) + origin[dim];
  13586. min = Math.min(proj_1, min);
  13587. max = Math.max(proj_1, max);
  13588. }
  13589. out[0] = min;
  13590. out[1] = max;
  13591. };
  13592. return OrientedBoundingRect;
  13593. }());
  13594. var m = [];
  13595. var IncrementalDisplayable = (function (_super) {
  13596. __extends(IncrementalDisplayable, _super);
  13597. function IncrementalDisplayable() {
  13598. var _this = _super !== null && _super.apply(this, arguments) || this;
  13599. _this.notClear = true;
  13600. _this.incremental = true;
  13601. _this._displayables = [];
  13602. _this._temporaryDisplayables = [];
  13603. _this._cursor = 0;
  13604. return _this;
  13605. }
  13606. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13607. cb.call(context, this);
  13608. };
  13609. IncrementalDisplayable.prototype.useStyle = function () {
  13610. this.style = {};
  13611. };
  13612. IncrementalDisplayable.prototype.getCursor = function () {
  13613. return this._cursor;
  13614. };
  13615. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13616. this._cursor = this._displayables.length;
  13617. };
  13618. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13619. this._displayables = [];
  13620. this._temporaryDisplayables = [];
  13621. this._cursor = 0;
  13622. this.markRedraw();
  13623. this.notClear = false;
  13624. };
  13625. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13626. this._temporaryDisplayables = [];
  13627. };
  13628. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13629. if (notPersistent) {
  13630. this._temporaryDisplayables.push(displayable);
  13631. }
  13632. else {
  13633. this._displayables.push(displayable);
  13634. }
  13635. this.markRedraw();
  13636. };
  13637. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13638. notPersistent = notPersistent || false;
  13639. for (var i = 0; i < displayables.length; i++) {
  13640. this.addDisplayable(displayables[i], notPersistent);
  13641. }
  13642. };
  13643. IncrementalDisplayable.prototype.getDisplayables = function () {
  13644. return this._displayables;
  13645. };
  13646. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13647. return this._temporaryDisplayables;
  13648. };
  13649. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13650. for (var i = this._cursor; i < this._displayables.length; i++) {
  13651. cb && cb(this._displayables[i]);
  13652. }
  13653. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13654. cb && cb(this._temporaryDisplayables[i]);
  13655. }
  13656. };
  13657. IncrementalDisplayable.prototype.update = function () {
  13658. this.updateTransform();
  13659. for (var i = this._cursor; i < this._displayables.length; i++) {
  13660. var displayable = this._displayables[i];
  13661. displayable.parent = this;
  13662. displayable.update();
  13663. displayable.parent = null;
  13664. }
  13665. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13666. var displayable = this._temporaryDisplayables[i];
  13667. displayable.parent = this;
  13668. displayable.update();
  13669. displayable.parent = null;
  13670. }
  13671. };
  13672. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13673. if (!this._rect) {
  13674. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13675. for (var i = 0; i < this._displayables.length; i++) {
  13676. var displayable = this._displayables[i];
  13677. var childRect = displayable.getBoundingRect().clone();
  13678. if (displayable.needLocalTransform()) {
  13679. childRect.applyTransform(displayable.getLocalTransform(m));
  13680. }
  13681. rect.union(childRect);
  13682. }
  13683. this._rect = rect;
  13684. }
  13685. return this._rect;
  13686. };
  13687. IncrementalDisplayable.prototype.contain = function (x, y) {
  13688. var localPos = this.transformCoordToLocal(x, y);
  13689. var rect = this.getBoundingRect();
  13690. if (rect.contain(localPos[0], localPos[1])) {
  13691. for (var i = 0; i < this._displayables.length; i++) {
  13692. var displayable = this._displayables[i];
  13693. if (displayable.contain(x, y)) {
  13694. return true;
  13695. }
  13696. }
  13697. }
  13698. return false;
  13699. };
  13700. return IncrementalDisplayable;
  13701. }(Displayable));
  13702. var transitionStore = makeInner();
  13703. /**
  13704. * Return null if animation is disabled.
  13705. */
  13706. function getAnimationConfig(animationType, animatableModel, dataIndex, // Extra opts can override the option in animatable model.
  13707. extraOpts, // TODO It's only for pictorial bar now.
  13708. extraDelayParams) {
  13709. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  13710. // If animation is enabled. Will use this animation config in payload.
  13711. // If animation is disabled. Just ignore it.
  13712. if (animatableModel && animatableModel.ecModel) {
  13713. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  13714. animationPayload = updatePayload && updatePayload.animation;
  13715. }
  13716. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  13717. var isUpdate = animationType === 'update';
  13718. if (animationEnabled) {
  13719. var duration = void 0;
  13720. var easing = void 0;
  13721. var delay = void 0;
  13722. if (extraOpts) {
  13723. duration = retrieve2(extraOpts.duration, 200);
  13724. easing = retrieve2(extraOpts.easing, 'cubicOut');
  13725. delay = 0;
  13726. } else {
  13727. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  13728. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  13729. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  13730. } // animation from payload has highest priority.
  13731. if (animationPayload) {
  13732. animationPayload.duration != null && (duration = animationPayload.duration);
  13733. animationPayload.easing != null && (easing = animationPayload.easing);
  13734. animationPayload.delay != null && (delay = animationPayload.delay);
  13735. }
  13736. if (isFunction(delay)) {
  13737. delay = delay(dataIndex, extraDelayParams);
  13738. }
  13739. if (isFunction(duration)) {
  13740. duration = duration(dataIndex);
  13741. }
  13742. var config = {
  13743. duration: duration || 0,
  13744. delay: delay,
  13745. easing: easing
  13746. };
  13747. return config;
  13748. } else {
  13749. return null;
  13750. }
  13751. }
  13752. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  13753. var isFrom = false;
  13754. var removeOpt;
  13755. if (isFunction(dataIndex)) {
  13756. during = cb;
  13757. cb = dataIndex;
  13758. dataIndex = null;
  13759. } else if (isObject(dataIndex)) {
  13760. cb = dataIndex.cb;
  13761. during = dataIndex.during;
  13762. isFrom = dataIndex.isFrom;
  13763. removeOpt = dataIndex.removeOpt;
  13764. dataIndex = dataIndex.dataIndex;
  13765. }
  13766. var isRemove = animationType === 'leave';
  13767. if (!isRemove) {
  13768. // Must stop the remove animation.
  13769. el.stopAnimation('leave');
  13770. }
  13771. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  13772. if (animationConfig && animationConfig.duration > 0) {
  13773. var duration = animationConfig.duration;
  13774. var animationDelay = animationConfig.delay;
  13775. var animationEasing = animationConfig.easing;
  13776. var animateConfig = {
  13777. duration: duration,
  13778. delay: animationDelay || 0,
  13779. easing: animationEasing,
  13780. done: cb,
  13781. force: !!cb || !!during,
  13782. // Set to final state in update/init animation.
  13783. // So the post processing based on the path shape can be done correctly.
  13784. setToFinal: !isRemove,
  13785. scope: animationType,
  13786. during: during
  13787. };
  13788. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  13789. } else {
  13790. el.stopAnimation(); // If `isFrom`, the props is the "from" props.
  13791. !isFrom && el.attr(props); // Call during at least once.
  13792. during && during(1);
  13793. cb && cb();
  13794. }
  13795. }
  13796. /**
  13797. * Update graphic element properties with or without animation according to the
  13798. * configuration in series.
  13799. *
  13800. * Caution: this method will stop previous animation.
  13801. * So do not use this method to one element twice before
  13802. * animation starts, unless you know what you are doing.
  13803. * @example
  13804. * graphic.updateProps(el, {
  13805. * position: [100, 100]
  13806. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  13807. * // Or
  13808. * graphic.updateProps(el, {
  13809. * position: [100, 100]
  13810. * }, seriesModel, function () { console.log('Animation done!'); });
  13811. */
  13812. function updateProps(el, props, // TODO: TYPE AnimatableModel
  13813. animatableModel, dataIndex, cb, during) {
  13814. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  13815. }
  13816. /**
  13817. * Init graphic element properties with or without animation according to the
  13818. * configuration in series.
  13819. *
  13820. * Caution: this method will stop previous animation.
  13821. * So do not use this method to one element twice before
  13822. * animation starts, unless you know what you are doing.
  13823. */
  13824. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  13825. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  13826. }
  13827. /**
  13828. * If element is removed.
  13829. * It can determine if element is having remove animation.
  13830. */
  13831. function isElementRemoved(el) {
  13832. if (!el.__zr) {
  13833. return true;
  13834. }
  13835. for (var i = 0; i < el.animators.length; i++) {
  13836. var animator = el.animators[i];
  13837. if (animator.scope === 'leave') {
  13838. return true;
  13839. }
  13840. }
  13841. return false;
  13842. }
  13843. /**
  13844. * Remove graphic element
  13845. */
  13846. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  13847. // Don't do remove animation twice.
  13848. if (isElementRemoved(el)) {
  13849. return;
  13850. }
  13851. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  13852. }
  13853. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  13854. el.removeTextContent();
  13855. el.removeTextGuideLine();
  13856. removeElement(el, {
  13857. style: {
  13858. opacity: 0
  13859. }
  13860. }, animatableModel, dataIndex, done);
  13861. }
  13862. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  13863. function doRemove() {
  13864. el.parent && el.parent.remove(el);
  13865. } // Hide label and labelLine first
  13866. // TODO Also use fade out animation?
  13867. if (!el.isGroup) {
  13868. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  13869. } else {
  13870. el.traverse(function (disp) {
  13871. if (!disp.isGroup) {
  13872. // Can invoke doRemove multiple times.
  13873. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  13874. }
  13875. });
  13876. }
  13877. }
  13878. /**
  13879. * Save old style for style transition in universalTransition module.
  13880. * It's used when element will be reused in each render.
  13881. * For chart like map, heatmap, which will always create new element.
  13882. * We don't need to save this because universalTransition can get old style from the old element
  13883. */
  13884. function saveOldStyle(el) {
  13885. transitionStore(el).oldStyle = el.style;
  13886. }
  13887. var mathMax$4 = Math.max;
  13888. var mathMin$4 = Math.min;
  13889. var _customShapeMap = {};
  13890. /**
  13891. * Extend shape with parameters
  13892. */
  13893. function extendShape(opts) {
  13894. return Path.extend(opts);
  13895. }
  13896. var extendPathFromString = extendFromString;
  13897. /**
  13898. * Extend path
  13899. */
  13900. function extendPath(pathData, opts) {
  13901. return extendPathFromString(pathData, opts);
  13902. }
  13903. /**
  13904. * Register a user defined shape.
  13905. * The shape class can be fetched by `getShapeClass`
  13906. * This method will overwrite the registered shapes, including
  13907. * the registered built-in shapes, if using the same `name`.
  13908. * The shape can be used in `custom series` and
  13909. * `graphic component` by declaring `{type: name}`.
  13910. *
  13911. * @param name
  13912. * @param ShapeClass Can be generated by `extendShape`.
  13913. */
  13914. function registerShape(name, ShapeClass) {
  13915. _customShapeMap[name] = ShapeClass;
  13916. }
  13917. /**
  13918. * Find shape class registered by `registerShape`. Usually used in
  13919. * fetching user defined shape.
  13920. *
  13921. * [Caution]:
  13922. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  13923. * to use user registered shapes.
  13924. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  13925. * `registerShape` by default. That enables users to get both built-in
  13926. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  13927. * the built-in shapes by using names like 'circle', 'rect' via calling
  13928. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  13929. * in case that it is overwritten by users, except that some features, like
  13930. * `custom series`, `graphic component`, do it deliberately.
  13931. *
  13932. * (2) In the features like `custom series`, `graphic component`, the user input
  13933. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  13934. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  13935. * are reserved names, that is, if some user register a shape named `'image'`,
  13936. * the shape will not be used. If we intending to add some more reserved names
  13937. * in feature, that might bring break changes (disable some existing user shape
  13938. * names). But that case probably rearly happen. So we dont make more mechanism
  13939. * to resolve this issue here.
  13940. *
  13941. * @param name
  13942. * @return The shape class. If not found, return nothing.
  13943. */
  13944. function getShapeClass(name) {
  13945. if (_customShapeMap.hasOwnProperty(name)) {
  13946. return _customShapeMap[name];
  13947. }
  13948. }
  13949. /**
  13950. * Create a path element from path data string
  13951. * @param pathData
  13952. * @param opts
  13953. * @param rect
  13954. * @param layout 'center' or 'cover' default to be cover
  13955. */
  13956. function makePath(pathData, opts, rect, layout) {
  13957. var path = createFromString(pathData, opts);
  13958. if (rect) {
  13959. if (layout === 'center') {
  13960. rect = centerGraphic(rect, path.getBoundingRect());
  13961. }
  13962. resizePath(path, rect);
  13963. }
  13964. return path;
  13965. }
  13966. /**
  13967. * Create a image element from image url
  13968. * @param imageUrl image url
  13969. * @param opts options
  13970. * @param rect constrain rect
  13971. * @param layout 'center' or 'cover'. Default to be 'cover'
  13972. */
  13973. function makeImage(imageUrl, rect, layout) {
  13974. var zrImg = new ZRImage({
  13975. style: {
  13976. image: imageUrl,
  13977. x: rect.x,
  13978. y: rect.y,
  13979. width: rect.width,
  13980. height: rect.height
  13981. },
  13982. onload: function (img) {
  13983. if (layout === 'center') {
  13984. var boundingRect = {
  13985. width: img.width,
  13986. height: img.height
  13987. };
  13988. zrImg.setStyle(centerGraphic(rect, boundingRect));
  13989. }
  13990. }
  13991. });
  13992. return zrImg;
  13993. }
  13994. /**
  13995. * Get position of centered element in bounding box.
  13996. *
  13997. * @param rect element local bounding box
  13998. * @param boundingRect constraint bounding box
  13999. * @return element position containing x, y, width, and height
  14000. */
  14001. function centerGraphic(rect, boundingRect) {
  14002. // Set rect to center, keep width / height ratio.
  14003. var aspect = boundingRect.width / boundingRect.height;
  14004. var width = rect.height * aspect;
  14005. var height;
  14006. if (width <= rect.width) {
  14007. height = rect.height;
  14008. } else {
  14009. width = rect.width;
  14010. height = width / aspect;
  14011. }
  14012. var cx = rect.x + rect.width / 2;
  14013. var cy = rect.y + rect.height / 2;
  14014. return {
  14015. x: cx - width / 2,
  14016. y: cy - height / 2,
  14017. width: width,
  14018. height: height
  14019. };
  14020. }
  14021. var mergePath$1 = mergePath;
  14022. /**
  14023. * Resize a path to fit the rect
  14024. * @param path
  14025. * @param rect
  14026. */
  14027. function resizePath(path, rect) {
  14028. if (!path.applyTransform) {
  14029. return;
  14030. }
  14031. var pathRect = path.getBoundingRect();
  14032. var m = pathRect.calculateTransform(rect);
  14033. path.applyTransform(m);
  14034. }
  14035. /**
  14036. * Get transform matrix of target (param target),
  14037. * in coordinate of its ancestor (param ancestor)
  14038. *
  14039. * @param target
  14040. * @param [ancestor]
  14041. */
  14042. function getTransform(target, ancestor) {
  14043. var mat = identity([]);
  14044. while (target && target !== ancestor) {
  14045. mul$1(mat, target.getLocalTransform(), mat);
  14046. target = target.parent;
  14047. }
  14048. return mat;
  14049. }
  14050. function isNotGroup(el) {
  14051. return !el.isGroup;
  14052. }
  14053. function isPath(el) {
  14054. return el.shape != null;
  14055. }
  14056. /**
  14057. * Apply group transition animation from g1 to g2.
  14058. * If no animatableModel, no animation.
  14059. */
  14060. function groupTransition(g1, g2, animatableModel) {
  14061. if (!g1 || !g2) {
  14062. return;
  14063. }
  14064. function getElMap(g) {
  14065. var elMap = {};
  14066. g.traverse(function (el) {
  14067. if (isNotGroup(el) && el.anid) {
  14068. elMap[el.anid] = el;
  14069. }
  14070. });
  14071. return elMap;
  14072. }
  14073. function getAnimatableProps(el) {
  14074. var obj = {
  14075. x: el.x,
  14076. y: el.y,
  14077. rotation: el.rotation
  14078. };
  14079. if (isPath(el)) {
  14080. obj.shape = extend({}, el.shape);
  14081. }
  14082. return obj;
  14083. }
  14084. var elMap1 = getElMap(g1);
  14085. g2.traverse(function (el) {
  14086. if (isNotGroup(el) && el.anid) {
  14087. var oldEl = elMap1[el.anid];
  14088. if (oldEl) {
  14089. var newProp = getAnimatableProps(el);
  14090. el.attr(getAnimatableProps(oldEl));
  14091. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14092. }
  14093. }
  14094. });
  14095. }
  14096. function clipPointsByRect(points, rect) {
  14097. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  14098. // and when element have border.
  14099. return map(points, function (point) {
  14100. var x = point[0];
  14101. x = mathMax$4(x, rect.x);
  14102. x = mathMin$4(x, rect.x + rect.width);
  14103. var y = point[1];
  14104. y = mathMax$4(y, rect.y);
  14105. y = mathMin$4(y, rect.y + rect.height);
  14106. return [x, y];
  14107. });
  14108. }
  14109. /**
  14110. * Return a new clipped rect. If rect size are negative, return undefined.
  14111. */
  14112. function clipRectByRect(targetRect, rect) {
  14113. var x = mathMax$4(targetRect.x, rect.x);
  14114. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14115. var y = mathMax$4(targetRect.y, rect.y);
  14116. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14117. // should be painted. So return undefined.
  14118. if (x2 >= x && y2 >= y) {
  14119. return {
  14120. x: x,
  14121. y: y,
  14122. width: x2 - x,
  14123. height: y2 - y
  14124. };
  14125. }
  14126. }
  14127. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14128. opt, rect) {
  14129. var innerOpts = extend({
  14130. rectHover: true
  14131. }, opt);
  14132. var style = innerOpts.style = {
  14133. strokeNoScale: true
  14134. };
  14135. rect = rect || {
  14136. x: -1,
  14137. y: -1,
  14138. width: 2,
  14139. height: 2
  14140. };
  14141. if (iconStr) {
  14142. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14143. }
  14144. }
  14145. function setTooltipConfig(opt) {
  14146. var itemTooltipOption = opt.itemTooltipOption;
  14147. var componentModel = opt.componentModel;
  14148. var itemName = opt.itemName;
  14149. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14150. formatter: itemTooltipOption
  14151. } : itemTooltipOption;
  14152. var mainType = componentModel.mainType;
  14153. var componentIndex = componentModel.componentIndex;
  14154. var formatterParams = {
  14155. componentType: mainType,
  14156. name: itemName,
  14157. $vars: ['name']
  14158. };
  14159. formatterParams[mainType + 'Index'] = componentIndex;
  14160. var formatterParamsExtra = opt.formatterParamsExtra;
  14161. if (formatterParamsExtra) {
  14162. each(keys(formatterParamsExtra), function (key) {
  14163. if (!hasOwn(formatterParams, key)) {
  14164. formatterParams[key] = formatterParamsExtra[key];
  14165. formatterParams.$vars.push(key);
  14166. }
  14167. });
  14168. }
  14169. var ecData = getECData(opt.el);
  14170. ecData.componentMainType = mainType;
  14171. ecData.componentIndex = componentIndex;
  14172. ecData.tooltipConfig = {
  14173. name: itemName,
  14174. option: defaults({
  14175. content: itemName,
  14176. formatterParams: formatterParams
  14177. }, itemTooltipOptionObj)
  14178. };
  14179. }
  14180. function traverseElement(el, cb) {
  14181. var stopped; // TODO
  14182. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14183. if (el.isGroup) {
  14184. stopped = cb(el);
  14185. }
  14186. if (!stopped) {
  14187. el.traverse(cb);
  14188. }
  14189. }
  14190. function traverseElements(els, cb) {
  14191. if (els) {
  14192. if (isArray(els)) {
  14193. for (var i = 0; i < els.length; i++) {
  14194. traverseElement(els[i], cb);
  14195. }
  14196. } else {
  14197. traverseElement(els, cb);
  14198. }
  14199. }
  14200. } // Register built-in shapes. These shapes might be overwirtten
  14201. // by users, although we do not recommend that.
  14202. registerShape('circle', Circle);
  14203. registerShape('ellipse', Ellipse);
  14204. registerShape('sector', Sector);
  14205. registerShape('ring', Ring);
  14206. registerShape('polygon', Polygon);
  14207. registerShape('polyline', Polyline);
  14208. registerShape('rect', Rect);
  14209. registerShape('line', Line);
  14210. registerShape('bezierCurve', BezierCurve);
  14211. registerShape('arc', Arc);
  14212. var EMPTY_OBJ = {};
  14213. function setLabelText(label, labelTexts) {
  14214. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14215. var stateName = SPECIAL_STATES[i];
  14216. var text = labelTexts[stateName];
  14217. var state = label.ensureState(stateName);
  14218. state.style = state.style || {};
  14219. state.style.text = text;
  14220. }
  14221. var oldStates = label.currentStates.slice();
  14222. label.clearStates(true);
  14223. label.setStyle({
  14224. text: labelTexts.normal
  14225. });
  14226. label.useStates(oldStates, true);
  14227. }
  14228. function getLabelText(opt, stateModels, interpolatedValue) {
  14229. var labelFetcher = opt.labelFetcher;
  14230. var labelDataIndex = opt.labelDataIndex;
  14231. var labelDimIndex = opt.labelDimIndex;
  14232. var normalModel = stateModels.normal;
  14233. var baseText;
  14234. if (labelFetcher) {
  14235. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14236. interpolatedValue: interpolatedValue
  14237. } : null);
  14238. }
  14239. if (baseText == null) {
  14240. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14241. }
  14242. var statesText = {
  14243. normal: baseText
  14244. };
  14245. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14246. var stateName = SPECIAL_STATES[i];
  14247. var stateModel = stateModels[stateName];
  14248. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14249. }
  14250. return statesText;
  14251. }
  14252. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14253. ) {
  14254. opt = opt || EMPTY_OBJ;
  14255. var isSetOnText = targetEl instanceof ZRText;
  14256. var needsCreateText = false;
  14257. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14258. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14259. if (stateModel && stateModel.getShallow('show')) {
  14260. needsCreateText = true;
  14261. break;
  14262. }
  14263. }
  14264. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14265. if (needsCreateText) {
  14266. if (!isSetOnText) {
  14267. // Reuse the previous
  14268. if (!textContent) {
  14269. textContent = new ZRText();
  14270. targetEl.setTextContent(textContent);
  14271. } // Use same state proxy
  14272. if (targetEl.stateProxy) {
  14273. textContent.stateProxy = targetEl.stateProxy;
  14274. }
  14275. }
  14276. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14277. var normalModel = labelStatesModels.normal;
  14278. var showNormal = !!normalModel.getShallow('show');
  14279. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14280. normalStyle.text = labelStatesTexts.normal;
  14281. if (!isSetOnText) {
  14282. // Always create new
  14283. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14284. }
  14285. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14286. var stateName = SPECIAL_STATES[i];
  14287. var stateModel = labelStatesModels[stateName];
  14288. if (stateModel) {
  14289. var stateObj = textContent.ensureState(stateName);
  14290. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14291. if (stateShow !== showNormal) {
  14292. stateObj.ignore = !stateShow;
  14293. }
  14294. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14295. stateObj.style.text = labelStatesTexts[stateName];
  14296. if (!isSetOnText) {
  14297. var targetElEmphasisState = targetEl.ensureState(stateName);
  14298. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14299. }
  14300. }
  14301. } // PENDING: if there is many requirements that emphasis position
  14302. // need to be different from normal position, we might consider
  14303. // auto slient is those cases.
  14304. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14305. if (textContent.style.x != null) {
  14306. normalStyle.x = textContent.style.x;
  14307. }
  14308. if (textContent.style.y != null) {
  14309. normalStyle.y = textContent.style.y;
  14310. }
  14311. textContent.ignore = !showNormal; // Always create new style.
  14312. textContent.useStyle(normalStyle);
  14313. textContent.dirty();
  14314. if (opt.enableTextSetter) {
  14315. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14316. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14317. setLabelText(textContent, labelStatesTexts);
  14318. };
  14319. }
  14320. } else if (textContent) {
  14321. // Not display rich text.
  14322. textContent.ignore = true;
  14323. }
  14324. targetEl.dirty();
  14325. }
  14326. function getLabelStatesModels(itemModel, labelName) {
  14327. labelName = labelName || 'label';
  14328. var statesModels = {
  14329. normal: itemModel.getModel(labelName)
  14330. };
  14331. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14332. var stateName = SPECIAL_STATES[i];
  14333. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14334. }
  14335. return statesModels;
  14336. }
  14337. /**
  14338. * Set basic textStyle properties.
  14339. */
  14340. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14341. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14342. ) {
  14343. var textStyle = {};
  14344. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14345. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14346. return textStyle;
  14347. }
  14348. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14349. opt = opt || {};
  14350. var textConfig = {};
  14351. var labelPosition;
  14352. var labelRotate = textStyleModel.getShallow('rotate');
  14353. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14354. var labelOffset = textStyleModel.getShallow('offset');
  14355. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14356. // in bar series, and magric type should be considered.
  14357. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14358. if (labelPosition != null) {
  14359. textConfig.position = labelPosition;
  14360. }
  14361. if (labelOffset != null) {
  14362. textConfig.offset = labelOffset;
  14363. }
  14364. if (labelRotate != null) {
  14365. labelRotate *= Math.PI / 180;
  14366. textConfig.rotation = labelRotate;
  14367. }
  14368. if (labelDistance != null) {
  14369. textConfig.distance = labelDistance;
  14370. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14371. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14372. return textConfig;
  14373. }
  14374. /**
  14375. * The uniform entry of set text style, that is, retrieve style definitions
  14376. * from `model` and set to `textStyle` object.
  14377. *
  14378. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14379. * properties will be set. (Consider the states of normal and emphasis and
  14380. * default value can be adopted, merge would make the logic too complicated
  14381. * to manage.)
  14382. */
  14383. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14384. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14385. opt = opt || EMPTY_OBJ;
  14386. var ecModel = textStyleModel.ecModel;
  14387. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14388. // {
  14389. // data: [{
  14390. // value: 12,
  14391. // label: {
  14392. // rich: {
  14393. // // no 'a' here but using parent 'a'.
  14394. // }
  14395. // }
  14396. // }],
  14397. // rich: {
  14398. // a: { ... }
  14399. // }
  14400. // }
  14401. var richItemNames = getRichItemNames(textStyleModel);
  14402. var richResult;
  14403. if (richItemNames) {
  14404. richResult = {};
  14405. for (var name_1 in richItemNames) {
  14406. if (richItemNames.hasOwnProperty(name_1)) {
  14407. // Cascade is supported in rich.
  14408. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14409. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14410. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14411. // That might confuses users. So probably we should put `textStyleModel` as the
  14412. // root ancestor of the `richTextStyle`. But that would be a break change.
  14413. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14414. }
  14415. }
  14416. }
  14417. if (richResult) {
  14418. textStyle.rich = richResult;
  14419. }
  14420. var overflow = textStyleModel.get('overflow');
  14421. if (overflow) {
  14422. textStyle.overflow = overflow;
  14423. }
  14424. var margin = textStyleModel.get('minMargin');
  14425. if (margin != null) {
  14426. textStyle.margin = margin;
  14427. }
  14428. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14429. } // Consider case:
  14430. // {
  14431. // data: [{
  14432. // value: 12,
  14433. // label: {
  14434. // rich: {
  14435. // // no 'a' here but using parent 'a'.
  14436. // }
  14437. // }
  14438. // }],
  14439. // rich: {
  14440. // a: { ... }
  14441. // }
  14442. // }
  14443. // TODO TextStyleModel
  14444. function getRichItemNames(textStyleModel) {
  14445. // Use object to remove duplicated names.
  14446. var richItemNameMap;
  14447. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14448. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14449. if (rich) {
  14450. richItemNameMap = richItemNameMap || {};
  14451. var richKeys = keys(rich);
  14452. for (var i = 0; i < richKeys.length; i++) {
  14453. var richKey = richKeys[i];
  14454. richItemNameMap[richKey] = 1;
  14455. }
  14456. }
  14457. textStyleModel = textStyleModel.parentModel;
  14458. }
  14459. return richItemNameMap;
  14460. }
  14461. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14462. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  14463. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14464. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14465. // In merge mode, default value should not be given.
  14466. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14467. var inheritColor = opt && opt.inheritColor;
  14468. var fillColor = textStyleModel.getShallow('color');
  14469. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14470. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14471. if (fillColor === 'inherit' || fillColor === 'auto') {
  14472. if ("development" !== 'production') {
  14473. if (fillColor === 'auto') {
  14474. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14475. }
  14476. }
  14477. if (inheritColor) {
  14478. fillColor = inheritColor;
  14479. } else {
  14480. fillColor = null;
  14481. }
  14482. }
  14483. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14484. if ("development" !== 'production') {
  14485. if (strokeColor === 'auto') {
  14486. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14487. }
  14488. }
  14489. if (inheritColor) {
  14490. strokeColor = inheritColor;
  14491. } else {
  14492. strokeColor = null;
  14493. }
  14494. }
  14495. if (!isAttached) {
  14496. // Only use default global textStyle.color if text is individual.
  14497. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14498. fillColor = fillColor || globalTextStyle.color;
  14499. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14500. }
  14501. if (fillColor != null) {
  14502. textStyle.fill = fillColor;
  14503. }
  14504. if (strokeColor != null) {
  14505. textStyle.stroke = strokeColor;
  14506. }
  14507. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14508. if (textBorderWidth != null) {
  14509. textStyle.lineWidth = textBorderWidth;
  14510. }
  14511. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14512. if (textBorderType != null) {
  14513. textStyle.lineDash = textBorderType;
  14514. }
  14515. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14516. if (textBorderDashOffset != null) {
  14517. textStyle.lineDashOffset = textBorderDashOffset;
  14518. }
  14519. if (!isNotNormal && opacity == null && !inRich) {
  14520. opacity = opt && opt.defaultOpacity;
  14521. }
  14522. if (opacity != null) {
  14523. textStyle.opacity = opacity;
  14524. } // TODO
  14525. if (!isNotNormal && !isAttached) {
  14526. // Set default finally.
  14527. if (textStyle.fill == null && opt.inheritColor) {
  14528. textStyle.fill = opt.inheritColor;
  14529. }
  14530. } // Do not use `getFont` here, because merge should be supported, where
  14531. // part of these properties may be changed in emphasis style, and the
  14532. // others should remain their original value got from normal style.
  14533. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14534. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14535. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14536. if (val != null) {
  14537. textStyle[key] = val;
  14538. }
  14539. }
  14540. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14541. var key = TEXT_PROPS_SELF[i];
  14542. var val = textStyleModel.getShallow(key);
  14543. if (val != null) {
  14544. textStyle[key] = val;
  14545. }
  14546. }
  14547. if (textStyle.verticalAlign == null) {
  14548. var baseline = textStyleModel.getShallow('baseline');
  14549. if (baseline != null) {
  14550. textStyle.verticalAlign = baseline;
  14551. }
  14552. }
  14553. if (!isBlock || !opt.disableBox) {
  14554. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  14555. var key = TEXT_PROPS_BOX[i];
  14556. var val = textStyleModel.getShallow(key);
  14557. if (val != null) {
  14558. textStyle[key] = val;
  14559. }
  14560. }
  14561. var borderType = textStyleModel.getShallow('borderType');
  14562. if (borderType != null) {
  14563. textStyle.borderDash = borderType;
  14564. }
  14565. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  14566. if ("development" !== 'production') {
  14567. if (textStyle.backgroundColor === 'auto') {
  14568. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  14569. }
  14570. }
  14571. textStyle.backgroundColor = inheritColor;
  14572. }
  14573. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  14574. if ("development" !== 'production') {
  14575. if (textStyle.borderColor === 'auto') {
  14576. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  14577. }
  14578. }
  14579. textStyle.borderColor = inheritColor;
  14580. }
  14581. }
  14582. }
  14583. function getFont(opt, ecModel) {
  14584. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14585. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14586. 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(' '));
  14587. }
  14588. var labelInner = makeInner();
  14589. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  14590. if (!label) {
  14591. return;
  14592. }
  14593. var obj = labelInner(label);
  14594. obj.prevValue = obj.value;
  14595. obj.value = value;
  14596. var normalLabelModel = labelStatesModels.normal;
  14597. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  14598. if (obj.valueAnimation) {
  14599. obj.precision = normalLabelModel.get('precision');
  14600. obj.defaultInterpolatedText = getDefaultText;
  14601. obj.statesModels = labelStatesModels;
  14602. }
  14603. }
  14604. var PATH_COLOR = ['textStyle', 'color'];
  14605. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow']; // TODO Performance improvement?
  14606. var tmpText = new ZRText();
  14607. var TextStyleMixin =
  14608. /** @class */
  14609. function () {
  14610. function TextStyleMixin() {}
  14611. /**
  14612. * Get color property or get color from option.textStyle.color
  14613. */
  14614. // TODO Callback
  14615. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  14616. var ecModel = this.ecModel;
  14617. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  14618. };
  14619. /**
  14620. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14621. * @return {string}
  14622. */
  14623. TextStyleMixin.prototype.getFont = function () {
  14624. return getFont({
  14625. fontStyle: this.getShallow('fontStyle'),
  14626. fontWeight: this.getShallow('fontWeight'),
  14627. fontSize: this.getShallow('fontSize'),
  14628. fontFamily: this.getShallow('fontFamily')
  14629. }, this.ecModel);
  14630. };
  14631. TextStyleMixin.prototype.getTextRect = function (text) {
  14632. var style = {
  14633. text: text,
  14634. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  14635. };
  14636. for (var i = 0; i < textStyleParams.length; i++) {
  14637. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  14638. }
  14639. tmpText.useStyle(style);
  14640. tmpText.update();
  14641. return tmpText.getBoundingRect();
  14642. };
  14643. return TextStyleMixin;
  14644. }();
  14645. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  14646. // So do not transfer decal directly.
  14647. ];
  14648. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  14649. var LineStyleMixin =
  14650. /** @class */
  14651. function () {
  14652. function LineStyleMixin() {}
  14653. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  14654. return getLineStyle(this, excludes);
  14655. };
  14656. return LineStyleMixin;
  14657. }();
  14658. var ITEM_STYLE_KEY_MAP = [['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'borderType'], ['lineDashOffset', 'borderDashOffset'], ['lineCap', 'borderCap'], ['lineJoin', 'borderJoin'], ['miterLimit', 'borderMiterLimit'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  14659. // So do not transfer decal directly.
  14660. ];
  14661. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  14662. var ItemStyleMixin =
  14663. /** @class */
  14664. function () {
  14665. function ItemStyleMixin() {}
  14666. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  14667. return getItemStyle(this, excludes, includes);
  14668. };
  14669. return ItemStyleMixin;
  14670. }();
  14671. var Model =
  14672. /** @class */
  14673. function () {
  14674. function Model(option, parentModel, ecModel) {
  14675. this.parentModel = parentModel;
  14676. this.ecModel = ecModel;
  14677. this.option = option; // Simple optimization
  14678. // if (this.init) {
  14679. // if (arguments.length <= 4) {
  14680. // this.init(option, parentModel, ecModel, extraOpt);
  14681. // }
  14682. // else {
  14683. // this.init.apply(this, arguments);
  14684. // }
  14685. // }
  14686. }
  14687. Model.prototype.init = function (option, parentModel, ecModel) {
  14688. var rest = [];
  14689. for (var _i = 3; _i < arguments.length; _i++) {
  14690. rest[_i - 3] = arguments[_i];
  14691. }
  14692. };
  14693. /**
  14694. * Merge the input option to me.
  14695. */
  14696. Model.prototype.mergeOption = function (option, ecModel) {
  14697. merge(this.option, option, true);
  14698. }; // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  14699. // TODO: TYPE strict key check?
  14700. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  14701. Model.prototype.get = function (path, ignoreParent) {
  14702. if (path == null) {
  14703. return this.option;
  14704. }
  14705. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  14706. };
  14707. Model.prototype.getShallow = function (key, ignoreParent) {
  14708. var option = this.option;
  14709. var val = option == null ? option : option[key];
  14710. if (val == null && !ignoreParent) {
  14711. var parentModel = this.parentModel;
  14712. if (parentModel) {
  14713. // FIXME:TS do not know how to make it works
  14714. val = parentModel.getShallow(key);
  14715. }
  14716. }
  14717. return val;
  14718. }; // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  14719. // getModel(path: string | string[], parentModel?: Model): Model;
  14720. // TODO 'a.b.c' is deprecated
  14721. Model.prototype.getModel = function (path, parentModel) {
  14722. var hasPath = path != null;
  14723. var pathFinal = hasPath ? this.parsePath(path) : null;
  14724. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  14725. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  14726. return new Model(obj, parentModel, this.ecModel);
  14727. };
  14728. /**
  14729. * If model has option
  14730. */
  14731. Model.prototype.isEmpty = function () {
  14732. return this.option == null;
  14733. };
  14734. Model.prototype.restoreData = function () {}; // Pending
  14735. Model.prototype.clone = function () {
  14736. var Ctor = this.constructor;
  14737. return new Ctor(clone(this.option));
  14738. }; // setReadOnly(properties): void {
  14739. // clazzUtil.setReadOnly(this, properties);
  14740. // }
  14741. // If path is null/undefined, return null/undefined.
  14742. Model.prototype.parsePath = function (path) {
  14743. if (typeof path === 'string') {
  14744. return path.split('.');
  14745. }
  14746. return path;
  14747. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  14748. // Default to be a identity resolver.
  14749. // Can be modified to a different resolver.
  14750. Model.prototype.resolveParentPath = function (path) {
  14751. return path;
  14752. }; // FIXME:TS check whether put this method here
  14753. Model.prototype.isAnimationEnabled = function () {
  14754. if (!env.node && this.option) {
  14755. if (this.option.animation != null) {
  14756. return !!this.option.animation;
  14757. } else if (this.parentModel) {
  14758. return this.parentModel.isAnimationEnabled();
  14759. }
  14760. }
  14761. };
  14762. Model.prototype._doGet = function (pathArr, parentModel) {
  14763. var obj = this.option;
  14764. if (!pathArr) {
  14765. return obj;
  14766. }
  14767. for (var i = 0; i < pathArr.length; i++) {
  14768. // Ignore empty
  14769. if (!pathArr[i]) {
  14770. continue;
  14771. } // obj could be number/string/... (like 0)
  14772. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  14773. if (obj == null) {
  14774. break;
  14775. }
  14776. }
  14777. if (obj == null && parentModel) {
  14778. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  14779. }
  14780. return obj;
  14781. };
  14782. return Model;
  14783. }();
  14784. enableClassExtend(Model);
  14785. enableClassCheck(Model);
  14786. mixin(Model, LineStyleMixin);
  14787. mixin(Model, ItemStyleMixin);
  14788. mixin(Model, AreaStyleMixin);
  14789. mixin(Model, TextStyleMixin);
  14790. var base = Math.round(Math.random() * 10);
  14791. /**
  14792. * @public
  14793. * @param {string} type
  14794. * @return {string}
  14795. */
  14796. function getUID(type) {
  14797. // Considering the case of crossing js context,
  14798. // use Math.random to make id as unique as possible.
  14799. return [type || '', base++].join('_');
  14800. }
  14801. /**
  14802. * Implements `SubTypeDefaulterManager` for `target`.
  14803. */
  14804. function enableSubTypeDefaulter(target) {
  14805. var subTypeDefaulters = {};
  14806. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  14807. var componentTypeInfo = parseClassType(componentType);
  14808. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  14809. };
  14810. target.determineSubType = function (componentType, option) {
  14811. var type = option.type;
  14812. if (!type) {
  14813. var componentTypeMain = parseClassType(componentType).main;
  14814. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14815. type = subTypeDefaulters[componentTypeMain](option);
  14816. }
  14817. }
  14818. return type;
  14819. };
  14820. }
  14821. /**
  14822. * Implements `TopologicalTravelable<any>` for `entity`.
  14823. *
  14824. * Topological travel on Activity Network (Activity On Vertices).
  14825. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14826. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14827. * If there is circular dependencey, Error will be thrown.
  14828. */
  14829. function enableTopologicalTravel(entity, dependencyGetter) {
  14830. /**
  14831. * @param targetNameList Target Component type list.
  14832. * Can be ['aa', 'bb', 'aa.xx']
  14833. * @param fullNameList By which we can build dependency graph.
  14834. * @param callback Params: componentType, dependencies.
  14835. * @param context Scope of callback.
  14836. */
  14837. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14838. if (!targetNameList.length) {
  14839. return;
  14840. }
  14841. var result = makeDepndencyGraph(fullNameList);
  14842. var graph = result.graph;
  14843. var noEntryList = result.noEntryList;
  14844. var targetNameSet = {};
  14845. each(targetNameList, function (name) {
  14846. targetNameSet[name] = true;
  14847. });
  14848. while (noEntryList.length) {
  14849. var currComponentType = noEntryList.pop();
  14850. var currVertex = graph[currComponentType];
  14851. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14852. if (isInTargetNameSet) {
  14853. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14854. delete targetNameSet[currComponentType];
  14855. }
  14856. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  14857. }
  14858. each(targetNameSet, function () {
  14859. var errMsg = '';
  14860. if ("development" !== 'production') {
  14861. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  14862. }
  14863. throw new Error(errMsg);
  14864. });
  14865. function removeEdge(succComponentType) {
  14866. graph[succComponentType].entryCount--;
  14867. if (graph[succComponentType].entryCount === 0) {
  14868. noEntryList.push(succComponentType);
  14869. }
  14870. } // Consider this case: legend depends on series, and we call
  14871. // chart.setOption({series: [...]}), where only series is in option.
  14872. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14873. // not be called, but only sereis.mergeOption is called. Thus legend
  14874. // have no chance to update its local record about series (like which
  14875. // name of series is available in legend).
  14876. function removeEdgeAndAdd(succComponentType) {
  14877. targetNameSet[succComponentType] = true;
  14878. removeEdge(succComponentType);
  14879. }
  14880. };
  14881. function makeDepndencyGraph(fullNameList) {
  14882. var graph = {};
  14883. var noEntryList = [];
  14884. each(fullNameList, function (name) {
  14885. var thisItem = createDependencyGraphItem(graph, name);
  14886. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14887. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14888. thisItem.entryCount = availableDeps.length;
  14889. if (thisItem.entryCount === 0) {
  14890. noEntryList.push(name);
  14891. }
  14892. each(availableDeps, function (dependentName) {
  14893. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14894. thisItem.predecessor.push(dependentName);
  14895. }
  14896. var thatItem = createDependencyGraphItem(graph, dependentName);
  14897. if (indexOf(thatItem.successor, dependentName) < 0) {
  14898. thatItem.successor.push(name);
  14899. }
  14900. });
  14901. });
  14902. return {
  14903. graph: graph,
  14904. noEntryList: noEntryList
  14905. };
  14906. }
  14907. function createDependencyGraphItem(graph, name) {
  14908. if (!graph[name]) {
  14909. graph[name] = {
  14910. predecessor: [],
  14911. successor: []
  14912. };
  14913. }
  14914. return graph[name];
  14915. }
  14916. function getAvailableDependencies(originalDeps, fullNameList) {
  14917. var availableDeps = [];
  14918. each(originalDeps, function (dep) {
  14919. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  14920. });
  14921. return availableDeps;
  14922. }
  14923. }
  14924. function inheritDefaultOption(superOption, subOption) {
  14925. // See also `model/Component.ts#getDefaultOption`
  14926. return merge(merge({}, superOption, true), subOption, true);
  14927. }
  14928. /*
  14929. * Licensed to the Apache Software Foundation (ASF) under one
  14930. * or more contributor license agreements. See the NOTICE file
  14931. * distributed with this work for additional information
  14932. * regarding copyright ownership. The ASF licenses this file
  14933. * to you under the Apache License, Version 2.0 (the
  14934. * "License"); you may not use this file except in compliance
  14935. * with the License. You may obtain a copy of the License at
  14936. *
  14937. * http://www.apache.org/licenses/LICENSE-2.0
  14938. *
  14939. * Unless required by applicable law or agreed to in writing,
  14940. * software distributed under the License is distributed on an
  14941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14942. * KIND, either express or implied. See the License for the
  14943. * specific language governing permissions and limitations
  14944. * under the License.
  14945. */
  14946. /**
  14947. * AUTO-GENERATED FILE. DO NOT MODIFY.
  14948. */
  14949. /*
  14950. * Licensed to the Apache Software Foundation (ASF) under one
  14951. * or more contributor license agreements. See the NOTICE file
  14952. * distributed with this work for additional information
  14953. * regarding copyright ownership. The ASF licenses this file
  14954. * to you under the Apache License, Version 2.0 (the
  14955. * "License"); you may not use this file except in compliance
  14956. * with the License. You may obtain a copy of the License at
  14957. *
  14958. * http://www.apache.org/licenses/LICENSE-2.0
  14959. *
  14960. * Unless required by applicable law or agreed to in writing,
  14961. * software distributed under the License is distributed on an
  14962. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14963. * KIND, either express or implied. See the License for the
  14964. * specific language governing permissions and limitations
  14965. * under the License.
  14966. */
  14967. /**
  14968. * Language: English.
  14969. */
  14970. var langEN = {
  14971. time: {
  14972. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  14973. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  14974. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  14975. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  14976. },
  14977. legend: {
  14978. selector: {
  14979. all: 'All',
  14980. inverse: 'Inv'
  14981. }
  14982. },
  14983. toolbox: {
  14984. brush: {
  14985. title: {
  14986. rect: 'Box Select',
  14987. polygon: 'Lasso Select',
  14988. lineX: 'Horizontally Select',
  14989. lineY: 'Vertically Select',
  14990. keep: 'Keep Selections',
  14991. clear: 'Clear Selections'
  14992. }
  14993. },
  14994. dataView: {
  14995. title: 'Data View',
  14996. lang: ['Data View', 'Close', 'Refresh']
  14997. },
  14998. dataZoom: {
  14999. title: {
  15000. zoom: 'Zoom',
  15001. back: 'Zoom Reset'
  15002. }
  15003. },
  15004. magicType: {
  15005. title: {
  15006. line: 'Switch to Line Chart',
  15007. bar: 'Switch to Bar Chart',
  15008. stack: 'Stack',
  15009. tiled: 'Tile'
  15010. }
  15011. },
  15012. restore: {
  15013. title: 'Restore'
  15014. },
  15015. saveAsImage: {
  15016. title: 'Save as Image',
  15017. lang: ['Right Click to Save Image']
  15018. }
  15019. },
  15020. series: {
  15021. typeNames: {
  15022. pie: 'Pie chart',
  15023. bar: 'Bar chart',
  15024. line: 'Line chart',
  15025. scatter: 'Scatter plot',
  15026. effectScatter: 'Ripple scatter plot',
  15027. radar: 'Radar chart',
  15028. tree: 'Tree',
  15029. treemap: 'Treemap',
  15030. boxplot: 'Boxplot',
  15031. candlestick: 'Candlestick',
  15032. k: 'K line chart',
  15033. heatmap: 'Heat map',
  15034. map: 'Map',
  15035. parallel: 'Parallel coordinate map',
  15036. lines: 'Line graph',
  15037. graph: 'Relationship graph',
  15038. sankey: 'Sankey diagram',
  15039. funnel: 'Funnel chart',
  15040. gauge: 'Gauge',
  15041. pictorialBar: 'Pictorial bar',
  15042. themeRiver: 'Theme River Map',
  15043. sunburst: 'Sunburst'
  15044. }
  15045. },
  15046. aria: {
  15047. general: {
  15048. withTitle: 'This is a chart about "{title}"',
  15049. withoutTitle: 'This is a chart'
  15050. },
  15051. series: {
  15052. single: {
  15053. prefix: '',
  15054. withName: ' with type {seriesType} named {seriesName}.',
  15055. withoutName: ' with type {seriesType}.'
  15056. },
  15057. multiple: {
  15058. prefix: '. It consists of {seriesCount} series count.',
  15059. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15060. withoutName: ' The {seriesId} series is a {seriesType}.',
  15061. separator: {
  15062. middle: '',
  15063. end: ''
  15064. }
  15065. }
  15066. },
  15067. data: {
  15068. allData: 'The data is as follows: ',
  15069. partialData: 'The first {displayCnt} items are: ',
  15070. withName: 'the data for {name} is {value}',
  15071. withoutName: '{value}',
  15072. separator: {
  15073. middle: ', ',
  15074. end: '. '
  15075. }
  15076. }
  15077. }
  15078. };
  15079. /*
  15080. * Licensed to the Apache Software Foundation (ASF) under one
  15081. * or more contributor license agreements. See the NOTICE file
  15082. * distributed with this work for additional information
  15083. * regarding copyright ownership. The ASF licenses this file
  15084. * to you under the Apache License, Version 2.0 (the
  15085. * "License"); you may not use this file except in compliance
  15086. * with the License. You may obtain a copy of the License at
  15087. *
  15088. * http://www.apache.org/licenses/LICENSE-2.0
  15089. *
  15090. * Unless required by applicable law or agreed to in writing,
  15091. * software distributed under the License is distributed on an
  15092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15093. * KIND, either express or implied. See the License for the
  15094. * specific language governing permissions and limitations
  15095. * under the License.
  15096. */
  15097. /**
  15098. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15099. */
  15100. /*
  15101. * Licensed to the Apache Software Foundation (ASF) under one
  15102. * or more contributor license agreements. See the NOTICE file
  15103. * distributed with this work for additional information
  15104. * regarding copyright ownership. The ASF licenses this file
  15105. * to you under the Apache License, Version 2.0 (the
  15106. * "License"); you may not use this file except in compliance
  15107. * with the License. You may obtain a copy of the License at
  15108. *
  15109. * http://www.apache.org/licenses/LICENSE-2.0
  15110. *
  15111. * Unless required by applicable law or agreed to in writing,
  15112. * software distributed under the License is distributed on an
  15113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15114. * KIND, either express or implied. See the License for the
  15115. * specific language governing permissions and limitations
  15116. * under the License.
  15117. */
  15118. var langZH = {
  15119. time: {
  15120. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15121. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15122. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15123. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15124. },
  15125. legend: {
  15126. selector: {
  15127. all: '全选',
  15128. inverse: '反选'
  15129. }
  15130. },
  15131. toolbox: {
  15132. brush: {
  15133. title: {
  15134. rect: '矩形选择',
  15135. polygon: '圈选',
  15136. lineX: '横向选择',
  15137. lineY: '纵向选择',
  15138. keep: '保持选择',
  15139. clear: '清除选择'
  15140. }
  15141. },
  15142. dataView: {
  15143. title: '数据视图',
  15144. lang: ['数据视图', '关闭', '刷新']
  15145. },
  15146. dataZoom: {
  15147. title: {
  15148. zoom: '区域缩放',
  15149. back: '区域缩放还原'
  15150. }
  15151. },
  15152. magicType: {
  15153. title: {
  15154. line: '切换为折线图',
  15155. bar: '切换为柱状图',
  15156. stack: '切换为堆叠',
  15157. tiled: '切换为平铺'
  15158. }
  15159. },
  15160. restore: {
  15161. title: '还原'
  15162. },
  15163. saveAsImage: {
  15164. title: '保存为图片',
  15165. lang: ['右键另存为图片']
  15166. }
  15167. },
  15168. series: {
  15169. typeNames: {
  15170. pie: '饼图',
  15171. bar: '柱状图',
  15172. line: '折线图',
  15173. scatter: '散点图',
  15174. effectScatter: '涟漪散点图',
  15175. radar: '雷达图',
  15176. tree: '树图',
  15177. treemap: '矩形树图',
  15178. boxplot: '箱型图',
  15179. candlestick: 'K线图',
  15180. k: 'K线图',
  15181. heatmap: '热力图',
  15182. map: '地图',
  15183. parallel: '平行坐标图',
  15184. lines: '线图',
  15185. graph: '关系图',
  15186. sankey: '桑基图',
  15187. funnel: '漏斗图',
  15188. gauge: '仪表盘图',
  15189. pictorialBar: '象形柱图',
  15190. themeRiver: '主题河流图',
  15191. sunburst: '旭日图'
  15192. }
  15193. },
  15194. aria: {
  15195. general: {
  15196. withTitle: '这是一个关于“{title}”的图表。',
  15197. withoutTitle: '这是一个图表,'
  15198. },
  15199. series: {
  15200. single: {
  15201. prefix: '',
  15202. withName: '图表类型是{seriesType},表示{seriesName}。',
  15203. withoutName: '图表类型是{seriesType}。'
  15204. },
  15205. multiple: {
  15206. prefix: '它由{seriesCount}个图表系列组成。',
  15207. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15208. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15209. separator: {
  15210. middle: ';',
  15211. end: '。'
  15212. }
  15213. }
  15214. },
  15215. data: {
  15216. allData: '其数据是——',
  15217. partialData: '其中,前{displayCnt}项是——',
  15218. withName: '{name}的数据是{value}',
  15219. withoutName: '{value}',
  15220. separator: {
  15221. middle: ',',
  15222. end: ''
  15223. }
  15224. }
  15225. }
  15226. };
  15227. var LOCALE_ZH = 'ZH';
  15228. var LOCALE_EN = 'EN';
  15229. var DEFAULT_LOCALE = LOCALE_EN;
  15230. var localeStorage = {};
  15231. var localeModels = {};
  15232. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15233. var langStr = (
  15234. /* eslint-disable-next-line */
  15235. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15236. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15237. }();
  15238. function registerLocale(locale, localeObj) {
  15239. locale = locale.toUpperCase();
  15240. localeModels[locale] = new Model(localeObj);
  15241. localeStorage[locale] = localeObj;
  15242. } // export function getLocale(locale: string) {
  15243. // return localeStorage[locale];
  15244. // }
  15245. function createLocaleObject(locale) {
  15246. if (isString(locale)) {
  15247. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15248. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15249. return clone(localeObj);
  15250. } else {
  15251. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15252. }
  15253. } else {
  15254. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15255. }
  15256. }
  15257. function getLocaleModel(lang) {
  15258. return localeModels[lang];
  15259. }
  15260. function getDefaultLocaleModel() {
  15261. return localeModels[DEFAULT_LOCALE];
  15262. } // Default locale
  15263. registerLocale(LOCALE_EN, langEN);
  15264. registerLocale(LOCALE_ZH, langZH);
  15265. var ONE_SECOND = 1000;
  15266. var ONE_MINUTE = ONE_SECOND * 60;
  15267. var ONE_HOUR = ONE_MINUTE * 60;
  15268. var ONE_DAY = ONE_HOUR * 24;
  15269. var ONE_YEAR = ONE_DAY * 365;
  15270. var defaultLeveledFormatter = {
  15271. year: '{yyyy}',
  15272. month: '{MMM}',
  15273. day: '{d}',
  15274. hour: '{HH}:{mm}',
  15275. minute: '{HH}:{mm}',
  15276. second: '{HH}:{mm}:{ss}',
  15277. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15278. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15279. };
  15280. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15281. var fullLeveledFormatter = {
  15282. year: '{yyyy}',
  15283. month: '{yyyy}-{MM}',
  15284. day: fullDayFormatter,
  15285. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15286. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15287. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15288. millisecond: defaultLeveledFormatter.none
  15289. };
  15290. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15291. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15292. function pad(str, len) {
  15293. str += '';
  15294. return '0000'.substr(0, len - str.length) + str;
  15295. }
  15296. function getPrimaryTimeUnit(timeUnit) {
  15297. switch (timeUnit) {
  15298. case 'half-year':
  15299. case 'quarter':
  15300. return 'month';
  15301. case 'week':
  15302. case 'half-week':
  15303. return 'day';
  15304. case 'half-day':
  15305. case 'quarter-day':
  15306. return 'hour';
  15307. default:
  15308. // year, minutes, second, milliseconds
  15309. return timeUnit;
  15310. }
  15311. }
  15312. function isPrimaryTimeUnit(timeUnit) {
  15313. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15314. }
  15315. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15316. switch (timeUnit) {
  15317. case 'year':
  15318. case 'month':
  15319. return 'day';
  15320. case 'millisecond':
  15321. return 'millisecond';
  15322. default:
  15323. // Also for day, hour, minute, second
  15324. return 'second';
  15325. }
  15326. }
  15327. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15328. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15329. time, template, isUTC, lang) {
  15330. var date = parseDate(time);
  15331. var y = date[fullYearGetterName(isUTC)]();
  15332. var M = date[monthGetterName(isUTC)]() + 1;
  15333. var q = Math.floor((M - 1) / 3) + 1;
  15334. var d = date[dateGetterName(isUTC)]();
  15335. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15336. var H = date[hoursGetterName(isUTC)]();
  15337. var h = (H - 1) % 12 + 1;
  15338. var m = date[minutesGetterName(isUTC)]();
  15339. var s = date[secondsGetterName(isUTC)]();
  15340. var S = date[millisecondsGetterName(isUTC)]();
  15341. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15342. var timeModel = localeModel.getModel('time');
  15343. var month = timeModel.get('month');
  15344. var monthAbbr = timeModel.get('monthAbbr');
  15345. var dayOfWeek = timeModel.get('dayOfWeek');
  15346. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15347. return (template || '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, y % 100 + '').replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  15348. }
  15349. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15350. var template = null;
  15351. if (isString(formatter)) {
  15352. // Single formatter for all units at all levels
  15353. template = formatter;
  15354. } else if (isFunction(formatter)) {
  15355. // Callback formatter
  15356. template = formatter(tick.value, idx, {
  15357. level: tick.level
  15358. });
  15359. } else {
  15360. var defaults$1 = extend({}, defaultLeveledFormatter);
  15361. if (tick.level > 0) {
  15362. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15363. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15364. }
  15365. }
  15366. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15367. : defaults(formatter, defaults$1) : defaults$1;
  15368. var unit = getUnitFromValue(tick.value, isUTC);
  15369. if (mergedFormatter[unit]) {
  15370. template = mergedFormatter[unit];
  15371. } else if (mergedFormatter.inherit) {
  15372. // Unit formatter is not defined and should inherit from bigger units
  15373. var targetId = timeUnits.indexOf(unit);
  15374. for (var i = targetId - 1; i >= 0; --i) {
  15375. if (mergedFormatter[unit]) {
  15376. template = mergedFormatter[unit];
  15377. break;
  15378. }
  15379. }
  15380. template = template || defaults$1.none;
  15381. }
  15382. if (isArray(template)) {
  15383. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15384. levelId = Math.min(levelId, template.length - 1);
  15385. template = template[levelId];
  15386. }
  15387. }
  15388. return format(new Date(tick.value), template, isUTC, lang);
  15389. }
  15390. function getUnitFromValue(value, isUTC) {
  15391. var date = parseDate(value);
  15392. var M = date[monthGetterName(isUTC)]() + 1;
  15393. var d = date[dateGetterName(isUTC)]();
  15394. var h = date[hoursGetterName(isUTC)]();
  15395. var m = date[minutesGetterName(isUTC)]();
  15396. var s = date[secondsGetterName(isUTC)]();
  15397. var S = date[millisecondsGetterName(isUTC)]();
  15398. var isSecond = S === 0;
  15399. var isMinute = isSecond && s === 0;
  15400. var isHour = isMinute && m === 0;
  15401. var isDay = isHour && h === 0;
  15402. var isMonth = isDay && d === 1;
  15403. var isYear = isMonth && M === 1;
  15404. if (isYear) {
  15405. return 'year';
  15406. } else if (isMonth) {
  15407. return 'month';
  15408. } else if (isDay) {
  15409. return 'day';
  15410. } else if (isHour) {
  15411. return 'hour';
  15412. } else if (isMinute) {
  15413. return 'minute';
  15414. } else if (isSecond) {
  15415. return 'second';
  15416. } else {
  15417. return 'millisecond';
  15418. }
  15419. }
  15420. function getUnitValue(value, unit, isUTC) {
  15421. var date = isNumber(value) ? parseDate(value) : value;
  15422. unit = unit || getUnitFromValue(value, isUTC);
  15423. switch (unit) {
  15424. case 'year':
  15425. return date[fullYearGetterName(isUTC)]();
  15426. case 'half-year':
  15427. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15428. case 'quarter':
  15429. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15430. case 'month':
  15431. return date[monthGetterName(isUTC)]();
  15432. case 'day':
  15433. return date[dateGetterName(isUTC)]();
  15434. case 'half-day':
  15435. return date[hoursGetterName(isUTC)]() / 24;
  15436. case 'hour':
  15437. return date[hoursGetterName(isUTC)]();
  15438. case 'minute':
  15439. return date[minutesGetterName(isUTC)]();
  15440. case 'second':
  15441. return date[secondsGetterName(isUTC)]();
  15442. case 'millisecond':
  15443. return date[millisecondsGetterName(isUTC)]();
  15444. }
  15445. }
  15446. function fullYearGetterName(isUTC) {
  15447. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15448. }
  15449. function monthGetterName(isUTC) {
  15450. return isUTC ? 'getUTCMonth' : 'getMonth';
  15451. }
  15452. function dateGetterName(isUTC) {
  15453. return isUTC ? 'getUTCDate' : 'getDate';
  15454. }
  15455. function hoursGetterName(isUTC) {
  15456. return isUTC ? 'getUTCHours' : 'getHours';
  15457. }
  15458. function minutesGetterName(isUTC) {
  15459. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15460. }
  15461. function secondsGetterName(isUTC) {
  15462. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15463. }
  15464. function millisecondsGetterName(isUTC) {
  15465. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  15466. }
  15467. function fullYearSetterName(isUTC) {
  15468. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15469. }
  15470. function monthSetterName(isUTC) {
  15471. return isUTC ? 'setUTCMonth' : 'setMonth';
  15472. }
  15473. function dateSetterName(isUTC) {
  15474. return isUTC ? 'setUTCDate' : 'setDate';
  15475. }
  15476. function hoursSetterName(isUTC) {
  15477. return isUTC ? 'setUTCHours' : 'setHours';
  15478. }
  15479. function minutesSetterName(isUTC) {
  15480. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15481. }
  15482. function secondsSetterName(isUTC) {
  15483. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15484. }
  15485. function millisecondsSetterName(isUTC) {
  15486. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  15487. }
  15488. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15489. var textEl = new ZRText({
  15490. style: {
  15491. text: text,
  15492. font: font,
  15493. align: align,
  15494. verticalAlign: verticalAlign,
  15495. padding: padding,
  15496. rich: rich,
  15497. overflow: truncate ? 'truncate' : null,
  15498. lineHeight: lineHeight
  15499. }
  15500. });
  15501. return textEl.getBoundingRect();
  15502. }
  15503. /**
  15504. * Add a comma each three digit.
  15505. */
  15506. function addCommas(x) {
  15507. if (!isNumeric(x)) {
  15508. return isString(x) ? x : '-';
  15509. }
  15510. var parts = (x + '').split('.');
  15511. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15512. }
  15513. function toCamelCase(str, upperCaseFirst) {
  15514. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15515. return group1.toUpperCase();
  15516. });
  15517. if (upperCaseFirst && str) {
  15518. str = str.charAt(0).toUpperCase() + str.slice(1);
  15519. }
  15520. return str;
  15521. }
  15522. var normalizeCssArray$1 = normalizeCssArray;
  15523. var replaceReg = /([&<>"'])/g;
  15524. var replaceMap = {
  15525. '&': '&amp;',
  15526. '<': '&lt;',
  15527. '>': '&gt;',
  15528. '"': '&quot;',
  15529. '\'': '&#39;'
  15530. };
  15531. function encodeHTML(source) {
  15532. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  15533. return replaceMap[c];
  15534. });
  15535. }
  15536. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15537. var wrapVar = function (varName, seriesIdx) {
  15538. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15539. };
  15540. /**
  15541. * Template formatter
  15542. * @param {Array.<Object>|Object} paramsList
  15543. */
  15544. function formatTpl(tpl, paramsList, encode) {
  15545. if (!isArray(paramsList)) {
  15546. paramsList = [paramsList];
  15547. }
  15548. var seriesLen = paramsList.length;
  15549. if (!seriesLen) {
  15550. return '';
  15551. }
  15552. var $vars = paramsList[0].$vars || [];
  15553. for (var i = 0; i < $vars.length; i++) {
  15554. var alias = TPL_VAR_ALIAS[i];
  15555. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15556. }
  15557. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15558. for (var k = 0; k < $vars.length; k++) {
  15559. var val = paramsList[seriesIdx][$vars[k]];
  15560. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  15561. }
  15562. }
  15563. return tpl;
  15564. }
  15565. function getTooltipMarker(inOpt, extraCssText) {
  15566. var opt = isString(inOpt) ? {
  15567. color: inOpt,
  15568. extraCssText: extraCssText
  15569. } : inOpt || {};
  15570. var color = opt.color;
  15571. var type = opt.type;
  15572. extraCssText = opt.extraCssText;
  15573. var renderMode = opt.renderMode || 'html';
  15574. if (!color) {
  15575. return '';
  15576. }
  15577. if (renderMode === 'html') {
  15578. return type === 'subItem' ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;' + 'border-radius:4px;width:4px;height:4px;background-color:' // Only support string
  15579. + 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>';
  15580. } else {
  15581. // Should better not to auto generate style name by auto-increment number here.
  15582. // Because this util is usually called in tooltip formatter, which is probably
  15583. // called repeatly when mouse move and the auto-increment number increases fast.
  15584. // Users can make their own style name by theirselves, make it unique and readable.
  15585. var markerId = opt.markerId || 'markerX';
  15586. return {
  15587. renderMode: renderMode,
  15588. content: '{' + markerId + '|} ',
  15589. style: type === 'subItem' ? {
  15590. width: 4,
  15591. height: 4,
  15592. borderRadius: 2,
  15593. backgroundColor: color
  15594. } : {
  15595. width: 10,
  15596. height: 10,
  15597. borderRadius: 5,
  15598. backgroundColor: color
  15599. }
  15600. };
  15601. }
  15602. }
  15603. /**
  15604. * @deprecated Use `time/format` instead.
  15605. * ISO Date format
  15606. * @param {string} tpl
  15607. * @param {number} value
  15608. * @param {boolean} [isUTC=false] Default in local time.
  15609. * see `module:echarts/scale/Time`
  15610. * and `module:echarts/util/number#parseDate`.
  15611. * @inner
  15612. */
  15613. function formatTime(tpl, value, isUTC) {
  15614. if ("development" !== 'production') {
  15615. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  15616. }
  15617. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  15618. tpl = 'MM-dd\nyyyy';
  15619. }
  15620. var date = parseDate(value);
  15621. var getUTC = isUTC ? 'getUTC' : 'get';
  15622. var y = date[getUTC + 'FullYear']();
  15623. var M = date[getUTC + 'Month']() + 1;
  15624. var d = date[getUTC + 'Date']();
  15625. var h = date[getUTC + 'Hours']();
  15626. var m = date[getUTC + 'Minutes']();
  15627. var s = date[getUTC + 'Seconds']();
  15628. var S = date[getUTC + 'Milliseconds']();
  15629. 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));
  15630. return tpl;
  15631. }
  15632. /**
  15633. * Capital first
  15634. * @param {string} str
  15635. * @return {string}
  15636. */
  15637. function capitalFirst(str) {
  15638. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15639. }
  15640. /**
  15641. * @return Never be null/undefined.
  15642. */
  15643. function convertToColorString(color, defaultColor) {
  15644. defaultColor = defaultColor || 'transparent';
  15645. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  15646. }
  15647. var each$1 = each;
  15648. /**
  15649. * @public
  15650. */
  15651. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  15652. /**
  15653. * @public
  15654. */
  15655. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  15656. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15657. var x = 0;
  15658. var y = 0;
  15659. if (maxWidth == null) {
  15660. maxWidth = Infinity;
  15661. }
  15662. if (maxHeight == null) {
  15663. maxHeight = Infinity;
  15664. }
  15665. var currentLineMaxSize = 0;
  15666. group.eachChild(function (child, idx) {
  15667. var rect = child.getBoundingRect();
  15668. var nextChild = group.childAt(idx + 1);
  15669. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15670. var nextX;
  15671. var nextY;
  15672. if (orient === 'horizontal') {
  15673. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  15674. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  15675. // FIXME compare before adding gap?
  15676. if (nextX > maxWidth || child.newline) {
  15677. x = 0;
  15678. nextX = moveX;
  15679. y += currentLineMaxSize + gap;
  15680. currentLineMaxSize = rect.height;
  15681. } else {
  15682. // FIXME: consider rect.y is not `0`?
  15683. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15684. }
  15685. } else {
  15686. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  15687. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  15688. if (nextY > maxHeight || child.newline) {
  15689. x += currentLineMaxSize + gap;
  15690. y = 0;
  15691. nextY = moveY;
  15692. currentLineMaxSize = rect.width;
  15693. } else {
  15694. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15695. }
  15696. }
  15697. if (child.newline) {
  15698. return;
  15699. }
  15700. child.x = x;
  15701. child.y = y;
  15702. child.markRedraw();
  15703. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  15704. });
  15705. }
  15706. /**
  15707. * VBox layouting
  15708. * @param {module:zrender/graphic/Group} group
  15709. * @param {number} gap
  15710. * @param {number} [width=Infinity]
  15711. * @param {number} [height=Infinity]
  15712. */
  15713. var vbox = curry(boxLayout, 'vertical');
  15714. /**
  15715. * HBox layouting
  15716. * @param {module:zrender/graphic/Group} group
  15717. * @param {number} gap
  15718. * @param {number} [width=Infinity]
  15719. * @param {number} [height=Infinity]
  15720. */
  15721. var hbox = curry(boxLayout, 'horizontal');
  15722. /**
  15723. * Parse position info.
  15724. */
  15725. function getLayoutRect(positionInfo, containerRect, margin) {
  15726. margin = normalizeCssArray$1(margin || 0);
  15727. var containerWidth = containerRect.width;
  15728. var containerHeight = containerRect.height;
  15729. var left = parsePercent$1(positionInfo.left, containerWidth);
  15730. var top = parsePercent$1(positionInfo.top, containerHeight);
  15731. var right = parsePercent$1(positionInfo.right, containerWidth);
  15732. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15733. var width = parsePercent$1(positionInfo.width, containerWidth);
  15734. var height = parsePercent$1(positionInfo.height, containerHeight);
  15735. var verticalMargin = margin[2] + margin[0];
  15736. var horizontalMargin = margin[1] + margin[3];
  15737. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  15738. if (isNaN(width)) {
  15739. width = containerWidth - right - horizontalMargin - left;
  15740. }
  15741. if (isNaN(height)) {
  15742. height = containerHeight - bottom - verticalMargin - top;
  15743. }
  15744. if (aspect != null) {
  15745. // If width and height are not given
  15746. // 1. Graph should not exceeds the container
  15747. // 2. Aspect must be keeped
  15748. // 3. Graph should take the space as more as possible
  15749. // FIXME
  15750. // Margin is not considered, because there is no case that both
  15751. // using margin and aspect so far.
  15752. if (isNaN(width) && isNaN(height)) {
  15753. if (aspect > containerWidth / containerHeight) {
  15754. width = containerWidth * 0.8;
  15755. } else {
  15756. height = containerHeight * 0.8;
  15757. }
  15758. } // Calculate width or height with given aspect
  15759. if (isNaN(width)) {
  15760. width = aspect * height;
  15761. }
  15762. if (isNaN(height)) {
  15763. height = width / aspect;
  15764. }
  15765. } // If left is not specified, calculate left from right and width
  15766. if (isNaN(left)) {
  15767. left = containerWidth - right - width - horizontalMargin;
  15768. }
  15769. if (isNaN(top)) {
  15770. top = containerHeight - bottom - height - verticalMargin;
  15771. } // Align left and top
  15772. switch (positionInfo.left || positionInfo.right) {
  15773. case 'center':
  15774. left = containerWidth / 2 - width / 2 - margin[3];
  15775. break;
  15776. case 'right':
  15777. left = containerWidth - width - horizontalMargin;
  15778. break;
  15779. }
  15780. switch (positionInfo.top || positionInfo.bottom) {
  15781. case 'middle':
  15782. case 'center':
  15783. top = containerHeight / 2 - height / 2 - margin[0];
  15784. break;
  15785. case 'bottom':
  15786. top = containerHeight - height - verticalMargin;
  15787. break;
  15788. } // If something is wrong and left, top, width, height are calculated as NaN
  15789. left = left || 0;
  15790. top = top || 0;
  15791. if (isNaN(width)) {
  15792. // Width may be NaN if only one value is given except width
  15793. width = containerWidth - horizontalMargin - left - (right || 0);
  15794. }
  15795. if (isNaN(height)) {
  15796. // Height may be NaN if only one value is given except height
  15797. height = containerHeight - verticalMargin - top - (bottom || 0);
  15798. }
  15799. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15800. rect.margin = margin;
  15801. return rect;
  15802. }
  15803. function fetchLayoutMode(ins) {
  15804. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  15805. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  15806. type: layoutMode
  15807. } : null;
  15808. }
  15809. /**
  15810. * Consider Case:
  15811. * When default option has {left: 0, width: 100}, and we set {right: 0}
  15812. * through setOption or media query, using normal zrUtil.merge will cause
  15813. * {right: 0} does not take effect.
  15814. *
  15815. * @example
  15816. * ComponentModel.extend({
  15817. * init: function () {
  15818. * ...
  15819. * let inputPositionParams = layout.getLayoutParams(option);
  15820. * this.mergeOption(inputPositionParams);
  15821. * },
  15822. * mergeOption: function (newOption) {
  15823. * newOption && zrUtil.merge(thisOption, newOption, true);
  15824. * layout.mergeLayoutParam(thisOption, newOption);
  15825. * }
  15826. * });
  15827. *
  15828. * @param targetOption
  15829. * @param newOption
  15830. * @param opt
  15831. */
  15832. function mergeLayoutParam(targetOption, newOption, opt) {
  15833. var ignoreSize = opt && opt.ignoreSize;
  15834. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15835. var hResult = merge(HV_NAMES[0], 0);
  15836. var vResult = merge(HV_NAMES[1], 1);
  15837. copy(HV_NAMES[0], targetOption, hResult);
  15838. copy(HV_NAMES[1], targetOption, vResult);
  15839. function merge(names, hvIdx) {
  15840. var newParams = {};
  15841. var newValueCount = 0;
  15842. var merged = {};
  15843. var mergedValueCount = 0;
  15844. var enoughParamNumber = 2;
  15845. each$1(names, function (name) {
  15846. merged[name] = targetOption[name];
  15847. });
  15848. each$1(names, function (name) {
  15849. // Consider case: newOption.width is null, which is
  15850. // set by user for removing width setting.
  15851. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15852. hasValue(newParams, name) && newValueCount++;
  15853. hasValue(merged, name) && mergedValueCount++;
  15854. });
  15855. if (ignoreSize[hvIdx]) {
  15856. // Only one of left/right is premitted to exist.
  15857. if (hasValue(newOption, names[1])) {
  15858. merged[names[2]] = null;
  15859. } else if (hasValue(newOption, names[2])) {
  15860. merged[names[1]] = null;
  15861. }
  15862. return merged;
  15863. } // Case: newOption: {width: ..., right: ...},
  15864. // or targetOption: {right: ...} and newOption: {width: ...},
  15865. // There is no conflict when merged only has params count
  15866. // little than enoughParamNumber.
  15867. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15868. return merged;
  15869. } // Case: newOption: {width: ..., right: ...},
  15870. // Than we can make sure user only want those two, and ignore
  15871. // all origin params in targetOption.
  15872. else if (newValueCount >= enoughParamNumber) {
  15873. return newParams;
  15874. } else {
  15875. // Chose another param from targetOption by priority.
  15876. for (var i = 0; i < names.length; i++) {
  15877. var name_1 = names[i];
  15878. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  15879. newParams[name_1] = targetOption[name_1];
  15880. break;
  15881. }
  15882. }
  15883. return newParams;
  15884. }
  15885. }
  15886. function hasProp(obj, name) {
  15887. return obj.hasOwnProperty(name);
  15888. }
  15889. function hasValue(obj, name) {
  15890. return obj[name] != null && obj[name] !== 'auto';
  15891. }
  15892. function copy(names, target, source) {
  15893. each$1(names, function (name) {
  15894. target[name] = source[name];
  15895. });
  15896. }
  15897. }
  15898. /**
  15899. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15900. */
  15901. function getLayoutParams(source) {
  15902. return copyLayoutParams({}, source);
  15903. }
  15904. /**
  15905. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15906. * @param {Object} source
  15907. * @return {Object} Result contains those props.
  15908. */
  15909. function copyLayoutParams(target, source) {
  15910. source && target && each$1(LOCATION_PARAMS, function (name) {
  15911. source.hasOwnProperty(name) && (target[name] = source[name]);
  15912. });
  15913. return target;
  15914. }
  15915. var inner = makeInner();
  15916. var ComponentModel =
  15917. /** @class */
  15918. function (_super) {
  15919. __extends(ComponentModel, _super);
  15920. function ComponentModel(option, parentModel, ecModel) {
  15921. var _this = _super.call(this, option, parentModel, ecModel) || this;
  15922. _this.uid = getUID('ec_cpt_model');
  15923. return _this;
  15924. }
  15925. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  15926. this.mergeDefaultAndTheme(option, ecModel);
  15927. };
  15928. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  15929. var layoutMode = fetchLayoutMode(this);
  15930. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  15931. var themeModel = ecModel.getTheme();
  15932. merge(option, themeModel.get(this.mainType));
  15933. merge(option, this.getDefaultOption());
  15934. if (layoutMode) {
  15935. mergeLayoutParam(option, inputPositionParams, layoutMode);
  15936. }
  15937. };
  15938. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  15939. merge(this.option, option, true);
  15940. var layoutMode = fetchLayoutMode(this);
  15941. if (layoutMode) {
  15942. mergeLayoutParam(this.option, option, layoutMode);
  15943. }
  15944. };
  15945. /**
  15946. * Called immediately after `init` or `mergeOption` of this instance called.
  15947. */
  15948. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  15949. /**
  15950. * [How to declare defaultOption]:
  15951. *
  15952. * (A) If using class declaration in typescript (since echarts 5):
  15953. * ```ts
  15954. * import {ComponentOption} from '../model/option.js';
  15955. * export interface XxxOption extends ComponentOption {
  15956. * aaa: number
  15957. * }
  15958. * export class XxxModel extends Component {
  15959. * static type = 'xxx';
  15960. * static defaultOption: XxxOption = {
  15961. * aaa: 123
  15962. * }
  15963. * }
  15964. * Component.registerClass(XxxModel);
  15965. * ```
  15966. * ```ts
  15967. * import {inheritDefaultOption} from '../util/component.js';
  15968. * import {XxxModel, XxxOption} from './XxxModel.js';
  15969. * export interface XxxSubOption extends XxxOption {
  15970. * bbb: number
  15971. * }
  15972. * class XxxSubModel extends XxxModel {
  15973. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  15974. * bbb: 456
  15975. * })
  15976. * fn() {
  15977. * let opt = this.getDefaultOption();
  15978. * // opt is {aaa: 123, bbb: 456}
  15979. * }
  15980. * }
  15981. * ```
  15982. *
  15983. * (B) If using class extend (previous approach in echarts 3 & 4):
  15984. * ```js
  15985. * let XxxComponent = Component.extend({
  15986. * defaultOption: {
  15987. * xx: 123
  15988. * }
  15989. * })
  15990. * ```
  15991. * ```js
  15992. * let XxxSubComponent = XxxComponent.extend({
  15993. * defaultOption: {
  15994. * yy: 456
  15995. * },
  15996. * fn: function () {
  15997. * let opt = this.getDefaultOption();
  15998. * // opt is {xx: 123, yy: 456}
  15999. * }
  16000. * })
  16001. * ```
  16002. */
  16003. ComponentModel.prototype.getDefaultOption = function () {
  16004. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16005. // in legacy env and auto merge defaultOption. So if using class
  16006. // declaration, defaultOption should be merged manually.
  16007. if (!isExtendedClass(ctor)) {
  16008. // When using ts class, defaultOption must be declared as static.
  16009. return ctor.defaultOption;
  16010. } // FIXME: remove this approach?
  16011. var fields = inner(this);
  16012. if (!fields.defaultOption) {
  16013. var optList = [];
  16014. var clz = ctor;
  16015. while (clz) {
  16016. var opt = clz.prototype.defaultOption;
  16017. opt && optList.push(opt);
  16018. clz = clz.superClass;
  16019. }
  16020. var defaultOption = {};
  16021. for (var i = optList.length - 1; i >= 0; i--) {
  16022. defaultOption = merge(defaultOption, optList[i], true);
  16023. }
  16024. fields.defaultOption = defaultOption;
  16025. }
  16026. return fields.defaultOption;
  16027. };
  16028. /**
  16029. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16030. * The same behavior as `modelUtil.parseFinder`.
  16031. *
  16032. * @param useDefault In many cases like series refer axis and axis refer grid,
  16033. * If axis index / axis id not specified, use the first target as default.
  16034. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16035. */
  16036. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16037. var indexKey = mainType + 'Index';
  16038. var idKey = mainType + 'Id';
  16039. return queryReferringComponents(this.ecModel, mainType, {
  16040. index: this.get(indexKey, true),
  16041. id: this.get(idKey, true)
  16042. }, opt);
  16043. };
  16044. ComponentModel.prototype.getBoxLayoutParams = function () {
  16045. // Consider itself having box layout configs.
  16046. var boxLayoutModel = this;
  16047. return {
  16048. left: boxLayoutModel.get('left'),
  16049. top: boxLayoutModel.get('top'),
  16050. right: boxLayoutModel.get('right'),
  16051. bottom: boxLayoutModel.get('bottom'),
  16052. width: boxLayoutModel.get('width'),
  16053. height: boxLayoutModel.get('height')
  16054. };
  16055. };
  16056. /**
  16057. * Get key for zlevel.
  16058. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16059. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16060. */
  16061. ComponentModel.prototype.getZLevelKey = function () {
  16062. return '';
  16063. };
  16064. ComponentModel.prototype.setZLevel = function (zlevel) {
  16065. this.option.zlevel = zlevel;
  16066. };
  16067. ComponentModel.protoInitialize = function () {
  16068. var proto = ComponentModel.prototype;
  16069. proto.type = 'component';
  16070. proto.id = '';
  16071. proto.name = '';
  16072. proto.mainType = '';
  16073. proto.subType = '';
  16074. proto.componentIndex = 0;
  16075. }();
  16076. return ComponentModel;
  16077. }(Model);
  16078. mountExtend(ComponentModel, Model);
  16079. enableClassManagement(ComponentModel);
  16080. enableSubTypeDefaulter(ComponentModel);
  16081. enableTopologicalTravel(ComponentModel, getDependencies);
  16082. function getDependencies(componentType) {
  16083. var deps = [];
  16084. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16085. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16086. }); // Ensure main type.
  16087. deps = map(deps, function (type) {
  16088. return parseClassType(type).main;
  16089. }); // Hack dataset for convenience.
  16090. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16091. deps.unshift('dataset');
  16092. }
  16093. return deps;
  16094. }
  16095. /*
  16096. * Licensed to the Apache Software Foundation (ASF) under one
  16097. * or more contributor license agreements. See the NOTICE file
  16098. * distributed with this work for additional information
  16099. * regarding copyright ownership. The ASF licenses this file
  16100. * to you under the Apache License, Version 2.0 (the
  16101. * "License"); you may not use this file except in compliance
  16102. * with the License. You may obtain a copy of the License at
  16103. *
  16104. * http://www.apache.org/licenses/LICENSE-2.0
  16105. *
  16106. * Unless required by applicable law or agreed to in writing,
  16107. * software distributed under the License is distributed on an
  16108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16109. * KIND, either express or implied. See the License for the
  16110. * specific language governing permissions and limitations
  16111. * under the License.
  16112. */
  16113. /**
  16114. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16115. */
  16116. /*
  16117. * Licensed to the Apache Software Foundation (ASF) under one
  16118. * or more contributor license agreements. See the NOTICE file
  16119. * distributed with this work for additional information
  16120. * regarding copyright ownership. The ASF licenses this file
  16121. * to you under the Apache License, Version 2.0 (the
  16122. * "License"); you may not use this file except in compliance
  16123. * with the License. You may obtain a copy of the License at
  16124. *
  16125. * http://www.apache.org/licenses/LICENSE-2.0
  16126. *
  16127. * Unless required by applicable law or agreed to in writing,
  16128. * software distributed under the License is distributed on an
  16129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16130. * KIND, either express or implied. See the License for the
  16131. * specific language governing permissions and limitations
  16132. * under the License.
  16133. */
  16134. var platform = ''; // Navigator not exists in node
  16135. if (typeof navigator !== 'undefined') {
  16136. /* global navigator */
  16137. platform = navigator.platform || '';
  16138. }
  16139. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16140. var globalDefault = {
  16141. darkMode: 'auto',
  16142. // backgroundColor: 'rgba(0,0,0,0)',
  16143. colorBy: 'series',
  16144. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16145. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16146. aria: {
  16147. decal: {
  16148. decals: [{
  16149. color: decalColor,
  16150. dashArrayX: [1, 0],
  16151. dashArrayY: [2, 5],
  16152. symbolSize: 1,
  16153. rotation: Math.PI / 6
  16154. }, {
  16155. color: decalColor,
  16156. symbol: 'circle',
  16157. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16158. dashArrayY: [6, 0],
  16159. symbolSize: 0.8
  16160. }, {
  16161. color: decalColor,
  16162. dashArrayX: [1, 0],
  16163. dashArrayY: [4, 3],
  16164. rotation: -Math.PI / 4
  16165. }, {
  16166. color: decalColor,
  16167. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16168. dashArrayY: [6, 0]
  16169. }, {
  16170. color: decalColor,
  16171. dashArrayX: [[1, 0], [1, 6]],
  16172. dashArrayY: [1, 0, 6, 0],
  16173. rotation: Math.PI / 4
  16174. }, {
  16175. color: decalColor,
  16176. symbol: 'triangle',
  16177. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16178. dashArrayY: [7, 2],
  16179. symbolSize: 0.75
  16180. }]
  16181. }
  16182. },
  16183. // If xAxis and yAxis declared, grid is created by default.
  16184. // grid: {},
  16185. textStyle: {
  16186. // color: '#000',
  16187. // decoration: 'none',
  16188. // PENDING
  16189. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16190. // fontFamily: 'Arial, Verdana, sans-serif',
  16191. fontSize: 12,
  16192. fontStyle: 'normal',
  16193. fontWeight: 'normal'
  16194. },
  16195. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16196. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16197. // Default is source-over
  16198. blendMode: null,
  16199. stateAnimation: {
  16200. duration: 300,
  16201. easing: 'cubicOut'
  16202. },
  16203. animation: 'auto',
  16204. animationDuration: 1000,
  16205. animationDurationUpdate: 500,
  16206. animationEasing: 'cubicInOut',
  16207. animationEasingUpdate: 'cubicInOut',
  16208. animationThreshold: 2000,
  16209. // Configuration for progressive/incremental rendering
  16210. progressiveThreshold: 3000,
  16211. progressive: 400,
  16212. // Threshold of if use single hover layer to optimize.
  16213. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16214. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16215. // which is unexpected.
  16216. // see example <echarts/test/heatmap-large.html>.
  16217. hoverLayerThreshold: 3000,
  16218. // See: module:echarts/scale/Time
  16219. useUTC: false
  16220. };
  16221. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'seriesName']);
  16222. var SOURCE_FORMAT_ORIGINAL = 'original';
  16223. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16224. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16225. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16226. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16227. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16228. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16229. var SERIES_LAYOUT_BY_ROW = 'row';
  16230. var BE_ORDINAL = {
  16231. Must: 1,
  16232. Might: 2,
  16233. Not: 3 // Other cases
  16234. };
  16235. var innerGlobalModel = makeInner();
  16236. /**
  16237. * MUST be called before mergeOption of all series.
  16238. */
  16239. function resetSourceDefaulter(ecModel) {
  16240. // `datasetMap` is used to make default encode.
  16241. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16242. }
  16243. /**
  16244. * [The strategy of the arrengment of data dimensions for dataset]:
  16245. * "value way": all axes are non-category axes. So series one by one take
  16246. * several (the number is coordSysDims.length) dimensions from dataset.
  16247. * The result of data arrengment of data dimensions like:
  16248. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16249. * "category way": at least one axis is category axis. So the the first data
  16250. * dimension is always mapped to the first category axis and shared by
  16251. * all of the series. The other data dimensions are taken by series like
  16252. * "value way" does.
  16253. * The result of data arrengment of data dimensions like:
  16254. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16255. *
  16256. * @return encode Never be `null/undefined`.
  16257. */
  16258. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16259. var encode = {};
  16260. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16261. if (!datasetModel || !coordDimensions) {
  16262. return encode;
  16263. }
  16264. var encodeItemName = [];
  16265. var encodeSeriesName = [];
  16266. var ecModel = seriesModel.ecModel;
  16267. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16268. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16269. var baseCategoryDimIndex;
  16270. var categoryWayValueDimStart;
  16271. coordDimensions = coordDimensions.slice();
  16272. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16273. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16274. name: coordDimInfoLoose
  16275. };
  16276. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16277. baseCategoryDimIndex = coordDimIdx;
  16278. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16279. }
  16280. encode[coordDimInfo.name] = [];
  16281. });
  16282. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16283. categoryWayDim: categoryWayValueDimStart,
  16284. valueWayDim: 0
  16285. }); // TODO
  16286. // Auto detect first time axis and do arrangement.
  16287. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16288. var coordDimName = coordDimInfo.name;
  16289. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  16290. if (baseCategoryDimIndex == null) {
  16291. var start = datasetRecord.valueWayDim;
  16292. pushDim(encode[coordDimName], start, count);
  16293. pushDim(encodeSeriesName, start, count);
  16294. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  16295. // especially when encode x y specified.
  16296. // consider: when mutiple series share one dimension
  16297. // category axis, series name should better use
  16298. // the other dimsion name. On the other hand, use
  16299. // both dimensions name.
  16300. } // In category way, the first category axis.
  16301. else if (baseCategoryDimIndex === coordDimIdx) {
  16302. pushDim(encode[coordDimName], 0, count);
  16303. pushDim(encodeItemName, 0, count);
  16304. } // In category way, the other axis.
  16305. else {
  16306. var start = datasetRecord.categoryWayDim;
  16307. pushDim(encode[coordDimName], start, count);
  16308. pushDim(encodeSeriesName, start, count);
  16309. datasetRecord.categoryWayDim += count;
  16310. }
  16311. });
  16312. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16313. for (var i = 0; i < idxCount; i++) {
  16314. dimIdxArr.push(idxFrom + i);
  16315. }
  16316. }
  16317. function getDataDimCountOnCoordDim(coordDimInfo) {
  16318. var dimsDef = coordDimInfo.dimsDef;
  16319. return dimsDef ? dimsDef.length : 1;
  16320. }
  16321. encodeItemName.length && (encode.itemName = encodeItemName);
  16322. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16323. return encode;
  16324. }
  16325. /**
  16326. * Work for data like [{name: ..., value: ...}, ...].
  16327. *
  16328. * @return encode Never be `null/undefined`.
  16329. */
  16330. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16331. var encode = {};
  16332. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16333. if (!datasetModel) {
  16334. return encode;
  16335. }
  16336. var sourceFormat = source.sourceFormat;
  16337. var dimensionsDefine = source.dimensionsDefine;
  16338. var potentialNameDimIndex;
  16339. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16340. each(dimensionsDefine, function (dim, idx) {
  16341. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16342. potentialNameDimIndex = idx;
  16343. }
  16344. });
  16345. }
  16346. var idxResult = function () {
  16347. var idxRes0 = {};
  16348. var idxRes1 = {};
  16349. var guessRecords = []; // 5 is an experience value.
  16350. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16351. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16352. guessRecords.push(guessResult);
  16353. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16354. // and then find a name dim with the priority:
  16355. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16356. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16357. idxRes0.v = i;
  16358. }
  16359. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16360. idxRes0.n = i;
  16361. }
  16362. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16363. return idxRes0;
  16364. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16365. // find the first BE_ORDINAL.Might as the value dim,
  16366. // and then find a name dim with the priority:
  16367. // "other dim" > "the value dim itself".
  16368. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16369. // treated as number.
  16370. if (!isPureNumber) {
  16371. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16372. idxRes1.v = i;
  16373. }
  16374. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16375. idxRes1.n = i;
  16376. }
  16377. }
  16378. }
  16379. function fulfilled(idxResult) {
  16380. return idxResult.v != null && idxResult.n != null;
  16381. }
  16382. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16383. }();
  16384. if (idxResult) {
  16385. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  16386. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  16387. // So we dont set encodeLabel here.
  16388. encode.itemName = [nameDimIndex];
  16389. encode.seriesName = [nameDimIndex];
  16390. }
  16391. return encode;
  16392. }
  16393. /**
  16394. * @return If return null/undefined, indicate that should not use datasetModel.
  16395. */
  16396. function querySeriesUpstreamDatasetModel(seriesModel) {
  16397. // Caution: consider the scenario:
  16398. // A dataset is declared and a series is not expected to use the dataset,
  16399. // and at the beginning `setOption({series: { noData })` (just prepare other
  16400. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16401. // the user should set an empty array to avoid that dataset is used by default.
  16402. var thisData = seriesModel.get('data', true);
  16403. if (!thisData) {
  16404. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16405. index: seriesModel.get('datasetIndex', true),
  16406. id: seriesModel.get('datasetId', true)
  16407. }, SINGLE_REFERRING).models[0];
  16408. }
  16409. }
  16410. /**
  16411. * @return Always return an array event empty.
  16412. */
  16413. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16414. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  16415. // Otherwise, no reference.
  16416. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16417. return [];
  16418. }
  16419. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16420. index: datasetModel.get('fromDatasetIndex', true),
  16421. id: datasetModel.get('fromDatasetId', true)
  16422. }, SINGLE_REFERRING).models;
  16423. }
  16424. /**
  16425. * The rule should not be complex, otherwise user might not
  16426. * be able to known where the data is wrong.
  16427. * The code is ugly, but how to make it neat?
  16428. */
  16429. function guessOrdinal(source, dimIndex) {
  16430. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  16431. } // dimIndex may be overflow source data.
  16432. // return {BE_ORDINAL}
  16433. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  16434. var result; // Experience value.
  16435. var maxLoop = 5;
  16436. if (isTypedArray(data)) {
  16437. return BE_ORDINAL.Not;
  16438. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16439. // always exists in source.
  16440. var dimName;
  16441. var dimType;
  16442. if (dimensionsDefine) {
  16443. var dimDefItem = dimensionsDefine[dimIndex];
  16444. if (isObject(dimDefItem)) {
  16445. dimName = dimDefItem.name;
  16446. dimType = dimDefItem.type;
  16447. } else if (isString(dimDefItem)) {
  16448. dimName = dimDefItem;
  16449. }
  16450. }
  16451. if (dimType != null) {
  16452. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  16453. }
  16454. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16455. var dataArrayRows = data;
  16456. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16457. var sample = dataArrayRows[dimIndex];
  16458. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16459. if ((result = detectValue(sample[startIndex + i])) != null) {
  16460. return result;
  16461. }
  16462. }
  16463. } else {
  16464. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  16465. var row = dataArrayRows[startIndex + i];
  16466. if (row && (result = detectValue(row[dimIndex])) != null) {
  16467. return result;
  16468. }
  16469. }
  16470. }
  16471. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16472. var dataObjectRows = data;
  16473. if (!dimName) {
  16474. return BE_ORDINAL.Not;
  16475. }
  16476. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  16477. var item = dataObjectRows[i];
  16478. if (item && (result = detectValue(item[dimName])) != null) {
  16479. return result;
  16480. }
  16481. }
  16482. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16483. var dataKeyedColumns = data;
  16484. if (!dimName) {
  16485. return BE_ORDINAL.Not;
  16486. }
  16487. var sample = dataKeyedColumns[dimName];
  16488. if (!sample || isTypedArray(sample)) {
  16489. return BE_ORDINAL.Not;
  16490. }
  16491. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16492. if ((result = detectValue(sample[i])) != null) {
  16493. return result;
  16494. }
  16495. }
  16496. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16497. var dataOriginal = data;
  16498. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  16499. var item = dataOriginal[i];
  16500. var val = getDataItemValue(item);
  16501. if (!isArray(val)) {
  16502. return BE_ORDINAL.Not;
  16503. }
  16504. if ((result = detectValue(val[dimIndex])) != null) {
  16505. return result;
  16506. }
  16507. }
  16508. }
  16509. function detectValue(val) {
  16510. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  16511. // `isFinit('')` get `true`.
  16512. if (val != null && isFinite(val) && val !== '') {
  16513. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  16514. } else if (beStr && val !== '-') {
  16515. return BE_ORDINAL.Must;
  16516. }
  16517. }
  16518. return BE_ORDINAL.Not;
  16519. }
  16520. var internalOptionCreatorMap = createHashMap();
  16521. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  16522. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  16523. if (!internalOptionCreator) {
  16524. return newCmptOptionList;
  16525. }
  16526. var internalOptions = internalOptionCreator(ecModel);
  16527. if (!internalOptions) {
  16528. return newCmptOptionList;
  16529. }
  16530. if ("development" !== 'production') {
  16531. for (var i = 0; i < internalOptions.length; i++) {
  16532. assert(isComponentIdInternal(internalOptions[i]));
  16533. }
  16534. }
  16535. return newCmptOptionList.concat(internalOptions);
  16536. }
  16537. var innerColor = makeInner();
  16538. var innerDecal = makeInner();
  16539. var PaletteMixin =
  16540. /** @class */
  16541. function () {
  16542. function PaletteMixin() {}
  16543. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  16544. var defaultPalette = normalizeToArray(this.get('color', true));
  16545. var layeredPalette = this.get('colorLayer', true);
  16546. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  16547. };
  16548. PaletteMixin.prototype.clearColorPalette = function () {
  16549. clearPalette(this, innerColor);
  16550. };
  16551. return PaletteMixin;
  16552. }();
  16553. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  16554. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  16555. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  16556. }
  16557. function getNearestPalette(palettes, requestColorNum) {
  16558. var paletteNum = palettes.length; // TODO palettes must be in order
  16559. for (var i = 0; i < paletteNum; i++) {
  16560. if (palettes[i].length > requestColorNum) {
  16561. return palettes[i];
  16562. }
  16563. }
  16564. return palettes[paletteNum - 1];
  16565. }
  16566. /**
  16567. * @param name MUST NOT be null/undefined. Otherwise call this function
  16568. * twise with the same parameters will get different result.
  16569. * @param scope default this.
  16570. * @return Can be null/undefined
  16571. */
  16572. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  16573. scope = scope || that;
  16574. var scopeFields = inner(scope);
  16575. var paletteIdx = scopeFields.paletteIdx || 0;
  16576. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16577. if (paletteNameMap.hasOwnProperty(name)) {
  16578. return paletteNameMap[name];
  16579. }
  16580. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  16581. palette = palette || defaultPalette;
  16582. if (!palette || !palette.length) {
  16583. return;
  16584. }
  16585. var pickedPaletteItem = palette[paletteIdx];
  16586. if (name) {
  16587. paletteNameMap[name] = pickedPaletteItem;
  16588. }
  16589. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  16590. return pickedPaletteItem;
  16591. }
  16592. function clearPalette(that, inner) {
  16593. inner(that).paletteIdx = 0;
  16594. inner(that).paletteNameMap = {};
  16595. }
  16596. // Internal method names:
  16597. // -----------------------
  16598. var reCreateSeriesIndices;
  16599. var assertSeriesInitialized;
  16600. var initBase;
  16601. var OPTION_INNER_KEY = '\0_ec_inner';
  16602. var OPTION_INNER_VALUE = 1;
  16603. var BUITIN_COMPONENTS_MAP = {
  16604. grid: 'GridComponent',
  16605. polar: 'PolarComponent',
  16606. geo: 'GeoComponent',
  16607. singleAxis: 'SingleAxisComponent',
  16608. parallel: 'ParallelComponent',
  16609. calendar: 'CalendarComponent',
  16610. graphic: 'GraphicComponent',
  16611. toolbox: 'ToolboxComponent',
  16612. tooltip: 'TooltipComponent',
  16613. axisPointer: 'AxisPointerComponent',
  16614. brush: 'BrushComponent',
  16615. title: 'TitleComponent',
  16616. timeline: 'TimelineComponent',
  16617. markPoint: 'MarkPointComponent',
  16618. markLine: 'MarkLineComponent',
  16619. markArea: 'MarkAreaComponent',
  16620. legend: 'LegendComponent',
  16621. dataZoom: 'DataZoomComponent',
  16622. visualMap: 'VisualMapComponent',
  16623. // aria: 'AriaComponent',
  16624. // dataset: 'DatasetComponent',
  16625. // Dependencies
  16626. xAxis: 'GridComponent',
  16627. yAxis: 'GridComponent',
  16628. angleAxis: 'PolarComponent',
  16629. radiusAxis: 'PolarComponent'
  16630. };
  16631. var BUILTIN_CHARTS_MAP = {
  16632. line: 'LineChart',
  16633. bar: 'BarChart',
  16634. pie: 'PieChart',
  16635. scatter: 'ScatterChart',
  16636. radar: 'RadarChart',
  16637. map: 'MapChart',
  16638. tree: 'TreeChart',
  16639. treemap: 'TreemapChart',
  16640. graph: 'GraphChart',
  16641. gauge: 'GaugeChart',
  16642. funnel: 'FunnelChart',
  16643. parallel: 'ParallelChart',
  16644. sankey: 'SankeyChart',
  16645. boxplot: 'BoxplotChart',
  16646. candlestick: 'CandlestickChart',
  16647. effectScatter: 'EffectScatterChart',
  16648. lines: 'LinesChart',
  16649. heatmap: 'HeatmapChart',
  16650. pictorialBar: 'PictorialBarChart',
  16651. themeRiver: 'ThemeRiverChart',
  16652. sunburst: 'SunburstChart',
  16653. custom: 'CustomChart'
  16654. };
  16655. var componetsMissingLogPrinted = {};
  16656. function checkMissingComponents(option) {
  16657. each(option, function (componentOption, mainType) {
  16658. if (!ComponentModel.hasClass(mainType)) {
  16659. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  16660. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  16661. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  16662. componetsMissingLogPrinted[componentImportName] = true;
  16663. }
  16664. }
  16665. });
  16666. }
  16667. var GlobalModel =
  16668. /** @class */
  16669. function (_super) {
  16670. __extends(GlobalModel, _super);
  16671. function GlobalModel() {
  16672. return _super !== null && _super.apply(this, arguments) || this;
  16673. }
  16674. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  16675. theme = theme || {};
  16676. this.option = null; // Mark as not initialized.
  16677. this._theme = new Model(theme);
  16678. this._locale = new Model(locale);
  16679. this._optionManager = optionManager;
  16680. };
  16681. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  16682. if ("development" !== 'production') {
  16683. assert(option != null, 'option is null/undefined');
  16684. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  16685. }
  16686. var innerOpt = normalizeSetOptionInput(opts);
  16687. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  16688. this._resetOption(null, innerOpt);
  16689. };
  16690. /**
  16691. * @param type null/undefined: reset all.
  16692. * 'recreate': force recreate all.
  16693. * 'timeline': only reset timeline option
  16694. * 'media': only reset media query option
  16695. * @return Whether option changed.
  16696. */
  16697. GlobalModel.prototype.resetOption = function (type, opt) {
  16698. return this._resetOption(type, normalizeSetOptionInput(opt));
  16699. };
  16700. GlobalModel.prototype._resetOption = function (type, opt) {
  16701. var optionChanged = false;
  16702. var optionManager = this._optionManager;
  16703. if (!type || type === 'recreate') {
  16704. var baseOption = optionManager.mountOption(type === 'recreate');
  16705. if ("development" !== 'production') {
  16706. checkMissingComponents(baseOption);
  16707. }
  16708. if (!this.option || type === 'recreate') {
  16709. initBase(this, baseOption);
  16710. } else {
  16711. this.restoreData();
  16712. this._mergeOption(baseOption, opt);
  16713. }
  16714. optionChanged = true;
  16715. }
  16716. if (type === 'timeline' || type === 'media') {
  16717. this.restoreData();
  16718. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  16719. // it should better not have the same props with `MediaUnit['option']`.
  16720. // Becuase either `option2` or `MediaUnit['option']` will be always merged to "current option"
  16721. // rather than original "baseOption". If they both override a prop, the result might be
  16722. // unexpected when media state changed after `setOption` called.
  16723. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  16724. // (`{baseOption, media}`) in `setOption`.
  16725. // For `timeline`, the case is the same.
  16726. if (!type || type === 'recreate' || type === 'timeline') {
  16727. var timelineOption = optionManager.getTimelineOption(this);
  16728. if (timelineOption) {
  16729. optionChanged = true;
  16730. this._mergeOption(timelineOption, opt);
  16731. }
  16732. }
  16733. if (!type || type === 'recreate' || type === 'media') {
  16734. var mediaOptions = optionManager.getMediaOption(this);
  16735. if (mediaOptions.length) {
  16736. each(mediaOptions, function (mediaOption) {
  16737. optionChanged = true;
  16738. this._mergeOption(mediaOption, opt);
  16739. }, this);
  16740. }
  16741. }
  16742. return optionChanged;
  16743. };
  16744. GlobalModel.prototype.mergeOption = function (option) {
  16745. this._mergeOption(option, null);
  16746. };
  16747. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  16748. var option = this.option;
  16749. var componentsMap = this._componentsMap;
  16750. var componentsCount = this._componentsCount;
  16751. var newCmptTypes = [];
  16752. var newCmptTypeMap = createHashMap();
  16753. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  16754. resetSourceDefaulter(this); // If no component class, merge directly.
  16755. // For example: color, animaiton options, etc.
  16756. each(newOption, function (componentOption, mainType) {
  16757. if (componentOption == null) {
  16758. return;
  16759. }
  16760. if (!ComponentModel.hasClass(mainType)) {
  16761. // globalSettingTask.dirty();
  16762. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  16763. } else if (mainType) {
  16764. newCmptTypes.push(mainType);
  16765. newCmptTypeMap.set(mainType, true);
  16766. }
  16767. });
  16768. if (replaceMergeMainTypeMap) {
  16769. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  16770. // we trade it as it is declared in option as `{xxx: []}`. Because:
  16771. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  16772. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  16773. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  16774. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  16775. newCmptTypes.push(mainTypeInReplaceMerge);
  16776. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  16777. }
  16778. });
  16779. }
  16780. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  16781. function visitComponent(mainType) {
  16782. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  16783. var oldCmptList = componentsMap.get(mainType);
  16784. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  16785. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  16786. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  16787. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  16788. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  16789. // components, which is probably incorrect logic.
  16790. option[mainType] = null;
  16791. componentsMap.set(mainType, null);
  16792. componentsCount.set(mainType, 0);
  16793. var optionsByMainType = [];
  16794. var cmptsByMainType = [];
  16795. var cmptsCountByMainType = 0;
  16796. var tooltipExists;
  16797. var tooltipWarningLogged;
  16798. each(mappingResult, function (resultItem, index) {
  16799. var componentModel = resultItem.existing;
  16800. var newCmptOption = resultItem.newOption;
  16801. if (!newCmptOption) {
  16802. if (componentModel) {
  16803. // Consider where is no new option and should be merged using {},
  16804. // see removeEdgeAndAdd in topologicalTravel and
  16805. // ComponentModel.getAllClassMainTypes.
  16806. componentModel.mergeOption({}, this);
  16807. componentModel.optionUpdated({}, false);
  16808. } // If no both `resultItem.exist` and `resultItem.option`,
  16809. // either it is in `replaceMerge` and not matched by any id,
  16810. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  16811. } else {
  16812. var isSeriesType = mainType === 'series';
  16813. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  16814. );
  16815. if (!ComponentModelClass) {
  16816. if ("development" !== 'production') {
  16817. var subType = resultItem.keyInfo.subType;
  16818. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  16819. if (!componetsMissingLogPrinted[subType]) {
  16820. componetsMissingLogPrinted[subType] = true;
  16821. if (seriesImportName) {
  16822. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  16823. } else {
  16824. error("Unkown series " + subType);
  16825. }
  16826. }
  16827. }
  16828. return;
  16829. } // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  16830. if (mainType === 'tooltip') {
  16831. if (tooltipExists) {
  16832. if ("development" !== 'production') {
  16833. if (!tooltipWarningLogged) {
  16834. warn('Currently only one tooltip component is allowed.');
  16835. tooltipWarningLogged = true;
  16836. }
  16837. }
  16838. return;
  16839. }
  16840. tooltipExists = true;
  16841. }
  16842. if (componentModel && componentModel.constructor === ComponentModelClass) {
  16843. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  16844. componentModel.mergeOption(newCmptOption, this);
  16845. componentModel.optionUpdated(newCmptOption, false);
  16846. } else {
  16847. // PENDING Global as parent ?
  16848. var extraOpt = extend({
  16849. componentIndex: index
  16850. }, resultItem.keyInfo);
  16851. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  16852. extend(componentModel, extraOpt);
  16853. if (resultItem.brandNew) {
  16854. componentModel.__requireNewView = true;
  16855. }
  16856. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  16857. // newCmptOption has been used as componentModel.option
  16858. // and may be merged with theme and default, so pass null
  16859. // to avoid confusion.
  16860. componentModel.optionUpdated(null, true);
  16861. }
  16862. }
  16863. if (componentModel) {
  16864. optionsByMainType.push(componentModel.option);
  16865. cmptsByMainType.push(componentModel);
  16866. cmptsCountByMainType++;
  16867. } else {
  16868. // Always do assign to avoid elided item in array.
  16869. optionsByMainType.push(void 0);
  16870. cmptsByMainType.push(void 0);
  16871. }
  16872. }, this);
  16873. option[mainType] = optionsByMainType;
  16874. componentsMap.set(mainType, cmptsByMainType);
  16875. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  16876. if (mainType === 'series') {
  16877. reCreateSeriesIndices(this);
  16878. }
  16879. } // If no series declared, ensure `_seriesIndices` initialized.
  16880. if (!this._seriesIndices) {
  16881. reCreateSeriesIndices(this);
  16882. }
  16883. };
  16884. /**
  16885. * Get option for output (cloned option and inner info removed)
  16886. */
  16887. GlobalModel.prototype.getOption = function () {
  16888. var option = clone(this.option);
  16889. each(option, function (optInMainType, mainType) {
  16890. if (ComponentModel.hasClass(mainType)) {
  16891. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  16892. // Inner cmpts might not be at last since ec5.0, but still
  16893. // compatible for users: if inner cmpt at last, splice the returned array.
  16894. var realLen = opts.length;
  16895. var metNonInner = false;
  16896. for (var i = realLen - 1; i >= 0; i--) {
  16897. // Remove options with inner id.
  16898. if (opts[i] && !isComponentIdInternal(opts[i])) {
  16899. metNonInner = true;
  16900. } else {
  16901. opts[i] = null;
  16902. !metNonInner && realLen--;
  16903. }
  16904. }
  16905. opts.length = realLen;
  16906. option[mainType] = opts;
  16907. }
  16908. });
  16909. delete option[OPTION_INNER_KEY];
  16910. return option;
  16911. };
  16912. GlobalModel.prototype.getTheme = function () {
  16913. return this._theme;
  16914. };
  16915. GlobalModel.prototype.getLocaleModel = function () {
  16916. return this._locale;
  16917. };
  16918. GlobalModel.prototype.setUpdatePayload = function (payload) {
  16919. this._payload = payload;
  16920. };
  16921. GlobalModel.prototype.getUpdatePayload = function () {
  16922. return this._payload;
  16923. };
  16924. /**
  16925. * @param idx If not specified, return the first one.
  16926. */
  16927. GlobalModel.prototype.getComponent = function (mainType, idx) {
  16928. var list = this._componentsMap.get(mainType);
  16929. if (list) {
  16930. var cmpt = list[idx || 0];
  16931. if (cmpt) {
  16932. return cmpt;
  16933. } else if (idx == null) {
  16934. for (var i = 0; i < list.length; i++) {
  16935. if (list[i]) {
  16936. return list[i];
  16937. }
  16938. }
  16939. }
  16940. }
  16941. };
  16942. /**
  16943. * @return Never be null/undefined.
  16944. */
  16945. GlobalModel.prototype.queryComponents = function (condition) {
  16946. var mainType = condition.mainType;
  16947. if (!mainType) {
  16948. return [];
  16949. }
  16950. var index = condition.index;
  16951. var id = condition.id;
  16952. var name = condition.name;
  16953. var cmpts = this._componentsMap.get(mainType);
  16954. if (!cmpts || !cmpts.length) {
  16955. return [];
  16956. }
  16957. var result;
  16958. if (index != null) {
  16959. result = [];
  16960. each(normalizeToArray(index), function (idx) {
  16961. cmpts[idx] && result.push(cmpts[idx]);
  16962. });
  16963. } else if (id != null) {
  16964. result = queryByIdOrName('id', id, cmpts);
  16965. } else if (name != null) {
  16966. result = queryByIdOrName('name', name, cmpts);
  16967. } else {
  16968. // Return all non-empty components in that mainType
  16969. result = filter(cmpts, function (cmpt) {
  16970. return !!cmpt;
  16971. });
  16972. }
  16973. return filterBySubType(result, condition);
  16974. };
  16975. /**
  16976. * The interface is different from queryComponents,
  16977. * which is convenient for inner usage.
  16978. *
  16979. * @usage
  16980. * let result = findComponents(
  16981. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  16982. * );
  16983. * let result = findComponents(
  16984. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  16985. * );
  16986. * let result = findComponents(
  16987. * {mainType: 'series',
  16988. * filter: function (model, index) {...}}
  16989. * );
  16990. * // result like [component0, componnet1, ...]
  16991. */
  16992. GlobalModel.prototype.findComponents = function (condition) {
  16993. var query = condition.query;
  16994. var mainType = condition.mainType;
  16995. var queryCond = getQueryCond(query);
  16996. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  16997. : filter(this._componentsMap.get(mainType), function (cmpt) {
  16998. return !!cmpt;
  16999. });
  17000. return doFilter(filterBySubType(result, condition));
  17001. function getQueryCond(q) {
  17002. var indexAttr = mainType + 'Index';
  17003. var idAttr = mainType + 'Id';
  17004. var nameAttr = mainType + 'Name';
  17005. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17006. mainType: mainType,
  17007. // subType will be filtered finally.
  17008. index: q[indexAttr],
  17009. id: q[idAttr],
  17010. name: q[nameAttr]
  17011. } : null;
  17012. }
  17013. function doFilter(res) {
  17014. return condition.filter ? filter(res, condition.filter) : res;
  17015. }
  17016. };
  17017. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17018. var componentsMap = this._componentsMap;
  17019. if (isFunction(mainType)) {
  17020. var ctxForAll_1 = cb;
  17021. var cbForAll_1 = mainType;
  17022. componentsMap.each(function (cmpts, componentType) {
  17023. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17024. var cmpt = cmpts[i];
  17025. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17026. }
  17027. });
  17028. } else {
  17029. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17030. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17031. var cmpt = cmpts[i];
  17032. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17033. }
  17034. }
  17035. };
  17036. /**
  17037. * Get series list before filtered by name.
  17038. */
  17039. GlobalModel.prototype.getSeriesByName = function (name) {
  17040. var nameStr = convertOptionIdName(name, null);
  17041. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17042. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17043. });
  17044. };
  17045. /**
  17046. * Get series list before filtered by index.
  17047. */
  17048. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17049. return this._componentsMap.get('series')[seriesIndex];
  17050. };
  17051. /**
  17052. * Get series list before filtered by type.
  17053. * FIXME: rename to getRawSeriesByType?
  17054. */
  17055. GlobalModel.prototype.getSeriesByType = function (subType) {
  17056. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17057. return !!oneSeries && oneSeries.subType === subType;
  17058. });
  17059. };
  17060. /**
  17061. * Get all series before filtered.
  17062. */
  17063. GlobalModel.prototype.getSeries = function () {
  17064. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17065. return !!oneSeries;
  17066. });
  17067. };
  17068. /**
  17069. * Count series before filtered.
  17070. */
  17071. GlobalModel.prototype.getSeriesCount = function () {
  17072. return this._componentsCount.get('series');
  17073. };
  17074. /**
  17075. * After filtering, series may be different
  17076. * frome raw series.
  17077. */
  17078. GlobalModel.prototype.eachSeries = function (cb, context) {
  17079. assertSeriesInitialized(this);
  17080. each(this._seriesIndices, function (rawSeriesIndex) {
  17081. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17082. cb.call(context, series, rawSeriesIndex);
  17083. }, this);
  17084. };
  17085. /**
  17086. * Iterate raw series before filtered.
  17087. *
  17088. * @param {Function} cb
  17089. * @param {*} context
  17090. */
  17091. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17092. each(this._componentsMap.get('series'), function (series) {
  17093. series && cb.call(context, series, series.componentIndex);
  17094. });
  17095. };
  17096. /**
  17097. * After filtering, series may be different.
  17098. * frome raw series.
  17099. */
  17100. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17101. assertSeriesInitialized(this);
  17102. each(this._seriesIndices, function (rawSeriesIndex) {
  17103. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17104. if (series.subType === subType) {
  17105. cb.call(context, series, rawSeriesIndex);
  17106. }
  17107. }, this);
  17108. };
  17109. /**
  17110. * Iterate raw series before filtered of given type.
  17111. */
  17112. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17113. return each(this.getSeriesByType(subType), cb, context);
  17114. };
  17115. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17116. assertSeriesInitialized(this);
  17117. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17118. };
  17119. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17120. return (this._seriesIndices || []).slice();
  17121. };
  17122. GlobalModel.prototype.filterSeries = function (cb, context) {
  17123. assertSeriesInitialized(this);
  17124. var newSeriesIndices = [];
  17125. each(this._seriesIndices, function (seriesRawIdx) {
  17126. var series = this._componentsMap.get('series')[seriesRawIdx];
  17127. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17128. }, this);
  17129. this._seriesIndices = newSeriesIndices;
  17130. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17131. };
  17132. GlobalModel.prototype.restoreData = function (payload) {
  17133. reCreateSeriesIndices(this);
  17134. var componentsMap = this._componentsMap;
  17135. var componentTypes = [];
  17136. componentsMap.each(function (components, componentType) {
  17137. if (ComponentModel.hasClass(componentType)) {
  17138. componentTypes.push(componentType);
  17139. }
  17140. });
  17141. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17142. each(componentsMap.get(componentType), function (component) {
  17143. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17144. component.restoreData();
  17145. }
  17146. });
  17147. });
  17148. };
  17149. GlobalModel.internalField = function () {
  17150. reCreateSeriesIndices = function (ecModel) {
  17151. var seriesIndices = ecModel._seriesIndices = [];
  17152. each(ecModel._componentsMap.get('series'), function (series) {
  17153. // series may have been removed by `replaceMerge`.
  17154. series && seriesIndices.push(series.componentIndex);
  17155. });
  17156. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17157. };
  17158. assertSeriesInitialized = function (ecModel) {
  17159. // Components that use _seriesIndices should depends on series component,
  17160. // which make sure that their initialization is after series.
  17161. if ("development" !== 'production') {
  17162. if (!ecModel._seriesIndices) {
  17163. throw new Error('Option should contains series.');
  17164. }
  17165. }
  17166. };
  17167. initBase = function (ecModel, baseOption) {
  17168. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17169. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17170. ecModel.option = {};
  17171. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17172. // before series initialized.
  17173. ecModel._componentsMap = createHashMap({
  17174. series: []
  17175. });
  17176. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17177. // performed before theme and globalDefault merge.
  17178. var airaOption = baseOption.aria;
  17179. if (isObject(airaOption) && airaOption.enabled == null) {
  17180. airaOption.enabled = true;
  17181. }
  17182. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17183. merge(baseOption, globalDefault, false);
  17184. ecModel._mergeOption(baseOption, null);
  17185. };
  17186. }();
  17187. return GlobalModel;
  17188. }(Model);
  17189. function isNotTargetSeries(seriesModel, payload) {
  17190. if (payload) {
  17191. var index = payload.seriesIndex;
  17192. var id = payload.seriesId;
  17193. var name_1 = payload.seriesName;
  17194. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17195. }
  17196. }
  17197. function mergeTheme(option, theme) {
  17198. // PENDING
  17199. // NOT use `colorLayer` in theme if option has `color`
  17200. var notMergeColorLayer = option.color && !option.colorLayer;
  17201. each(theme, function (themeItem, name) {
  17202. if (name === 'colorLayer' && notMergeColorLayer) {
  17203. return;
  17204. } // If it is component model mainType, the model handles that merge later.
  17205. // otherwise, merge them here.
  17206. if (!ComponentModel.hasClass(name)) {
  17207. if (typeof themeItem === 'object') {
  17208. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17209. } else {
  17210. if (option[name] == null) {
  17211. option[name] = themeItem;
  17212. }
  17213. }
  17214. }
  17215. });
  17216. }
  17217. function queryByIdOrName(attr, idOrName, cmpts) {
  17218. // Here is a break from echarts4: string and number are
  17219. // treated as equal.
  17220. if (isArray(idOrName)) {
  17221. var keyMap_1 = createHashMap();
  17222. each(idOrName, function (idOrNameItem) {
  17223. if (idOrNameItem != null) {
  17224. var idName = convertOptionIdName(idOrNameItem, null);
  17225. idName != null && keyMap_1.set(idOrNameItem, true);
  17226. }
  17227. });
  17228. return filter(cmpts, function (cmpt) {
  17229. return cmpt && keyMap_1.get(cmpt[attr]);
  17230. });
  17231. } else {
  17232. var idName_1 = convertOptionIdName(idOrName, null);
  17233. return filter(cmpts, function (cmpt) {
  17234. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17235. });
  17236. }
  17237. }
  17238. function filterBySubType(components, condition) {
  17239. // Using hasOwnProperty for restrict. Consider
  17240. // subType is undefined in user payload.
  17241. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  17242. return cmpt && cmpt.subType === condition.subType;
  17243. }) : components;
  17244. }
  17245. function normalizeSetOptionInput(opts) {
  17246. var replaceMergeMainTypeMap = createHashMap();
  17247. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  17248. if ("development" !== 'production') {
  17249. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  17250. }
  17251. replaceMergeMainTypeMap.set(mainType, true);
  17252. });
  17253. return {
  17254. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  17255. };
  17256. }
  17257. mixin(GlobalModel, PaletteMixin);
  17258. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  17259. 'getOption', // 'getViewOfComponentModel',
  17260. // 'getViewOfSeriesModel',
  17261. 'getId', 'updateLabelLayout'];
  17262. var ExtensionAPI =
  17263. /** @class */
  17264. function () {
  17265. function ExtensionAPI(ecInstance) {
  17266. each(availableMethods, function (methodName) {
  17267. this[methodName] = bind(ecInstance[methodName], ecInstance);
  17268. }, this);
  17269. }
  17270. return ExtensionAPI;
  17271. }();
  17272. var coordinateSystemCreators = {};
  17273. var CoordinateSystemManager =
  17274. /** @class */
  17275. function () {
  17276. function CoordinateSystemManager() {
  17277. this._coordinateSystems = [];
  17278. }
  17279. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17280. var coordinateSystems = [];
  17281. each(coordinateSystemCreators, function (creater, type) {
  17282. var list = creater.create(ecModel, api);
  17283. coordinateSystems = coordinateSystems.concat(list || []);
  17284. });
  17285. this._coordinateSystems = coordinateSystems;
  17286. };
  17287. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17288. each(this._coordinateSystems, function (coordSys) {
  17289. coordSys.update && coordSys.update(ecModel, api);
  17290. });
  17291. };
  17292. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17293. return this._coordinateSystems.slice();
  17294. };
  17295. CoordinateSystemManager.register = function (type, creator) {
  17296. coordinateSystemCreators[type] = creator;
  17297. };
  17298. CoordinateSystemManager.get = function (type) {
  17299. return coordinateSystemCreators[type];
  17300. };
  17301. return CoordinateSystemManager;
  17302. }();
  17303. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  17304. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  17305. /**
  17306. * TERM EXPLANATIONS:
  17307. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  17308. */
  17309. var OptionManager =
  17310. /** @class */
  17311. function () {
  17312. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17313. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17314. // rawOption cloned and backuped when timeline changed, which does no
  17315. // good to performance. What's more, that both timeline and setOption
  17316. // method supply 'notMerge' brings complex and some problems.
  17317. // Consider this case:
  17318. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17319. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17320. function OptionManager(api) {
  17321. this._timelineOptions = [];
  17322. this._mediaList = [];
  17323. /**
  17324. * -1, means default.
  17325. * empty means no media.
  17326. */
  17327. this._currentMediaIndices = [];
  17328. this._api = api;
  17329. }
  17330. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17331. if (rawOption) {
  17332. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17333. each(normalizeToArray(rawOption.series), function (series) {
  17334. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17335. });
  17336. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17337. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17338. });
  17339. } // Caution: some series modify option data, if do not clone,
  17340. // it should ensure that the repeat modify correctly
  17341. // (create a new object when modify itself).
  17342. rawOption = clone(rawOption); // FIXME
  17343. // If some property is set in timeline options or media option but
  17344. // not set in baseOption, a warning should be given.
  17345. var optionBackup = this._optionBackup;
  17346. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17347. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  17348. if (optionBackup) {
  17349. // FIXME
  17350. // the restore merge solution is essentially incorrect.
  17351. // the mapping can not be 100% consistent with ecModel, which probably brings
  17352. // potential bug!
  17353. // The first merge is delayed, becuase in most cases, users do not call `setOption` twice.
  17354. // let fakeCmptsMap = this._fakeCmptsMap;
  17355. // if (!fakeCmptsMap) {
  17356. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17357. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17358. // }
  17359. // mergeToBackupOption(
  17360. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17361. // );
  17362. // For simplicity, timeline options and media options do not support merge,
  17363. // that is, if you `setOption` twice and both has timeline options, the latter
  17364. // timeline opitons will not be merged to the formers, but just substitude them.
  17365. if (newParsedOption.timelineOptions.length) {
  17366. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17367. }
  17368. if (newParsedOption.mediaList.length) {
  17369. optionBackup.mediaList = newParsedOption.mediaList;
  17370. }
  17371. if (newParsedOption.mediaDefault) {
  17372. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17373. }
  17374. } else {
  17375. this._optionBackup = newParsedOption;
  17376. }
  17377. };
  17378. OptionManager.prototype.mountOption = function (isRecreate) {
  17379. var optionBackup = this._optionBackup;
  17380. this._timelineOptions = optionBackup.timelineOptions;
  17381. this._mediaList = optionBackup.mediaList;
  17382. this._mediaDefault = optionBackup.mediaDefault;
  17383. this._currentMediaIndices = [];
  17384. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  17385. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17386. // each time `setOption` called, can be only used in `isRecreate`, because
  17387. // its reliability is under suspicion. In other cases option merge is
  17388. // performed by `model.mergeOption`.
  17389. ? optionBackup.baseOption : this._newBaseOption);
  17390. };
  17391. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17392. var option;
  17393. var timelineOptions = this._timelineOptions;
  17394. if (timelineOptions.length) {
  17395. // getTimelineOption can only be called after ecModel inited,
  17396. // so we can get currentIndex from timelineModel.
  17397. var timelineModel = ecModel.getComponent('timeline');
  17398. if (timelineModel) {
  17399. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  17400. timelineOptions[timelineModel.getCurrentIndex()]);
  17401. }
  17402. }
  17403. return option;
  17404. };
  17405. OptionManager.prototype.getMediaOption = function (ecModel) {
  17406. var ecWidth = this._api.getWidth();
  17407. var ecHeight = this._api.getHeight();
  17408. var mediaList = this._mediaList;
  17409. var mediaDefault = this._mediaDefault;
  17410. var indices = [];
  17411. var result = []; // No media defined.
  17412. if (!mediaList.length && !mediaDefault) {
  17413. return result;
  17414. } // Multi media may be applied, the latter defined media has higher priority.
  17415. for (var i = 0, len = mediaList.length; i < len; i++) {
  17416. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17417. indices.push(i);
  17418. }
  17419. } // FIXME
  17420. // Whether mediaDefault should force users to provide? Otherwise
  17421. // the change by media query can not be recorvered.
  17422. if (!indices.length && mediaDefault) {
  17423. indices = [-1];
  17424. }
  17425. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17426. result = map(indices, function (index) {
  17427. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  17428. });
  17429. } // Otherwise return nothing.
  17430. this._currentMediaIndices = indices;
  17431. return result;
  17432. };
  17433. return OptionManager;
  17434. }();
  17435. /**
  17436. * [RAW_OPTION_PATTERNS]
  17437. * (Note: "series: []" represents all other props in `ECUnitOption`)
  17438. *
  17439. * (1) No prop "baseOption" declared:
  17440. * Root option is used as "baseOption" (except prop "options" and "media").
  17441. * ```js
  17442. * option = {
  17443. * series: [],
  17444. * timeline: {},
  17445. * options: [],
  17446. * };
  17447. * option = {
  17448. * series: [],
  17449. * media: {},
  17450. * };
  17451. * option = {
  17452. * series: [],
  17453. * timeline: {},
  17454. * options: [],
  17455. * media: {},
  17456. * }
  17457. * ```
  17458. *
  17459. * (2) Prop "baseOption" declared:
  17460. * If "baseOption" declared, `ECUnitOption` props can only be declared
  17461. * inside "baseOption" except prop "timeline" (compat ec2).
  17462. * ```js
  17463. * option = {
  17464. * baseOption: {
  17465. * timeline: {},
  17466. * series: [],
  17467. * },
  17468. * options: []
  17469. * };
  17470. * option = {
  17471. * baseOption: {
  17472. * series: [],
  17473. * },
  17474. * media: []
  17475. * };
  17476. * option = {
  17477. * baseOption: {
  17478. * timeline: {},
  17479. * series: [],
  17480. * },
  17481. * options: []
  17482. * media: []
  17483. * };
  17484. * option = {
  17485. * // ec3 compat ec2: allow (only) `timeline` declared
  17486. * // outside baseOption. Keep this setting for compat.
  17487. * timeline: {},
  17488. * baseOption: {
  17489. * series: [],
  17490. * },
  17491. * options: [],
  17492. * media: []
  17493. * };
  17494. * ```
  17495. */
  17496. function parseRawOption( // `rawOption` May be modified
  17497. rawOption, optionPreprocessorFuncs, isNew) {
  17498. var mediaList = [];
  17499. var mediaDefault;
  17500. var baseOption;
  17501. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  17502. var timelineOnRoot = rawOption.timeline;
  17503. var timelineOptionsOnRoot = rawOption.options;
  17504. var mediaOnRoot = rawOption.media;
  17505. var hasMedia = !!rawOption.media;
  17506. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  17507. if (declaredBaseOption) {
  17508. baseOption = declaredBaseOption; // For merge option.
  17509. if (!baseOption.timeline) {
  17510. baseOption.timeline = timelineOnRoot;
  17511. }
  17512. } // For convenience, enable to use the root option as the `baseOption`:
  17513. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  17514. else {
  17515. if (hasTimeline || hasMedia) {
  17516. rawOption.options = rawOption.media = null;
  17517. }
  17518. baseOption = rawOption;
  17519. }
  17520. if (hasMedia) {
  17521. if (isArray(mediaOnRoot)) {
  17522. each(mediaOnRoot, function (singleMedia) {
  17523. if ("development" !== 'production') {
  17524. // Real case of wrong config.
  17525. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  17526. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  17527. }
  17528. }
  17529. if (singleMedia && singleMedia.option) {
  17530. if (singleMedia.query) {
  17531. mediaList.push(singleMedia);
  17532. } else if (!mediaDefault) {
  17533. // Use the first media default.
  17534. mediaDefault = singleMedia;
  17535. }
  17536. }
  17537. });
  17538. } else {
  17539. if ("development" !== 'production') {
  17540. // Real case of wrong config.
  17541. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  17542. }
  17543. }
  17544. }
  17545. doPreprocess(baseOption);
  17546. each(timelineOptionsOnRoot, function (option) {
  17547. return doPreprocess(option);
  17548. });
  17549. each(mediaList, function (media) {
  17550. return doPreprocess(media.option);
  17551. });
  17552. function doPreprocess(option) {
  17553. each(optionPreprocessorFuncs, function (preProcess) {
  17554. preProcess(option, isNew);
  17555. });
  17556. }
  17557. return {
  17558. baseOption: baseOption,
  17559. timelineOptions: timelineOptionsOnRoot || [],
  17560. mediaDefault: mediaDefault,
  17561. mediaList: mediaList
  17562. };
  17563. }
  17564. /**
  17565. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17566. * Support: width, height, aspectRatio
  17567. * Can use max or min as prefix.
  17568. */
  17569. function applyMediaQuery(query, ecWidth, ecHeight) {
  17570. var realMap = {
  17571. width: ecWidth,
  17572. height: ecHeight,
  17573. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17574. };
  17575. var applicatable = true;
  17576. each(query, function (value, attr) {
  17577. var matched = attr.match(QUERY_REG);
  17578. if (!matched || !matched[1] || !matched[2]) {
  17579. return;
  17580. }
  17581. var operator = matched[1];
  17582. var realAttr = matched[2].toLowerCase();
  17583. if (!compare(realMap[realAttr], value, operator)) {
  17584. applicatable = false;
  17585. }
  17586. });
  17587. return applicatable;
  17588. }
  17589. function compare(real, expect, operator) {
  17590. if (operator === 'min') {
  17591. return real >= expect;
  17592. } else if (operator === 'max') {
  17593. return real <= expect;
  17594. } else {
  17595. // Equals
  17596. return real === expect;
  17597. }
  17598. }
  17599. function indicesEquals(indices1, indices2) {
  17600. // indices is always order by asc and has only finite number.
  17601. return indices1.join(',') === indices2.join(',');
  17602. }
  17603. var each$2 = each;
  17604. var isObject$1 = isObject;
  17605. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  17606. function compatEC2ItemStyle(opt) {
  17607. var itemStyleOpt = opt && opt.itemStyle;
  17608. if (!itemStyleOpt) {
  17609. return;
  17610. }
  17611. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17612. var styleName = POSSIBLE_STYLES[i];
  17613. var normalItemStyleOpt = itemStyleOpt.normal;
  17614. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17615. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  17616. if ("development" !== 'production') {
  17617. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  17618. }
  17619. opt[styleName] = opt[styleName] || {};
  17620. if (!opt[styleName].normal) {
  17621. opt[styleName].normal = normalItemStyleOpt[styleName];
  17622. } else {
  17623. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  17624. }
  17625. normalItemStyleOpt[styleName] = null;
  17626. }
  17627. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  17628. if ("development" !== 'production') {
  17629. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  17630. }
  17631. opt[styleName] = opt[styleName] || {};
  17632. if (!opt[styleName].emphasis) {
  17633. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  17634. } else {
  17635. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  17636. }
  17637. emphasisItemStyleOpt[styleName] = null;
  17638. }
  17639. }
  17640. }
  17641. function convertNormalEmphasis(opt, optType, useExtend) {
  17642. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  17643. var normalOpt = opt[optType].normal;
  17644. var emphasisOpt = opt[optType].emphasis;
  17645. if (normalOpt) {
  17646. if ("development" !== 'production') {
  17647. // eslint-disable-next-line max-len
  17648. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  17649. } // Timeline controlStyle has other properties besides normal and emphasis
  17650. if (useExtend) {
  17651. opt[optType].normal = opt[optType].emphasis = null;
  17652. defaults(opt[optType], normalOpt);
  17653. } else {
  17654. opt[optType] = normalOpt;
  17655. }
  17656. }
  17657. if (emphasisOpt) {
  17658. if ("development" !== 'production') {
  17659. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  17660. }
  17661. opt.emphasis = opt.emphasis || {};
  17662. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  17663. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  17664. if (emphasisOpt.focus) {
  17665. opt.emphasis.focus = emphasisOpt.focus;
  17666. }
  17667. if (emphasisOpt.blurScope) {
  17668. opt.emphasis.blurScope = emphasisOpt.blurScope;
  17669. }
  17670. }
  17671. }
  17672. }
  17673. function removeEC3NormalStatus(opt) {
  17674. convertNormalEmphasis(opt, 'itemStyle');
  17675. convertNormalEmphasis(opt, 'lineStyle');
  17676. convertNormalEmphasis(opt, 'areaStyle');
  17677. convertNormalEmphasis(opt, 'label');
  17678. convertNormalEmphasis(opt, 'labelLine'); // treemap
  17679. convertNormalEmphasis(opt, 'upperLabel'); // graph
  17680. convertNormalEmphasis(opt, 'edgeLabel');
  17681. }
  17682. function compatTextStyle(opt, propName) {
  17683. // Check whether is not object (string\null\undefined ...)
  17684. var labelOptSingle = isObject$1(opt) && opt[propName];
  17685. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  17686. if (textStyle) {
  17687. if ("development" !== 'production') {
  17688. // eslint-disable-next-line max-len
  17689. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  17690. }
  17691. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  17692. var textPropName = TEXT_STYLE_OPTIONS[i];
  17693. if (textStyle.hasOwnProperty(textPropName)) {
  17694. labelOptSingle[textPropName] = textStyle[textPropName];
  17695. }
  17696. }
  17697. }
  17698. }
  17699. function compatEC3CommonStyles(opt) {
  17700. if (opt) {
  17701. removeEC3NormalStatus(opt);
  17702. compatTextStyle(opt, 'label');
  17703. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  17704. }
  17705. }
  17706. function processSeries(seriesOpt) {
  17707. if (!isObject$1(seriesOpt)) {
  17708. return;
  17709. }
  17710. compatEC2ItemStyle(seriesOpt);
  17711. removeEC3NormalStatus(seriesOpt);
  17712. compatTextStyle(seriesOpt, 'label'); // treemap
  17713. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  17714. compatTextStyle(seriesOpt, 'edgeLabel');
  17715. if (seriesOpt.emphasis) {
  17716. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  17717. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  17718. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  17719. }
  17720. var markPoint = seriesOpt.markPoint;
  17721. if (markPoint) {
  17722. compatEC2ItemStyle(markPoint);
  17723. compatEC3CommonStyles(markPoint);
  17724. }
  17725. var markLine = seriesOpt.markLine;
  17726. if (markLine) {
  17727. compatEC2ItemStyle(markLine);
  17728. compatEC3CommonStyles(markLine);
  17729. }
  17730. var markArea = seriesOpt.markArea;
  17731. if (markArea) {
  17732. compatEC3CommonStyles(markArea);
  17733. }
  17734. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  17735. // then the backward compat based on option type will not be performed.
  17736. if (seriesOpt.type === 'graph') {
  17737. data = data || seriesOpt.nodes;
  17738. var edgeData = seriesOpt.links || seriesOpt.edges;
  17739. if (edgeData && !isTypedArray(edgeData)) {
  17740. for (var i = 0; i < edgeData.length; i++) {
  17741. compatEC3CommonStyles(edgeData[i]);
  17742. }
  17743. }
  17744. each(seriesOpt.categories, function (opt) {
  17745. removeEC3NormalStatus(opt);
  17746. });
  17747. }
  17748. if (data && !isTypedArray(data)) {
  17749. for (var i = 0; i < data.length; i++) {
  17750. compatEC3CommonStyles(data[i]);
  17751. }
  17752. } // mark point data
  17753. markPoint = seriesOpt.markPoint;
  17754. if (markPoint && markPoint.data) {
  17755. var mpData = markPoint.data;
  17756. for (var i = 0; i < mpData.length; i++) {
  17757. compatEC3CommonStyles(mpData[i]);
  17758. }
  17759. } // mark line data
  17760. markLine = seriesOpt.markLine;
  17761. if (markLine && markLine.data) {
  17762. var mlData = markLine.data;
  17763. for (var i = 0; i < mlData.length; i++) {
  17764. if (isArray(mlData[i])) {
  17765. compatEC3CommonStyles(mlData[i][0]);
  17766. compatEC3CommonStyles(mlData[i][1]);
  17767. } else {
  17768. compatEC3CommonStyles(mlData[i]);
  17769. }
  17770. }
  17771. } // Series
  17772. if (seriesOpt.type === 'gauge') {
  17773. compatTextStyle(seriesOpt, 'axisLabel');
  17774. compatTextStyle(seriesOpt, 'title');
  17775. compatTextStyle(seriesOpt, 'detail');
  17776. } else if (seriesOpt.type === 'treemap') {
  17777. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  17778. each(seriesOpt.levels, function (opt) {
  17779. removeEC3NormalStatus(opt);
  17780. });
  17781. } else if (seriesOpt.type === 'tree') {
  17782. removeEC3NormalStatus(seriesOpt.leaves);
  17783. } // sunburst starts from ec4, so it does not need to compat levels.
  17784. }
  17785. function toArr(o) {
  17786. return isArray(o) ? o : o ? [o] : [];
  17787. }
  17788. function toObj(o) {
  17789. return (isArray(o) ? o[0] : o) || {};
  17790. }
  17791. function globalCompatStyle(option, isTheme) {
  17792. each$2(toArr(option.series), function (seriesOpt) {
  17793. isObject$1(seriesOpt) && processSeries(seriesOpt);
  17794. });
  17795. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  17796. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  17797. each$2(axes, function (axisName) {
  17798. each$2(toArr(option[axisName]), function (axisOpt) {
  17799. if (axisOpt) {
  17800. compatTextStyle(axisOpt, 'axisLabel');
  17801. compatTextStyle(axisOpt.axisPointer, 'label');
  17802. }
  17803. });
  17804. });
  17805. each$2(toArr(option.parallel), function (parallelOpt) {
  17806. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  17807. compatTextStyle(parallelAxisDefault, 'axisLabel');
  17808. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  17809. });
  17810. each$2(toArr(option.calendar), function (calendarOpt) {
  17811. convertNormalEmphasis(calendarOpt, 'itemStyle');
  17812. compatTextStyle(calendarOpt, 'dayLabel');
  17813. compatTextStyle(calendarOpt, 'monthLabel');
  17814. compatTextStyle(calendarOpt, 'yearLabel');
  17815. }); // radar.name.textStyle
  17816. each$2(toArr(option.radar), function (radarOpt) {
  17817. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  17818. if (radarOpt.name && radarOpt.axisName == null) {
  17819. radarOpt.axisName = radarOpt.name;
  17820. delete radarOpt.name;
  17821. if ("development" !== 'production') {
  17822. deprecateLog('name property in radar component has been changed to axisName');
  17823. }
  17824. }
  17825. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  17826. radarOpt.axisNameGap = radarOpt.nameGap;
  17827. delete radarOpt.nameGap;
  17828. if ("development" !== 'production') {
  17829. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  17830. }
  17831. }
  17832. if ("development" !== 'production') {
  17833. each$2(radarOpt.indicator, function (indicatorOpt) {
  17834. if (indicatorOpt.text) {
  17835. deprecateReplaceLog('text', 'name', 'radar.indicator');
  17836. }
  17837. });
  17838. }
  17839. });
  17840. each$2(toArr(option.geo), function (geoOpt) {
  17841. if (isObject$1(geoOpt)) {
  17842. compatEC3CommonStyles(geoOpt);
  17843. each$2(toArr(geoOpt.regions), function (regionObj) {
  17844. compatEC3CommonStyles(regionObj);
  17845. });
  17846. }
  17847. });
  17848. each$2(toArr(option.timeline), function (timelineOpt) {
  17849. compatEC3CommonStyles(timelineOpt);
  17850. convertNormalEmphasis(timelineOpt, 'label');
  17851. convertNormalEmphasis(timelineOpt, 'itemStyle');
  17852. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  17853. var data = timelineOpt.data;
  17854. isArray(data) && each(data, function (item) {
  17855. if (isObject(item)) {
  17856. convertNormalEmphasis(item, 'label');
  17857. convertNormalEmphasis(item, 'itemStyle');
  17858. }
  17859. });
  17860. });
  17861. each$2(toArr(option.toolbox), function (toolboxOpt) {
  17862. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  17863. each$2(toolboxOpt.feature, function (featureOpt) {
  17864. convertNormalEmphasis(featureOpt, 'iconStyle');
  17865. });
  17866. });
  17867. compatTextStyle(toObj(option.axisPointer), 'label');
  17868. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  17869. // storedLogs = {};
  17870. }
  17871. function get(opt, path) {
  17872. var pathArr = path.split(',');
  17873. var obj = opt;
  17874. for (var i = 0; i < pathArr.length; i++) {
  17875. obj = obj && obj[pathArr[i]];
  17876. if (obj == null) {
  17877. break;
  17878. }
  17879. }
  17880. return obj;
  17881. }
  17882. function set$1(opt, path, val, overwrite) {
  17883. var pathArr = path.split(',');
  17884. var obj = opt;
  17885. var key;
  17886. var i = 0;
  17887. for (; i < pathArr.length - 1; i++) {
  17888. key = pathArr[i];
  17889. if (obj[key] == null) {
  17890. obj[key] = {};
  17891. }
  17892. obj = obj[key];
  17893. }
  17894. if (overwrite || obj[pathArr[i]] == null) {
  17895. obj[pathArr[i]] = val;
  17896. }
  17897. }
  17898. function compatLayoutProperties(option) {
  17899. option && each(LAYOUT_PROPERTIES, function (prop) {
  17900. if (prop[0] in option && !(prop[1] in option)) {
  17901. option[prop[1]] = option[prop[0]];
  17902. }
  17903. });
  17904. }
  17905. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  17906. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  17907. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  17908. function compatBarItemStyle(option) {
  17909. var itemStyle = option && option.itemStyle;
  17910. if (itemStyle) {
  17911. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  17912. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  17913. var newName = BAR_ITEM_STYLE_MAP[i][0];
  17914. if (itemStyle[oldName] != null) {
  17915. itemStyle[newName] = itemStyle[oldName];
  17916. if ("development" !== 'production') {
  17917. deprecateReplaceLog(oldName, newName);
  17918. }
  17919. }
  17920. }
  17921. }
  17922. }
  17923. function compatPieLabel(option) {
  17924. if (!option) {
  17925. return;
  17926. }
  17927. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  17928. if ("development" !== 'production') {
  17929. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  17930. }
  17931. option.edgeDistance = option.margin;
  17932. }
  17933. }
  17934. function compatSunburstState(option) {
  17935. if (!option) {
  17936. return;
  17937. }
  17938. if (option.downplay && !option.blur) {
  17939. option.blur = option.downplay;
  17940. if ("development" !== 'production') {
  17941. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  17942. }
  17943. }
  17944. }
  17945. function compatGraphFocus(option) {
  17946. if (!option) {
  17947. return;
  17948. }
  17949. if (option.focusNodeAdjacency != null) {
  17950. option.emphasis = option.emphasis || {};
  17951. if (option.emphasis.focus == null) {
  17952. if ("development" !== 'production') {
  17953. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  17954. }
  17955. option.emphasis.focus = 'adjacency';
  17956. }
  17957. }
  17958. }
  17959. function traverseTree(data, cb) {
  17960. if (data) {
  17961. for (var i = 0; i < data.length; i++) {
  17962. cb(data[i]);
  17963. data[i] && traverseTree(data[i].children, cb);
  17964. }
  17965. }
  17966. }
  17967. function globalBackwardCompat(option, isTheme) {
  17968. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  17969. option.series = normalizeToArray(option.series);
  17970. each(option.series, function (seriesOpt) {
  17971. if (!isObject(seriesOpt)) {
  17972. return;
  17973. }
  17974. var seriesType = seriesOpt.type;
  17975. if (seriesType === 'line') {
  17976. if (seriesOpt.clipOverflow != null) {
  17977. seriesOpt.clip = seriesOpt.clipOverflow;
  17978. if ("development" !== 'production') {
  17979. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  17980. }
  17981. }
  17982. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  17983. if (seriesOpt.clockWise != null) {
  17984. seriesOpt.clockwise = seriesOpt.clockWise;
  17985. if ("development" !== 'production') {
  17986. deprecateReplaceLog('clockWise', 'clockwise');
  17987. }
  17988. }
  17989. compatPieLabel(seriesOpt.label);
  17990. var data = seriesOpt.data;
  17991. if (data && !isTypedArray(data)) {
  17992. for (var i = 0; i < data.length; i++) {
  17993. compatPieLabel(data[i]);
  17994. }
  17995. }
  17996. if (seriesOpt.hoverOffset != null) {
  17997. seriesOpt.emphasis = seriesOpt.emphasis || {};
  17998. if (seriesOpt.emphasis.scaleSize = null) {
  17999. if ("development" !== 'production') {
  18000. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18001. }
  18002. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18003. }
  18004. }
  18005. } else if (seriesType === 'gauge') {
  18006. var pointerColor = get(seriesOpt, 'pointer.color');
  18007. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18008. } else if (seriesType === 'bar') {
  18009. compatBarItemStyle(seriesOpt);
  18010. compatBarItemStyle(seriesOpt.backgroundStyle);
  18011. compatBarItemStyle(seriesOpt.emphasis);
  18012. var data = seriesOpt.data;
  18013. if (data && !isTypedArray(data)) {
  18014. for (var i = 0; i < data.length; i++) {
  18015. if (typeof data[i] === 'object') {
  18016. compatBarItemStyle(data[i]);
  18017. compatBarItemStyle(data[i] && data[i].emphasis);
  18018. }
  18019. }
  18020. }
  18021. } else if (seriesType === 'sunburst') {
  18022. var highlightPolicy = seriesOpt.highlightPolicy;
  18023. if (highlightPolicy) {
  18024. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18025. if (!seriesOpt.emphasis.focus) {
  18026. seriesOpt.emphasis.focus = highlightPolicy;
  18027. if ("development" !== 'production') {
  18028. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18029. }
  18030. }
  18031. }
  18032. compatSunburstState(seriesOpt);
  18033. traverseTree(seriesOpt.data, compatSunburstState);
  18034. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18035. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18036. } else if (seriesType === 'map') {
  18037. if (seriesOpt.mapType && !seriesOpt.map) {
  18038. if ("development" !== 'production') {
  18039. deprecateReplaceLog('mapType', 'map', 'map');
  18040. }
  18041. seriesOpt.map = seriesOpt.mapType;
  18042. }
  18043. if (seriesOpt.mapLocation) {
  18044. if ("development" !== 'production') {
  18045. deprecateLog('`mapLocation` is not used anymore.');
  18046. }
  18047. defaults(seriesOpt, seriesOpt.mapLocation);
  18048. }
  18049. }
  18050. if (seriesOpt.hoverAnimation != null) {
  18051. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18052. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18053. if ("development" !== 'production') {
  18054. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18055. }
  18056. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18057. }
  18058. }
  18059. compatLayoutProperties(seriesOpt);
  18060. }); // dataRange has changed to visualMap
  18061. if (option.dataRange) {
  18062. option.visualMap = option.dataRange;
  18063. }
  18064. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18065. var options = option[componentName];
  18066. if (options) {
  18067. if (!isArray(options)) {
  18068. options = [options];
  18069. }
  18070. each(options, function (option) {
  18071. compatLayoutProperties(option);
  18072. });
  18073. }
  18074. });
  18075. }
  18076. // data processing stage is blocked in stream.
  18077. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18078. // (2) Only register once when import repeatedly.
  18079. // Should be executed after series is filtered and before stack calculation.
  18080. function dataStack(ecModel) {
  18081. var stackInfoMap = createHashMap();
  18082. ecModel.eachSeries(function (seriesModel) {
  18083. var stack = seriesModel.get('stack'); // Compatible: when `stack` is set as '', do not stack.
  18084. if (stack) {
  18085. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18086. var data = seriesModel.getData();
  18087. var stackInfo = {
  18088. // Used for calculate axis extent automatically.
  18089. // TODO: Type getCalculationInfo return more specific type?
  18090. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18091. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18092. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18093. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18094. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18095. data: data,
  18096. seriesModel: seriesModel
  18097. }; // If stacked on axis that do not support data stack.
  18098. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18099. return;
  18100. }
  18101. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18102. stackInfoList.push(stackInfo);
  18103. }
  18104. });
  18105. stackInfoMap.each(calculateStack);
  18106. }
  18107. function calculateStack(stackInfoList) {
  18108. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18109. var resultVal = [];
  18110. var resultNaN = [NaN, NaN];
  18111. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18112. var targetData = targetStackInfo.data;
  18113. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18114. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign'; // Should not write on raw data, because stack series model list changes
  18115. // depending on legend selection.
  18116. targetData.modify(dims, function (v0, v1, dataIndex) {
  18117. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18118. // should also be NaN, to draw a appropriate belt area.
  18119. if (isNaN(sum)) {
  18120. return resultNaN;
  18121. }
  18122. var byValue;
  18123. var stackedDataRawIndex;
  18124. if (isStackedByIndex) {
  18125. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18126. } else {
  18127. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18128. } // If stackOver is NaN, chart view will render point on value start.
  18129. var stackedOver = NaN;
  18130. for (var j = idxInStack - 1; j >= 0; j--) {
  18131. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18132. if (!isStackedByIndex) {
  18133. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18134. }
  18135. if (stackedDataRawIndex >= 0) {
  18136. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18137. if (stackStrategy === 'all' // single stack group
  18138. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  18139. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  18140. ) {
  18141. // The sum has to be very small to be affected by the
  18142. // floating arithmetic problem. An incorrect result will probably
  18143. // cause axis min/max to be filtered incorrectly.
  18144. sum = addSafe(sum, val);
  18145. stackedOver = val;
  18146. break;
  18147. }
  18148. }
  18149. }
  18150. resultVal[0] = sum;
  18151. resultVal[1] = stackedOver;
  18152. return resultVal;
  18153. });
  18154. });
  18155. }
  18156. var SourceImpl =
  18157. /** @class */
  18158. function () {
  18159. function SourceImpl(fields) {
  18160. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18161. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18162. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18163. this.startIndex = fields.startIndex || 0;
  18164. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18165. this.metaRawOption = fields.metaRawOption;
  18166. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18167. if (dimensionsDefine) {
  18168. for (var i = 0; i < dimensionsDefine.length; i++) {
  18169. var dim = dimensionsDefine[i];
  18170. if (dim.type == null) {
  18171. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18172. dim.type = 'ordinal';
  18173. }
  18174. }
  18175. }
  18176. }
  18177. }
  18178. return SourceImpl;
  18179. }();
  18180. function isSourceInstance(val) {
  18181. return val instanceof SourceImpl;
  18182. }
  18183. /**
  18184. * Create a source from option.
  18185. * NOTE: Created source is immutable. Don't change any properties in it.
  18186. */
  18187. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18188. sourceFormat) {
  18189. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18190. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18191. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18192. var source = new SourceImpl({
  18193. data: sourceData,
  18194. sourceFormat: sourceFormat,
  18195. seriesLayoutBy: seriesLayoutBy,
  18196. dimensionsDefine: determined.dimensionsDefine,
  18197. startIndex: determined.startIndex,
  18198. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18199. metaRawOption: clone(thisMetaRawOption)
  18200. });
  18201. return source;
  18202. }
  18203. /**
  18204. * Wrap original series data for some compatibility cases.
  18205. */
  18206. function createSourceFromSeriesDataOption(data) {
  18207. return new SourceImpl({
  18208. data: data,
  18209. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18210. });
  18211. }
  18212. /**
  18213. * Clone source but excludes source data.
  18214. */
  18215. function cloneSourceShallow(source) {
  18216. return new SourceImpl({
  18217. data: source.data,
  18218. sourceFormat: source.sourceFormat,
  18219. seriesLayoutBy: source.seriesLayoutBy,
  18220. dimensionsDefine: clone(source.dimensionsDefine),
  18221. startIndex: source.startIndex,
  18222. dimensionsDetectedCount: source.dimensionsDetectedCount
  18223. });
  18224. }
  18225. /**
  18226. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18227. */
  18228. function detectSourceFormat(data) {
  18229. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18230. if (isTypedArray(data)) {
  18231. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18232. } else if (isArray(data)) {
  18233. // FIXME Whether tolerate null in top level array?
  18234. if (data.length === 0) {
  18235. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18236. }
  18237. for (var i = 0, len = data.length; i < len; i++) {
  18238. var item = data[i];
  18239. if (item == null) {
  18240. continue;
  18241. } else if (isArray(item)) {
  18242. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18243. break;
  18244. } else if (isObject(item)) {
  18245. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18246. break;
  18247. }
  18248. }
  18249. } else if (isObject(data)) {
  18250. for (var key in data) {
  18251. if (hasOwn(data, key) && isArrayLike(data[key])) {
  18252. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18253. break;
  18254. }
  18255. }
  18256. }
  18257. return sourceFormat;
  18258. }
  18259. /**
  18260. * Determine the source definitions from data standalone dimensions definitions
  18261. * are not specified.
  18262. */
  18263. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  18264. // {
  18265. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  18266. // }
  18267. // in `dataset` or `series`
  18268. dimensionsDefine) {
  18269. var dimensionsDetectedCount;
  18270. var startIndex; // PEDING: could data be null/undefined here?
  18271. // currently, if `dataset.source` not specified, error thrown.
  18272. // if `series.data` not specified, nothing rendered without error thrown.
  18273. // Should test these cases.
  18274. if (!data) {
  18275. return {
  18276. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18277. startIndex: startIndex,
  18278. dimensionsDetectedCount: dimensionsDetectedCount
  18279. };
  18280. }
  18281. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18282. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  18283. // Caution: consider a line with 5 string and 1 number,
  18284. // it still can not be sure it is a head, because the
  18285. // 5 string may be 5 values of category columns.
  18286. if (sourceHeader === 'auto' || sourceHeader == null) {
  18287. arrayRowsTravelFirst(function (val) {
  18288. // '-' is regarded as null/undefined.
  18289. if (val != null && val !== '-') {
  18290. if (isString(val)) {
  18291. startIndex == null && (startIndex = 1);
  18292. } else {
  18293. startIndex = 0;
  18294. }
  18295. } // 10 is an experience number, avoid long loop.
  18296. }, seriesLayoutBy, dataArrayRows, 10);
  18297. } else {
  18298. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  18299. }
  18300. if (!dimensionsDefine && startIndex === 1) {
  18301. dimensionsDefine = [];
  18302. arrayRowsTravelFirst(function (val, index) {
  18303. dimensionsDefine[index] = val != null ? val + '' : '';
  18304. }, seriesLayoutBy, dataArrayRows, Infinity);
  18305. }
  18306. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  18307. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18308. if (!dimensionsDefine) {
  18309. dimensionsDefine = objectRowsCollectDimensions(data);
  18310. }
  18311. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18312. if (!dimensionsDefine) {
  18313. dimensionsDefine = [];
  18314. each(data, function (colArr, key) {
  18315. dimensionsDefine.push(key);
  18316. });
  18317. }
  18318. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18319. var value0 = getDataItemValue(data[0]);
  18320. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  18321. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18322. if ("development" !== 'production') {
  18323. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18324. }
  18325. }
  18326. return {
  18327. startIndex: startIndex,
  18328. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18329. dimensionsDetectedCount: dimensionsDetectedCount
  18330. };
  18331. }
  18332. function objectRowsCollectDimensions(data) {
  18333. var firstIndex = 0;
  18334. var obj;
  18335. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18336. if (obj) {
  18337. var dimensions_1 = [];
  18338. each(obj, function (value, key) {
  18339. dimensions_1.push(key);
  18340. });
  18341. return dimensions_1;
  18342. }
  18343. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18344. // which is reasonable. But dimension name is duplicated.
  18345. // Returns undefined or an array contains only object without null/undefiend or string.
  18346. function normalizeDimensionsOption(dimensionsDefine) {
  18347. if (!dimensionsDefine) {
  18348. // The meaning of null/undefined is different from empty array.
  18349. return;
  18350. }
  18351. var nameMap = createHashMap();
  18352. return map(dimensionsDefine, function (rawItem, index) {
  18353. rawItem = isObject(rawItem) ? rawItem : {
  18354. name: rawItem
  18355. }; // Other fields will be discarded.
  18356. var item = {
  18357. name: rawItem.name,
  18358. displayName: rawItem.displayName,
  18359. type: rawItem.type
  18360. }; // User can set null in dimensions.
  18361. // We dont auto specify name, othewise a given name may
  18362. // cause it be refered unexpectedly.
  18363. if (item.name == null) {
  18364. return item;
  18365. } // Also consider number form like 2012.
  18366. item.name += ''; // User may also specify displayName.
  18367. // displayName will always exists except user not
  18368. // specified or dim name is not specified or detected.
  18369. // (A auto generated dim name will not be used as
  18370. // displayName).
  18371. if (item.displayName == null) {
  18372. item.displayName = item.name;
  18373. }
  18374. var exist = nameMap.get(item.name);
  18375. if (!exist) {
  18376. nameMap.set(item.name, {
  18377. count: 1
  18378. });
  18379. } else {
  18380. item.name += '-' + exist.count++;
  18381. }
  18382. return item;
  18383. });
  18384. }
  18385. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18386. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18387. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18388. cb(data[i] ? data[i][0] : null, i);
  18389. }
  18390. } else {
  18391. var value0 = data[0] || [];
  18392. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18393. cb(value0[i], i);
  18394. }
  18395. }
  18396. }
  18397. function shouldRetrieveDataByName(source) {
  18398. var sourceFormat = source.sourceFormat;
  18399. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  18400. }
  18401. /*
  18402. * Licensed to the Apache Software Foundation (ASF) under one
  18403. * or more contributor license agreements. See the NOTICE file
  18404. * distributed with this work for additional information
  18405. * regarding copyright ownership. The ASF licenses this file
  18406. * to you under the Apache License, Version 2.0 (the
  18407. * "License"); you may not use this file except in compliance
  18408. * with the License. You may obtain a copy of the License at
  18409. *
  18410. * http://www.apache.org/licenses/LICENSE-2.0
  18411. *
  18412. * Unless required by applicable law or agreed to in writing,
  18413. * software distributed under the License is distributed on an
  18414. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18415. * KIND, either express or implied. See the License for the
  18416. * specific language governing permissions and limitations
  18417. * under the License.
  18418. */
  18419. /**
  18420. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18421. */
  18422. /*
  18423. * Licensed to the Apache Software Foundation (ASF) under one
  18424. * or more contributor license agreements. See the NOTICE file
  18425. * distributed with this work for additional information
  18426. * regarding copyright ownership. The ASF licenses this file
  18427. * to you under the Apache License, Version 2.0 (the
  18428. * "License"); you may not use this file except in compliance
  18429. * with the License. You may obtain a copy of the License at
  18430. *
  18431. * http://www.apache.org/licenses/LICENSE-2.0
  18432. *
  18433. * Unless required by applicable law or agreed to in writing,
  18434. * software distributed under the License is distributed on an
  18435. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18436. * KIND, either express or implied. See the License for the
  18437. * specific language governing permissions and limitations
  18438. * under the License.
  18439. */
  18440. var _a, _b, _c; // TODO
  18441. var providerMethods;
  18442. var mountMethods;
  18443. /**
  18444. * If normal array used, mutable chunk size is supported.
  18445. * If typed array used, chunk size must be fixed.
  18446. */
  18447. var DefaultDataProvider =
  18448. /** @class */
  18449. function () {
  18450. function DefaultDataProvider(sourceParam, dimSize) {
  18451. // let source: Source;
  18452. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  18453. this._source = source;
  18454. var data = this._data = source.data; // Typed array. TODO IE10+?
  18455. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18456. if ("development" !== 'production') {
  18457. if (dimSize == null) {
  18458. throw new Error('Typed array data must specify dimension size');
  18459. }
  18460. }
  18461. this._offset = 0;
  18462. this._dimSize = dimSize;
  18463. this._data = data;
  18464. }
  18465. mountMethods(this, data, source);
  18466. }
  18467. DefaultDataProvider.prototype.getSource = function () {
  18468. return this._source;
  18469. };
  18470. DefaultDataProvider.prototype.count = function () {
  18471. return 0;
  18472. };
  18473. DefaultDataProvider.prototype.getItem = function (idx, out) {
  18474. return;
  18475. };
  18476. DefaultDataProvider.prototype.appendData = function (newData) {};
  18477. DefaultDataProvider.prototype.clean = function () {};
  18478. DefaultDataProvider.protoInitialize = function () {
  18479. // PENDING: To avoid potential incompat (e.g., prototype
  18480. // is visited somewhere), still init them on prototype.
  18481. var proto = DefaultDataProvider.prototype;
  18482. proto.pure = false;
  18483. proto.persistent = true;
  18484. }();
  18485. DefaultDataProvider.internalField = function () {
  18486. var _a;
  18487. mountMethods = function (provider, data, source) {
  18488. var sourceFormat = source.sourceFormat;
  18489. var seriesLayoutBy = source.seriesLayoutBy;
  18490. var startIndex = source.startIndex;
  18491. var dimsDef = source.dimensionsDefine;
  18492. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18493. if ("development" !== 'production') {
  18494. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18495. }
  18496. extend(provider, methods);
  18497. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18498. provider.getItem = getItemForTypedArray;
  18499. provider.count = countForTypedArray;
  18500. provider.fillStorage = fillStorageForTypedArray;
  18501. } else {
  18502. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  18503. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  18504. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  18505. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  18506. }
  18507. };
  18508. var getItemForTypedArray = function (idx, out) {
  18509. idx = idx - this._offset;
  18510. out = out || [];
  18511. var data = this._data;
  18512. var dimSize = this._dimSize;
  18513. var offset = dimSize * idx;
  18514. for (var i = 0; i < dimSize; i++) {
  18515. out[i] = data[offset + i];
  18516. }
  18517. return out;
  18518. };
  18519. var fillStorageForTypedArray = function (start, end, storage, extent) {
  18520. var data = this._data;
  18521. var dimSize = this._dimSize;
  18522. for (var dim = 0; dim < dimSize; dim++) {
  18523. var dimExtent = extent[dim];
  18524. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  18525. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  18526. var count = end - start;
  18527. var arr = storage[dim];
  18528. for (var i = 0; i < count; i++) {
  18529. // appendData with TypedArray will always do replace in provider.
  18530. var val = data[i * dimSize + dim];
  18531. arr[start + i] = val;
  18532. val < min && (min = val);
  18533. val > max && (max = val);
  18534. }
  18535. dimExtent[0] = min;
  18536. dimExtent[1] = max;
  18537. }
  18538. };
  18539. var countForTypedArray = function () {
  18540. return this._data ? this._data.length / this._dimSize : 0;
  18541. };
  18542. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  18543. pure: true,
  18544. appendData: appendDataSimply
  18545. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  18546. pure: true,
  18547. appendData: function () {
  18548. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18549. }
  18550. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  18551. pure: true,
  18552. appendData: appendDataSimply
  18553. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  18554. pure: true,
  18555. appendData: function (newData) {
  18556. var data = this._data;
  18557. each(newData, function (newCol, key) {
  18558. var oldCol = data[key] || (data[key] = []);
  18559. for (var i = 0; i < (newCol || []).length; i++) {
  18560. oldCol.push(newCol[i]);
  18561. }
  18562. });
  18563. }
  18564. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  18565. appendData: appendDataSimply
  18566. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  18567. persistent: false,
  18568. pure: true,
  18569. appendData: function (newData) {
  18570. if ("development" !== 'production') {
  18571. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  18572. }
  18573. this._data = newData;
  18574. },
  18575. // Clean self if data is already used.
  18576. clean: function () {
  18577. // PENDING
  18578. this._offset += this.count();
  18579. this._data = null;
  18580. }
  18581. }, _a);
  18582. function appendDataSimply(newData) {
  18583. for (var i = 0; i < newData.length; i++) {
  18584. this._data.push(newData[i]);
  18585. }
  18586. }
  18587. }();
  18588. return DefaultDataProvider;
  18589. }();
  18590. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  18591. return rawData[idx];
  18592. };
  18593. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  18594. return rawData[idx + startIndex];
  18595. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  18596. idx += startIndex;
  18597. var item = out || [];
  18598. var data = rawData;
  18599. for (var i = 0; i < data.length; i++) {
  18600. var row = data[i];
  18601. item[i] = row ? row[idx] : null;
  18602. }
  18603. return item;
  18604. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  18605. var item = out || [];
  18606. for (var i = 0; i < dimsDef.length; i++) {
  18607. var dimName = dimsDef[i].name;
  18608. if ("development" !== 'production') {
  18609. if (dimName == null) {
  18610. throw new Error();
  18611. }
  18612. }
  18613. var col = rawData[dimName];
  18614. item[i] = col ? col[idx] : null;
  18615. }
  18616. return item;
  18617. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  18618. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  18619. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18620. if ("development" !== 'production') {
  18621. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18622. }
  18623. return method;
  18624. }
  18625. var countSimply = function (rawData, startIndex, dimsDef) {
  18626. return rawData.length;
  18627. };
  18628. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  18629. return Math.max(0, rawData.length - startIndex);
  18630. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  18631. var row = rawData[0];
  18632. return row ? Math.max(0, row.length - startIndex) : 0;
  18633. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  18634. var dimName = dimsDef[0].name;
  18635. if ("development" !== 'production') {
  18636. if (dimName == null) {
  18637. throw new Error();
  18638. }
  18639. }
  18640. var col = rawData[dimName];
  18641. return col ? col.length : 0;
  18642. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  18643. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  18644. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18645. if ("development" !== 'production') {
  18646. assert(method, 'Do not suppport count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18647. }
  18648. return method;
  18649. }
  18650. var getRawValueSimply = function (dataItem, dimIndex, property) {
  18651. return dataItem[dimIndex];
  18652. };
  18653. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  18654. return dataItem[property];
  18655. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  18656. // FIXME: In some case (markpoint in geo (geo-map.html)),
  18657. // dataItem is {coord: [...]}
  18658. var value = getDataItemValue(dataItem);
  18659. return !(value instanceof Array) ? value : value[dimIndex];
  18660. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  18661. function getRawSourceValueGetter(sourceFormat) {
  18662. var method = rawSourceValueGetterMap[sourceFormat];
  18663. if ("development" !== 'production') {
  18664. assert(method, 'Do not suppport get value on "' + sourceFormat + '".');
  18665. }
  18666. return method;
  18667. }
  18668. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  18669. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  18670. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18671. // Consider persistent.
  18672. // Caution: why use raw value to display on label or tooltip?
  18673. // A reason is to avoid format. For example time value we do not know
  18674. // how to format is expected. More over, if stack is used, calculated
  18675. // value may be 0.91000000001, which have brings trouble to display.
  18676. // TODO: consider how to treat null/undefined/NaN when display?
  18677. function retrieveRawValue(data, dataIndex, // If dimIndex is null/undefined, return OptionDataItem.
  18678. // Otherwise, return OptionDataValue.
  18679. dim) {
  18680. if (!data) {
  18681. return;
  18682. } // Consider data may be not persistent.
  18683. var dataItem = data.getRawDataItem(dataIndex);
  18684. if (dataItem == null) {
  18685. return;
  18686. }
  18687. var store = data.getStore();
  18688. var sourceFormat = store.getSource().sourceFormat;
  18689. if (dim != null) {
  18690. var dimIndex = data.getDimensionIndex(dim);
  18691. var property = store.getDimensionProperty(dimIndex);
  18692. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  18693. } else {
  18694. var result = dataItem;
  18695. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18696. result = getDataItemValue(dataItem);
  18697. }
  18698. return result;
  18699. }
  18700. }
  18701. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18702. var DataFormatMixin =
  18703. /** @class */
  18704. function () {
  18705. function DataFormatMixin() {}
  18706. /**
  18707. * Get params for formatter
  18708. */
  18709. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  18710. var data = this.getData(dataType);
  18711. var rawValue = this.getRawValue(dataIndex, dataType);
  18712. var rawDataIndex = data.getRawIndex(dataIndex);
  18713. var name = data.getName(dataIndex);
  18714. var itemOpt = data.getRawDataItem(dataIndex);
  18715. var style = data.getItemVisual(dataIndex, 'style');
  18716. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  18717. var borderColor = style && style.stroke;
  18718. var mainType = this.mainType;
  18719. var isSeries = mainType === 'series';
  18720. var userOutput = data.userOutput && data.userOutput.get();
  18721. return {
  18722. componentType: mainType,
  18723. componentSubType: this.subType,
  18724. componentIndex: this.componentIndex,
  18725. seriesType: isSeries ? this.subType : null,
  18726. seriesIndex: this.seriesIndex,
  18727. seriesId: isSeries ? this.id : null,
  18728. seriesName: isSeries ? this.name : null,
  18729. name: name,
  18730. dataIndex: rawDataIndex,
  18731. data: itemOpt,
  18732. dataType: dataType,
  18733. value: rawValue,
  18734. color: color,
  18735. borderColor: borderColor,
  18736. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  18737. encode: userOutput ? userOutput.encode : null,
  18738. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18739. $vars: ['seriesName', 'name', 'value']
  18740. };
  18741. };
  18742. /**
  18743. * Format label
  18744. * @param dataIndex
  18745. * @param status 'normal' by default
  18746. * @param dataType
  18747. * @param labelDimIndex Only used in some chart that
  18748. * use formatter in different dimensions, like radar.
  18749. * @param formatter Formatter given outside.
  18750. * @return return null/undefined if no formatter
  18751. */
  18752. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  18753. status = status || 'normal';
  18754. var data = this.getData(dataType);
  18755. var params = this.getDataParams(dataIndex, dataType);
  18756. if (extendParams) {
  18757. params.value = extendParams.interpolatedValue;
  18758. }
  18759. if (labelDimIndex != null && isArray(params.value)) {
  18760. params.value = params.value[labelDimIndex];
  18761. }
  18762. if (!formatter) {
  18763. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  18764. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  18765. }
  18766. if (isFunction(formatter)) {
  18767. params.status = status;
  18768. params.dimensionIndex = labelDimIndex;
  18769. return formatter(params);
  18770. } else if (isString(formatter)) {
  18771. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  18772. // Do not support '}' in dim name util have to.
  18773. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  18774. var len = dimStr.length;
  18775. var dimLoose = dimStr;
  18776. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  18777. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  18778. if ("development" !== 'production') {
  18779. if (isNaN(dimLoose)) {
  18780. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  18781. }
  18782. }
  18783. }
  18784. var val = retrieveRawValue(data, dataIndex, dimLoose);
  18785. if (extendParams && isArray(extendParams.interpolatedValue)) {
  18786. var dimIndex = data.getDimensionIndex(dimLoose);
  18787. if (dimIndex >= 0) {
  18788. val = extendParams.interpolatedValue[dimIndex];
  18789. }
  18790. }
  18791. return val != null ? val + '' : '';
  18792. });
  18793. }
  18794. };
  18795. /**
  18796. * Get raw value in option
  18797. */
  18798. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  18799. return retrieveRawValue(this.getData(dataType), idx);
  18800. };
  18801. /**
  18802. * Should be implemented.
  18803. * @param {number} dataIndex
  18804. * @param {boolean} [multipleSeries=false]
  18805. * @param {string} [dataType]
  18806. */
  18807. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  18808. // Empty function
  18809. return;
  18810. };
  18811. return DataFormatMixin;
  18812. }();
  18813. /**
  18814. * @param {Object} define
  18815. * @return See the return of `createTask`.
  18816. */
  18817. function createTask(define) {
  18818. return new Task(define);
  18819. }
  18820. var Task =
  18821. /** @class */
  18822. function () {
  18823. function Task(define) {
  18824. define = define || {};
  18825. this._reset = define.reset;
  18826. this._plan = define.plan;
  18827. this._count = define.count;
  18828. this._onDirty = define.onDirty;
  18829. this._dirty = true;
  18830. }
  18831. /**
  18832. * @param step Specified step.
  18833. * @param skip Skip customer perform call.
  18834. * @param modBy Sampling window size.
  18835. * @param modDataCount Sampling count.
  18836. * @return whether unfinished.
  18837. */
  18838. Task.prototype.perform = function (performArgs) {
  18839. var upTask = this._upstream;
  18840. var skip = performArgs && performArgs.skip; // TODO some refactor.
  18841. // Pull data. Must pull data each time, because context.data
  18842. // may be updated by Series.setData.
  18843. if (this._dirty && upTask) {
  18844. var context = this.context;
  18845. context.data = context.outputData = upTask.context.outputData;
  18846. }
  18847. if (this.__pipeline) {
  18848. this.__pipeline.currentTask = this;
  18849. }
  18850. var planResult;
  18851. if (this._plan && !skip) {
  18852. planResult = this._plan(this.context);
  18853. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  18854. // elements uniformed distributed when progress, especially when moving or zooming.
  18855. var lastModBy = normalizeModBy(this._modBy);
  18856. var lastModDataCount = this._modDataCount || 0;
  18857. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  18858. var modDataCount = performArgs && performArgs.modDataCount || 0;
  18859. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  18860. planResult = 'reset';
  18861. }
  18862. function normalizeModBy(val) {
  18863. !(val >= 1) && (val = 1); // jshint ignore:line
  18864. return val;
  18865. }
  18866. var forceFirstProgress;
  18867. if (this._dirty || planResult === 'reset') {
  18868. this._dirty = false;
  18869. forceFirstProgress = this._doReset(skip);
  18870. }
  18871. this._modBy = modBy;
  18872. this._modDataCount = modDataCount;
  18873. var step = performArgs && performArgs.step;
  18874. if (upTask) {
  18875. if ("development" !== 'production') {
  18876. assert(upTask._outputDueEnd != null);
  18877. }
  18878. this._dueEnd = upTask._outputDueEnd;
  18879. } // DataTask or overallTask
  18880. else {
  18881. if ("development" !== 'production') {
  18882. assert(!this._progress || this._count);
  18883. }
  18884. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18885. } // Note: Stubs, that its host overall task let it has progress, has progress.
  18886. // If no progress, pass index from upstream to downstream each time plan called.
  18887. if (this._progress) {
  18888. var start = this._dueIndex;
  18889. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  18890. if (!skip && (forceFirstProgress || start < end)) {
  18891. var progress = this._progress;
  18892. if (isArray(progress)) {
  18893. for (var i = 0; i < progress.length; i++) {
  18894. this._doProgress(progress[i], start, end, modBy, modDataCount);
  18895. }
  18896. } else {
  18897. this._doProgress(progress, start, end, modBy, modDataCount);
  18898. }
  18899. }
  18900. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  18901. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  18902. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  18903. if ("development" !== 'production') {
  18904. // ??? Can not rollback.
  18905. assert(outputDueEnd >= this._outputDueEnd);
  18906. }
  18907. this._outputDueEnd = outputDueEnd;
  18908. } else {
  18909. // (1) Some overall task has no progress.
  18910. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  18911. // This should always be performed so it can be passed to downstream.
  18912. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  18913. }
  18914. return this.unfinished();
  18915. };
  18916. Task.prototype.dirty = function () {
  18917. this._dirty = true;
  18918. this._onDirty && this._onDirty(this.context);
  18919. };
  18920. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  18921. iterator.reset(start, end, modBy, modDataCount);
  18922. this._callingProgress = progress;
  18923. this._callingProgress({
  18924. start: start,
  18925. end: end,
  18926. count: end - start,
  18927. next: iterator.next
  18928. }, this.context);
  18929. };
  18930. Task.prototype._doReset = function (skip) {
  18931. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  18932. this._settedOutputEnd = null;
  18933. var progress;
  18934. var forceFirstProgress;
  18935. if (!skip && this._reset) {
  18936. progress = this._reset(this.context);
  18937. if (progress && progress.progress) {
  18938. forceFirstProgress = progress.forceFirstProgress;
  18939. progress = progress.progress;
  18940. } // To simplify no progress checking, array must has item.
  18941. if (isArray(progress) && !progress.length) {
  18942. progress = null;
  18943. }
  18944. }
  18945. this._progress = progress;
  18946. this._modBy = this._modDataCount = null;
  18947. var downstream = this._downstream;
  18948. downstream && downstream.dirty();
  18949. return forceFirstProgress;
  18950. };
  18951. Task.prototype.unfinished = function () {
  18952. return this._progress && this._dueIndex < this._dueEnd;
  18953. };
  18954. /**
  18955. * @param downTask The downstream task.
  18956. * @return The downstream task.
  18957. */
  18958. Task.prototype.pipe = function (downTask) {
  18959. if ("development" !== 'production') {
  18960. assert(downTask && !downTask._disposed && downTask !== this);
  18961. } // If already downstream, do not dirty downTask.
  18962. if (this._downstream !== downTask || this._dirty) {
  18963. this._downstream = downTask;
  18964. downTask._upstream = this;
  18965. downTask.dirty();
  18966. }
  18967. };
  18968. Task.prototype.dispose = function () {
  18969. if (this._disposed) {
  18970. return;
  18971. }
  18972. this._upstream && (this._upstream._downstream = null);
  18973. this._downstream && (this._downstream._upstream = null);
  18974. this._dirty = false;
  18975. this._disposed = true;
  18976. };
  18977. Task.prototype.getUpstream = function () {
  18978. return this._upstream;
  18979. };
  18980. Task.prototype.getDownstream = function () {
  18981. return this._downstream;
  18982. };
  18983. Task.prototype.setOutputEnd = function (end) {
  18984. // This only happend in dataTask, dataZoom, map, currently.
  18985. // where dataZoom do not set end each time, but only set
  18986. // when reset. So we should record the setted end, in case
  18987. // that the stub of dataZoom perform again and earse the
  18988. // setted end by upstream.
  18989. this._outputDueEnd = this._settedOutputEnd = end;
  18990. };
  18991. return Task;
  18992. }();
  18993. var iterator = function () {
  18994. var end;
  18995. var current;
  18996. var modBy;
  18997. var modDataCount;
  18998. var winCount;
  18999. var it = {
  19000. reset: function (s, e, sStep, sCount) {
  19001. current = s;
  19002. end = e;
  19003. modBy = sStep;
  19004. modDataCount = sCount;
  19005. winCount = Math.ceil(modDataCount / modBy);
  19006. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19007. }
  19008. };
  19009. return it;
  19010. function sequentialNext() {
  19011. return current < end ? current++ : null;
  19012. }
  19013. function modNext() {
  19014. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19015. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19016. // Use normal linear rendering mode.
  19017. : current;
  19018. current++;
  19019. return result;
  19020. }
  19021. }(); ///////////////////////////////////////////////////////////
  19022. // For stream debug (Should be commented out after used!)
  19023. // @usage: printTask(this, 'begin');
  19024. // @usage: printTask(this, null, {someExtraProp});
  19025. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19026. //
  19027. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19028. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19029. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19030. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19031. // let props = [];
  19032. // if (task.__pipeline) {
  19033. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19034. // props.push({text: '__idxInPipeline/total', value: val});
  19035. // } else {
  19036. // let stubCount = 0;
  19037. // task.agentStubMap.each(() => stubCount++);
  19038. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19039. // }
  19040. // props.push({text: 'uid', value: task.uidDebug});
  19041. // if (task.__pipeline) {
  19042. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19043. // task.agent && props.push(
  19044. // {text: 'stubFor', value: task.agent.uidDebug}
  19045. // );
  19046. // }
  19047. // props.push(
  19048. // {text: 'dirty', value: task._dirty},
  19049. // {text: 'dueIndex', value: task._dueIndex},
  19050. // {text: 'dueEnd', value: task._dueEnd},
  19051. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19052. // );
  19053. // if (extra) {
  19054. // Object.keys(extra).forEach(key => {
  19055. // props.push({text: key, value: extra[key]});
  19056. // });
  19057. // }
  19058. // let args = ['color: blue'];
  19059. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19060. // args.push('color: green', 'color: red'),
  19061. // `${item.text}: %c${item.value}`
  19062. // )).join('%c, ');
  19063. // console.log.apply(console, [msg].concat(args));
  19064. // // console.log(this);
  19065. // };
  19066. // window.printPipeline = function (task: any, prefix: string) {
  19067. // const pipeline = task.__pipeline;
  19068. // let currTask = pipeline.head;
  19069. // while (currTask) {
  19070. // window.printTask(currTask, prefix);
  19071. // currTask = currTask._downstream;
  19072. // }
  19073. // };
  19074. // window.showChain = function (chainHeadTask) {
  19075. // var chain = [];
  19076. // var task = chainHeadTask;
  19077. // while (task) {
  19078. // chain.push({
  19079. // task: task,
  19080. // up: task._upstream,
  19081. // down: task._downstream,
  19082. // idxInPipeline: task.__idxInPipeline
  19083. // });
  19084. // task = task._downstream;
  19085. // }
  19086. // return chain;
  19087. // };
  19088. // window.findTaskInChain = function (task, chainHeadTask) {
  19089. // let chain = window.showChain(chainHeadTask);
  19090. // let result = [];
  19091. // for (let i = 0; i < chain.length; i++) {
  19092. // let chainItem = chain[i];
  19093. // if (chainItem.task === task) {
  19094. // result.push(i);
  19095. // }
  19096. // }
  19097. // return result;
  19098. // };
  19099. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19100. // let chainA = window.showChain(chainHeadTaskA);
  19101. // for (let i = 0; i < chainA.length; i++) {
  19102. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19103. // }
  19104. // };
  19105. /**
  19106. * Convert raw the value in to inner value in List.
  19107. *
  19108. * [Performance sensitive]
  19109. *
  19110. * [Caution]: this is the key logic of user value parser.
  19111. * For backward compatibiliy, do not modify it until have to!
  19112. */
  19113. function parseDataValue(value, // For high performance, do not omit the second param.
  19114. opt) {
  19115. // Performance sensitive.
  19116. var dimType = opt && opt.type;
  19117. if (dimType === 'ordinal') {
  19118. // If given value is a category string
  19119. return value;
  19120. }
  19121. if (dimType === 'time' // spead up when using timestamp
  19122. && !isNumber(value) && value != null && value !== '-') {
  19123. value = +parseDate(value);
  19124. } // dimType defaults 'number'.
  19125. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19126. // parse to NaN.
  19127. // number-like string (like ' 123 ') can be converted to a number.
  19128. // where null/undefined or other string will be converted to NaN.
  19129. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19130. // If object, also parse to NaN
  19131. : +value;
  19132. }
  19133. var valueParserMap = createHashMap({
  19134. 'number': function (val) {
  19135. // Do not use `numericToNumber` here. We have by defualt `numericToNumber`.
  19136. // Here the number parser can have loose rule:
  19137. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19138. return parseFloat(val);
  19139. },
  19140. 'time': function (val) {
  19141. // return timestamp.
  19142. return +parseDate(val);
  19143. },
  19144. 'trim': function (val) {
  19145. return isString(val) ? trim(val) : val;
  19146. }
  19147. });
  19148. /**
  19149. * TODO: disable writable.
  19150. * This structure will be exposed to users.
  19151. */
  19152. var ExternalSource =
  19153. /** @class */
  19154. function () {
  19155. function ExternalSource() {}
  19156. ExternalSource.prototype.getRawData = function () {
  19157. // Only built-in transform available.
  19158. throw new Error('not supported');
  19159. };
  19160. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  19161. // Only built-in transform available.
  19162. throw new Error('not supported');
  19163. };
  19164. ExternalSource.prototype.cloneRawData = function () {
  19165. return;
  19166. };
  19167. /**
  19168. * @return If dimension not found, return null/undefined.
  19169. */
  19170. ExternalSource.prototype.getDimensionInfo = function (dim) {
  19171. return;
  19172. };
  19173. /**
  19174. * dimensions defined if and only if either:
  19175. * (a) dataset.dimensions are declared.
  19176. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  19177. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  19178. * the defined dimensions.
  19179. * Otherwise, `dimensionInfoAll` is determined by data columns.
  19180. * @return Always return an array (even empty array).
  19181. */
  19182. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  19183. return;
  19184. };
  19185. ExternalSource.prototype.count = function () {
  19186. return;
  19187. };
  19188. /**
  19189. * Only support by dimension index.
  19190. * No need to support by dimension name in transform function,
  19191. * becuase transform function is not case-specific, no need to use name literally.
  19192. */
  19193. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  19194. return;
  19195. };
  19196. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  19197. return;
  19198. };
  19199. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  19200. return parseDataValue(rawVal, dimInfo);
  19201. };
  19202. return ExternalSource;
  19203. }();
  19204. function createExternalSource(internalSource, externalTransform) {
  19205. var extSource = new ExternalSource();
  19206. var data = internalSource.data;
  19207. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  19208. var sourceHeaderCount = internalSource.startIndex;
  19209. var errMsg = '';
  19210. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  19211. // For the logic simplicity in transformer, only 'culumn' is
  19212. // supported in data transform. Otherwise, the `dimensionsDefine`
  19213. // might be detected by 'row', which probably confuses users.
  19214. if ("development" !== 'production') {
  19215. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  19216. }
  19217. throwError(errMsg);
  19218. } // [MEMO]
  19219. // Create a new dimensions structure for exposing.
  19220. // Do not expose all dimension info to users directly.
  19221. // Becuase the dimension is probably auto detected from data and not might reliable.
  19222. // Should not lead the transformers to think that is relialbe and return it.
  19223. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19224. var dimensions = [];
  19225. var dimsByName = {};
  19226. var dimsDef = internalSource.dimensionsDefine;
  19227. if (dimsDef) {
  19228. each(dimsDef, function (dimDef, idx) {
  19229. var name = dimDef.name;
  19230. var dimDefExt = {
  19231. index: idx,
  19232. name: name,
  19233. displayName: dimDef.displayName
  19234. };
  19235. dimensions.push(dimDefExt); // Users probably not sepcify dimension name. For simplicity, data transform
  19236. // do not generate dimension name.
  19237. if (name != null) {
  19238. // Dimension name should not be duplicated.
  19239. // For simplicity, data transform forbid name duplication, do not generate
  19240. // new name like module `completeDimensions.ts` did, but just tell users.
  19241. var errMsg_1 = '';
  19242. if (hasOwn(dimsByName, name)) {
  19243. if ("development" !== 'production') {
  19244. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  19245. }
  19246. throwError(errMsg_1);
  19247. }
  19248. dimsByName[name] = dimDefExt;
  19249. }
  19250. });
  19251. } // If dimension definitions are not defined and can not be detected.
  19252. // e.g., pure data `[[11, 22], ...]`.
  19253. else {
  19254. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  19255. // Do not generete name or anything others. The consequence process in
  19256. // `transform` or `series` probably have there own name generation strategry.
  19257. dimensions.push({
  19258. index: i
  19259. });
  19260. }
  19261. } // Implement public methods:
  19262. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19263. if (externalTransform.__isBuiltIn) {
  19264. extSource.getRawDataItem = function (dataIndex) {
  19265. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19266. };
  19267. extSource.getRawData = bind(getRawData, null, internalSource);
  19268. }
  19269. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  19270. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19271. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  19272. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  19273. extSource.retrieveValue = function (dataIndex, dimIndex) {
  19274. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19275. return retrieveValueFromItem(rawItem, dimIndex);
  19276. };
  19277. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  19278. if (dataItem == null) {
  19279. return;
  19280. }
  19281. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  19282. if (dimDef) {
  19283. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  19284. }
  19285. };
  19286. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  19287. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  19288. return extSource;
  19289. }
  19290. function getRawData(upstream) {
  19291. var sourceFormat = upstream.sourceFormat;
  19292. if (!isSupportedSourceFormat(sourceFormat)) {
  19293. var errMsg = '';
  19294. if ("development" !== 'production') {
  19295. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  19296. }
  19297. throwError(errMsg);
  19298. }
  19299. return upstream.data;
  19300. }
  19301. function cloneRawData(upstream) {
  19302. var sourceFormat = upstream.sourceFormat;
  19303. var data = upstream.data;
  19304. if (!isSupportedSourceFormat(sourceFormat)) {
  19305. var errMsg = '';
  19306. if ("development" !== 'production') {
  19307. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  19308. }
  19309. throwError(errMsg);
  19310. }
  19311. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19312. var result = [];
  19313. for (var i = 0, len = data.length; i < len; i++) {
  19314. // Not strictly clone for performance
  19315. result.push(data[i].slice());
  19316. }
  19317. return result;
  19318. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19319. var result = [];
  19320. for (var i = 0, len = data.length; i < len; i++) {
  19321. // Not strictly clone for performance
  19322. result.push(extend({}, data[i]));
  19323. }
  19324. return result;
  19325. }
  19326. }
  19327. function getDimensionInfo(dimensions, dimsByName, dim) {
  19328. if (dim == null) {
  19329. return;
  19330. } // Keep the same logic as `List::getDimension` did.
  19331. if (isNumber(dim) // If being a number-like string but not being defined a dimension name.
  19332. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  19333. return dimensions[dim];
  19334. } else if (hasOwn(dimsByName, dim)) {
  19335. return dimsByName[dim];
  19336. }
  19337. }
  19338. function cloneAllDimensionInfo(dimensions) {
  19339. return clone(dimensions);
  19340. }
  19341. var externalTransformMap = createHashMap();
  19342. function registerExternalTransform(externalTransform) {
  19343. externalTransform = clone(externalTransform);
  19344. var type = externalTransform.type;
  19345. var errMsg = '';
  19346. if (!type) {
  19347. if ("development" !== 'production') {
  19348. errMsg = 'Must have a `type` when `registerTransform`.';
  19349. }
  19350. throwError(errMsg);
  19351. }
  19352. var typeParsed = type.split(':');
  19353. if (typeParsed.length !== 2) {
  19354. if ("development" !== 'production') {
  19355. errMsg = 'Name must include namespace like "ns:regression".';
  19356. }
  19357. throwError(errMsg);
  19358. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  19359. // be called directly via 'xxx' rather than 'echarts:xxx'.
  19360. var isBuiltIn = false;
  19361. if (typeParsed[0] === 'echarts') {
  19362. type = typeParsed[1];
  19363. isBuiltIn = true;
  19364. }
  19365. externalTransform.__isBuiltIn = isBuiltIn;
  19366. externalTransformMap.set(type, externalTransform);
  19367. }
  19368. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  19369. var pipedTransOption = normalizeToArray(rawTransOption);
  19370. var pipeLen = pipedTransOption.length;
  19371. var errMsg = '';
  19372. if (!pipeLen) {
  19373. if ("development" !== 'production') {
  19374. errMsg = 'If `transform` declared, it should at least contain one transform.';
  19375. }
  19376. throwError(errMsg);
  19377. }
  19378. for (var i = 0, len = pipeLen; i < len; i++) {
  19379. var transOption = pipedTransOption[i];
  19380. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  19381. // piped transform only support single output, except the last one.
  19382. if (i !== len - 1) {
  19383. sourceList.length = Math.max(sourceList.length, 1);
  19384. }
  19385. }
  19386. return sourceList;
  19387. }
  19388. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  19389. pipeIndex) {
  19390. var errMsg = '';
  19391. if (!upSourceList.length) {
  19392. if ("development" !== 'production') {
  19393. errMsg = 'Must have at least one upstream dataset.';
  19394. }
  19395. throwError(errMsg);
  19396. }
  19397. if (!isObject(transOption)) {
  19398. if ("development" !== 'production') {
  19399. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  19400. }
  19401. throwError(errMsg);
  19402. }
  19403. var transType = transOption.type;
  19404. var externalTransform = externalTransformMap.get(transType);
  19405. if (!externalTransform) {
  19406. if ("development" !== 'production') {
  19407. errMsg = 'Can not find transform on type "' + transType + '".';
  19408. }
  19409. throwError(errMsg);
  19410. } // Prepare source
  19411. var extUpSourceList = map(upSourceList, function (upSource) {
  19412. return createExternalSource(upSource, externalTransform);
  19413. });
  19414. var resultList = normalizeToArray(externalTransform.transform({
  19415. upstream: extUpSourceList[0],
  19416. upstreamList: extUpSourceList,
  19417. config: clone(transOption.config)
  19418. }));
  19419. if ("development" !== 'production') {
  19420. if (transOption.print) {
  19421. var printStrArr = map(resultList, function (extSource) {
  19422. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  19423. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  19424. }).join('\n');
  19425. log(printStrArr);
  19426. }
  19427. }
  19428. return map(resultList, function (result, resultIndex) {
  19429. var errMsg = '';
  19430. if (!isObject(result)) {
  19431. if ("development" !== 'production') {
  19432. errMsg = 'A transform should not return some empty results.';
  19433. }
  19434. throwError(errMsg);
  19435. }
  19436. if (!result.data) {
  19437. if ("development" !== 'production') {
  19438. errMsg = 'Transform result data should be not be null or undefined';
  19439. }
  19440. throwError(errMsg);
  19441. }
  19442. var sourceFormat = detectSourceFormat(result.data);
  19443. if (!isSupportedSourceFormat(sourceFormat)) {
  19444. if ("development" !== 'production') {
  19445. errMsg = 'Transform result data should be array rows or object rows.';
  19446. }
  19447. throwError(errMsg);
  19448. }
  19449. var resultMetaRawOption;
  19450. var firstUpSource = upSourceList[0];
  19451. /**
  19452. * Intuitively, the end users known the content of the original `dataset.source`,
  19453. * calucating the transform result in mind.
  19454. * Suppose the original `dataset.source` is:
  19455. * ```js
  19456. * [
  19457. * ['product', '2012', '2013', '2014', '2015'],
  19458. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  19459. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  19460. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  19461. * ]
  19462. * ```
  19463. * The dimension info have to be detected from the source data.
  19464. * Some of the transformers (like filter, sort) will follow the dimension info
  19465. * of upstream, while others use new dimensions (like aggregate).
  19466. * Transformer can output a field `dimensions` to define the its own output dimensions.
  19467. * We also allow transformers to ignore the output `dimensions` field, and
  19468. * inherit the upstream dimensions definition. It can reduce the burden of handling
  19469. * dimensions in transformers.
  19470. *
  19471. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19472. */
  19473. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  19474. // dimensions definitions. We do not inherit anything from upstream.
  19475. && !result.dimensions) {
  19476. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result becuase:
  19477. // (1) The returned data always does not contain header line and can not be used
  19478. // as dimension-detection. In this case we can not use "detected dimensions" of
  19479. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  19480. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  19481. // So the original detected header should be add to the result, otherwise they can not be read.
  19482. if (startIndex) {
  19483. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  19484. }
  19485. resultMetaRawOption = {
  19486. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19487. sourceHeader: startIndex,
  19488. dimensions: firstUpSource.metaRawOption.dimensions
  19489. };
  19490. } else {
  19491. resultMetaRawOption = {
  19492. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19493. sourceHeader: 0,
  19494. dimensions: result.dimensions
  19495. };
  19496. }
  19497. return createSource(result.data, resultMetaRawOption, null);
  19498. });
  19499. }
  19500. function isSupportedSourceFormat(sourceFormat) {
  19501. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  19502. }
  19503. var UNDEFINED = 'undefined';
  19504. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  19505. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  19506. // different from the Ctor of typed array.
  19507. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  19508. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  19509. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  19510. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  19511. /**
  19512. * Multi dimensional data store
  19513. */
  19514. var dataCtors = {
  19515. 'float': CtorFloat64Array,
  19516. 'int': CtorInt32Array,
  19517. // Ordinal data type can be string or int
  19518. 'ordinal': Array,
  19519. 'number': Array,
  19520. 'time': CtorFloat64Array
  19521. };
  19522. var defaultDimValueGetters;
  19523. function getIndicesCtor(rawCount) {
  19524. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  19525. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  19526. }
  19527. function getInitialExtent() {
  19528. return [Infinity, -Infinity];
  19529. }
  19530. function cloneChunk(originalChunk) {
  19531. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  19532. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  19533. }
  19534. function prepareStore(store, dimIdx, dimType, end, append) {
  19535. var DataCtor = dataCtors[dimType || 'float'];
  19536. if (append) {
  19537. var oldStore = store[dimIdx];
  19538. var oldLen = oldStore && oldStore.length;
  19539. if (!(oldLen === end)) {
  19540. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  19541. // within the initial chunkSize.
  19542. for (var j = 0; j < oldLen; j++) {
  19543. newStore[j] = oldStore[j];
  19544. }
  19545. store[dimIdx] = newStore;
  19546. }
  19547. } else {
  19548. store[dimIdx] = new DataCtor(end);
  19549. }
  19550. }
  19551. /**
  19552. * Basically, DataStore API keep immutable.
  19553. */
  19554. var DataStore =
  19555. /** @class */
  19556. function () {
  19557. function DataStore() {
  19558. this._chunks = []; // It will not be calculated util needed.
  19559. this._rawExtent = [];
  19560. this._extent = [];
  19561. this._count = 0;
  19562. this._rawCount = 0;
  19563. this._calcDimNameToIdx = createHashMap();
  19564. }
  19565. /**
  19566. * Initialize from data
  19567. */
  19568. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  19569. if ("development" !== 'production') {
  19570. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  19571. }
  19572. this._provider = provider; // Clear
  19573. this._chunks = [];
  19574. this._indices = null;
  19575. this.getRawIndex = this._getRawIdxIdentity;
  19576. var source = provider.getSource();
  19577. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat]; // Default dim value getter
  19578. this._dimValueGetter = dimValueGetter || defaultGetter; // Reset raw extent.
  19579. this._rawExtent = [];
  19580. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  19581. this._dimensions = map(inputDimensions, function (dim) {
  19582. if ("development" !== 'production') {
  19583. if (willRetrieveDataByName) {
  19584. assert(dim.property != null);
  19585. }
  19586. }
  19587. return {
  19588. // Only pick these two props. Not leak other properties like orderMeta.
  19589. type: dim.type,
  19590. property: dim.property
  19591. };
  19592. });
  19593. this._initDataFromProvider(0, provider.count());
  19594. };
  19595. DataStore.prototype.getProvider = function () {
  19596. return this._provider;
  19597. };
  19598. /**
  19599. * Caution: even when a `source` instance owned by a series, the created data store
  19600. * may still be shared by different sereis (the source hash does not use all `source`
  19601. * props, see `sourceManager`). In this case, the `source` props that are not used in
  19602. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  19603. * thus should not be fetch here.
  19604. */
  19605. DataStore.prototype.getSource = function () {
  19606. return this._provider.getSource();
  19607. };
  19608. /**
  19609. * @caution Only used in dataStack.
  19610. */
  19611. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  19612. var calcDimNameToIdx = this._calcDimNameToIdx;
  19613. var dimensions = this._dimensions;
  19614. var calcDimIdx = calcDimNameToIdx.get(dimName);
  19615. if (calcDimIdx != null) {
  19616. if (dimensions[calcDimIdx].type === type) {
  19617. return calcDimIdx;
  19618. }
  19619. } else {
  19620. calcDimIdx = dimensions.length;
  19621. }
  19622. dimensions[calcDimIdx] = {
  19623. type: type
  19624. };
  19625. calcDimNameToIdx.set(dimName, calcDimIdx);
  19626. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  19627. this._rawExtent[calcDimIdx] = getInitialExtent();
  19628. return calcDimIdx;
  19629. };
  19630. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  19631. var chunk = this._chunks[dimIdx];
  19632. var dim = this._dimensions[dimIdx];
  19633. var rawExtents = this._rawExtent;
  19634. var offset = dim.ordinalOffset || 0;
  19635. var len = chunk.length;
  19636. if (offset === 0) {
  19637. // We need to reset the rawExtent if collect is from start.
  19638. // Because this dimension may be guessed as number and calcuating a wrong extent.
  19639. rawExtents[dimIdx] = getInitialExtent();
  19640. }
  19641. var dimRawExtent = rawExtents[dimIdx]; // Parse from previous data offset. len may be changed after appendData
  19642. for (var i = offset; i < len; i++) {
  19643. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  19644. if (!isNaN(val)) {
  19645. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  19646. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  19647. }
  19648. }
  19649. dim.ordinalMeta = ordinalMeta;
  19650. dim.ordinalOffset = len;
  19651. dim.type = 'ordinal'; // Force to be ordinal
  19652. };
  19653. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  19654. var dimInfo = this._dimensions[dimIdx];
  19655. var ordinalMeta = dimInfo.ordinalMeta;
  19656. return ordinalMeta;
  19657. };
  19658. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  19659. var item = this._dimensions[dimIndex];
  19660. return item && item.property;
  19661. };
  19662. /**
  19663. * Caution: Can be only called on raw data (before `this._indices` created).
  19664. */
  19665. DataStore.prototype.appendData = function (data) {
  19666. if ("development" !== 'production') {
  19667. assert(!this._indices, 'appendData can only be called on raw data.');
  19668. }
  19669. var provider = this._provider;
  19670. var start = this.count();
  19671. provider.appendData(data);
  19672. var end = provider.count();
  19673. if (!provider.persistent) {
  19674. end += start;
  19675. }
  19676. if (start < end) {
  19677. this._initDataFromProvider(start, end, true);
  19678. }
  19679. return [start, end];
  19680. };
  19681. DataStore.prototype.appendValues = function (values, minFillLen) {
  19682. var chunks = this._chunks;
  19683. var dimensions = this._dimensions;
  19684. var dimLen = dimensions.length;
  19685. var rawExtent = this._rawExtent;
  19686. var start = this.count();
  19687. var end = start + Math.max(values.length, minFillLen || 0);
  19688. for (var i = 0; i < dimLen; i++) {
  19689. var dim = dimensions[i];
  19690. prepareStore(chunks, i, dim.type, end, true);
  19691. }
  19692. var emptyDataItem = [];
  19693. for (var idx = start; idx < end; idx++) {
  19694. var sourceIdx = idx - start; // Store the data by dimensions
  19695. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  19696. var dim = dimensions[dimIdx];
  19697. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  19698. chunks[dimIdx][idx] = val;
  19699. var dimRawExtent = rawExtent[dimIdx];
  19700. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  19701. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  19702. }
  19703. }
  19704. this._rawCount = this._count = end;
  19705. return {
  19706. start: start,
  19707. end: end
  19708. };
  19709. };
  19710. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  19711. var provider = this._provider;
  19712. var chunks = this._chunks;
  19713. var dimensions = this._dimensions;
  19714. var dimLen = dimensions.length;
  19715. var rawExtent = this._rawExtent;
  19716. var dimNames = map(dimensions, function (dim) {
  19717. return dim.property;
  19718. });
  19719. for (var i = 0; i < dimLen; i++) {
  19720. var dim = dimensions[i];
  19721. if (!rawExtent[i]) {
  19722. rawExtent[i] = getInitialExtent();
  19723. }
  19724. prepareStore(chunks, i, dim.type, end, append);
  19725. }
  19726. if (provider.fillStorage) {
  19727. provider.fillStorage(start, end, chunks, rawExtent);
  19728. } else {
  19729. var dataItem = [];
  19730. for (var idx = start; idx < end; idx++) {
  19731. // NOTICE: Try not to write things into dataItem
  19732. dataItem = provider.getItem(idx, dataItem); // Each data item is value
  19733. // [1, 2]
  19734. // 2
  19735. // Bar chart, line chart which uses category axis
  19736. // only gives the 'y' value. 'x' value is the indices of category
  19737. // Use a tempValue to normalize the value to be a (x, y) value
  19738. // Store the data by dimensions
  19739. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  19740. var dimStorage = chunks[dimIdx]; // PENDING NULL is empty or zero
  19741. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  19742. dimStorage[idx] = val;
  19743. var dimRawExtent = rawExtent[dimIdx];
  19744. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  19745. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  19746. }
  19747. }
  19748. }
  19749. if (!provider.persistent && provider.clean) {
  19750. // Clean unused data if data source is typed array.
  19751. provider.clean();
  19752. }
  19753. this._rawCount = this._count = end; // Reset data extent
  19754. this._extent = [];
  19755. };
  19756. DataStore.prototype.count = function () {
  19757. return this._count;
  19758. };
  19759. /**
  19760. * Get value. Return NaN if idx is out of range.
  19761. */
  19762. DataStore.prototype.get = function (dim, idx) {
  19763. if (!(idx >= 0 && idx < this._count)) {
  19764. return NaN;
  19765. }
  19766. var dimStore = this._chunks[dim];
  19767. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  19768. };
  19769. DataStore.prototype.getValues = function (dimensions, idx) {
  19770. var values = [];
  19771. var dimArr = [];
  19772. if (idx == null) {
  19773. idx = dimensions; // TODO get all from store?
  19774. dimensions = []; // All dimensions
  19775. for (var i = 0; i < this._dimensions.length; i++) {
  19776. dimArr.push(i);
  19777. }
  19778. } else {
  19779. dimArr = dimensions;
  19780. }
  19781. for (var i = 0, len = dimArr.length; i < len; i++) {
  19782. values.push(this.get(dimArr[i], idx));
  19783. }
  19784. return values;
  19785. };
  19786. /**
  19787. * @param dim concrete dim
  19788. */
  19789. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  19790. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  19791. return NaN;
  19792. }
  19793. var dimStore = this._chunks[dim];
  19794. return dimStore ? dimStore[rawIdx] : NaN;
  19795. };
  19796. /**
  19797. * Get sum of data in one dimension
  19798. */
  19799. DataStore.prototype.getSum = function (dim) {
  19800. var dimData = this._chunks[dim];
  19801. var sum = 0;
  19802. if (dimData) {
  19803. for (var i = 0, len = this.count(); i < len; i++) {
  19804. var value = this.get(dim, i);
  19805. if (!isNaN(value)) {
  19806. sum += value;
  19807. }
  19808. }
  19809. }
  19810. return sum;
  19811. };
  19812. /**
  19813. * Get median of data in one dimension
  19814. */
  19815. DataStore.prototype.getMedian = function (dim) {
  19816. var dimDataArray = []; // map all data of one dimension
  19817. this.each([dim], function (val) {
  19818. if (!isNaN(val)) {
  19819. dimDataArray.push(val);
  19820. }
  19821. }); // TODO
  19822. // Use quick select?
  19823. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  19824. return a - b;
  19825. });
  19826. var len = this.count(); // calculate median
  19827. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  19828. };
  19829. /**
  19830. * Retreive the index with given raw data index
  19831. */
  19832. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  19833. if (rawIndex >= this._rawCount || rawIndex < 0) {
  19834. return -1;
  19835. }
  19836. if (!this._indices) {
  19837. return rawIndex;
  19838. } // Indices are ascending
  19839. var indices = this._indices; // If rawIndex === dataIndex
  19840. var rawDataIndex = indices[rawIndex];
  19841. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  19842. return rawIndex;
  19843. }
  19844. var left = 0;
  19845. var right = this._count - 1;
  19846. while (left <= right) {
  19847. var mid = (left + right) / 2 | 0;
  19848. if (indices[mid] < rawIndex) {
  19849. left = mid + 1;
  19850. } else if (indices[mid] > rawIndex) {
  19851. right = mid - 1;
  19852. } else {
  19853. return mid;
  19854. }
  19855. }
  19856. return -1;
  19857. };
  19858. /**
  19859. * Retreive the index of nearest value
  19860. * @param dim
  19861. * @param value
  19862. * @param [maxDistance=Infinity]
  19863. * @return If and only if multiple indices has
  19864. * the same value, they are put to the result.
  19865. */
  19866. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  19867. var chunks = this._chunks;
  19868. var dimData = chunks[dim];
  19869. var nearestIndices = [];
  19870. if (!dimData) {
  19871. return nearestIndices;
  19872. }
  19873. if (maxDistance == null) {
  19874. maxDistance = Infinity;
  19875. }
  19876. var minDist = Infinity;
  19877. var minDiff = -1;
  19878. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/SeriesData.js`.
  19879. for (var i = 0, len = this.count(); i < len; i++) {
  19880. var dataIndex = this.getRawIndex(i);
  19881. var diff = value - dimData[dataIndex];
  19882. var dist = Math.abs(diff);
  19883. if (dist <= maxDistance) {
  19884. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  19885. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  19886. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  19887. // So we chose the one that `diff >= 0` in this csae.
  19888. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  19889. // should be push to `nearestIndices`.
  19890. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  19891. minDist = dist;
  19892. minDiff = diff;
  19893. nearestIndicesLen = 0;
  19894. }
  19895. if (diff === minDiff) {
  19896. nearestIndices[nearestIndicesLen++] = i;
  19897. }
  19898. }
  19899. }
  19900. nearestIndices.length = nearestIndicesLen;
  19901. return nearestIndices;
  19902. };
  19903. DataStore.prototype.getIndices = function () {
  19904. var newIndices;
  19905. var indices = this._indices;
  19906. if (indices) {
  19907. var Ctor = indices.constructor;
  19908. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  19909. if (Ctor === Array) {
  19910. newIndices = new Ctor(thisCount);
  19911. for (var i = 0; i < thisCount; i++) {
  19912. newIndices[i] = indices[i];
  19913. }
  19914. } else {
  19915. newIndices = new Ctor(indices.buffer, 0, thisCount);
  19916. }
  19917. } else {
  19918. var Ctor = getIndicesCtor(this._rawCount);
  19919. newIndices = new Ctor(this.count());
  19920. for (var i = 0; i < newIndices.length; i++) {
  19921. newIndices[i] = i;
  19922. }
  19923. }
  19924. return newIndices;
  19925. };
  19926. /**
  19927. * Data filter.
  19928. */
  19929. DataStore.prototype.filter = function (dims, cb) {
  19930. if (!this._count) {
  19931. return this;
  19932. }
  19933. var newStore = this.clone();
  19934. var count = newStore.count();
  19935. var Ctor = getIndicesCtor(newStore._rawCount);
  19936. var newIndices = new Ctor(count);
  19937. var value = [];
  19938. var dimSize = dims.length;
  19939. var offset = 0;
  19940. var dim0 = dims[0];
  19941. var chunks = newStore._chunks;
  19942. for (var i = 0; i < count; i++) {
  19943. var keep = void 0;
  19944. var rawIdx = newStore.getRawIndex(i); // Simple optimization
  19945. if (dimSize === 0) {
  19946. keep = cb(i);
  19947. } else if (dimSize === 1) {
  19948. var val = chunks[dim0][rawIdx];
  19949. keep = cb(val, i);
  19950. } else {
  19951. var k = 0;
  19952. for (; k < dimSize; k++) {
  19953. value[k] = chunks[dims[k]][rawIdx];
  19954. }
  19955. value[k] = i;
  19956. keep = cb.apply(null, value);
  19957. }
  19958. if (keep) {
  19959. newIndices[offset++] = rawIdx;
  19960. }
  19961. } // Set indices after filtered.
  19962. if (offset < count) {
  19963. newStore._indices = newIndices;
  19964. }
  19965. newStore._count = offset; // Reset data extent
  19966. newStore._extent = [];
  19967. newStore._updateGetRawIdx();
  19968. return newStore;
  19969. };
  19970. /**
  19971. * Select data in range. (For optimization of filter)
  19972. * (Manually inline code, support 5 million data filtering in data zoom.)
  19973. */
  19974. DataStore.prototype.selectRange = function (range) {
  19975. var newStore = this.clone();
  19976. var len = newStore._count;
  19977. if (!len) {
  19978. return this;
  19979. }
  19980. var dims = keys(range);
  19981. var dimSize = dims.length;
  19982. if (!dimSize) {
  19983. return this;
  19984. }
  19985. var originalCount = newStore.count();
  19986. var Ctor = getIndicesCtor(newStore._rawCount);
  19987. var newIndices = new Ctor(originalCount);
  19988. var offset = 0;
  19989. var dim0 = dims[0];
  19990. var min = range[dim0][0];
  19991. var max = range[dim0][1];
  19992. var storeArr = newStore._chunks;
  19993. var quickFinished = false;
  19994. if (!newStore._indices) {
  19995. // Extreme optimization for common case. About 2x faster in chrome.
  19996. var idx = 0;
  19997. if (dimSize === 1) {
  19998. var dimStorage = storeArr[dims[0]];
  19999. for (var i = 0; i < len; i++) {
  20000. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  20001. // value indicates the line should be broken. But for the case like
  20002. // scatter plot, a data item with empty value will not be rendered,
  20003. // but the axis extent may be effected if some other dim of the data
  20004. // item has value. Fortunately it is not a significant negative effect.
  20005. if (val >= min && val <= max || isNaN(val)) {
  20006. newIndices[offset++] = idx;
  20007. }
  20008. idx++;
  20009. }
  20010. quickFinished = true;
  20011. } else if (dimSize === 2) {
  20012. var dimStorage = storeArr[dims[0]];
  20013. var dimStorage2 = storeArr[dims[1]];
  20014. var min2 = range[dims[1]][0];
  20015. var max2 = range[dims[1]][1];
  20016. for (var i = 0; i < len; i++) {
  20017. var val = dimStorage[i];
  20018. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  20019. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20020. newIndices[offset++] = idx;
  20021. }
  20022. idx++;
  20023. }
  20024. quickFinished = true;
  20025. }
  20026. }
  20027. if (!quickFinished) {
  20028. if (dimSize === 1) {
  20029. for (var i = 0; i < originalCount; i++) {
  20030. var rawIndex = newStore.getRawIndex(i);
  20031. var val = storeArr[dims[0]][rawIndex]; // Do not filter NaN, see comment above.
  20032. if (val >= min && val <= max || isNaN(val)) {
  20033. newIndices[offset++] = rawIndex;
  20034. }
  20035. }
  20036. } else {
  20037. for (var i = 0; i < originalCount; i++) {
  20038. var keep = true;
  20039. var rawIndex = newStore.getRawIndex(i);
  20040. for (var k = 0; k < dimSize; k++) {
  20041. var dimk = dims[k];
  20042. var val = storeArr[dimk][rawIndex]; // Do not filter NaN, see comment above.
  20043. if (val < range[dimk][0] || val > range[dimk][1]) {
  20044. keep = false;
  20045. }
  20046. }
  20047. if (keep) {
  20048. newIndices[offset++] = newStore.getRawIndex(i);
  20049. }
  20050. }
  20051. }
  20052. } // Set indices after filtered.
  20053. if (offset < originalCount) {
  20054. newStore._indices = newIndices;
  20055. }
  20056. newStore._count = offset; // Reset data extent
  20057. newStore._extent = [];
  20058. newStore._updateGetRawIdx();
  20059. return newStore;
  20060. }; // /**
  20061. // * Data mapping to a plain array
  20062. // */
  20063. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  20064. // const result: any[] = [];
  20065. // this.each(dims, function () {
  20066. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  20067. // });
  20068. // return result;
  20069. // }
  20070. /**
  20071. * Data mapping to a new List with given dimensions
  20072. */
  20073. DataStore.prototype.map = function (dims, cb) {
  20074. // TODO only clone picked chunks.
  20075. var target = this.clone(dims);
  20076. this._updateDims(target, dims, cb);
  20077. return target;
  20078. };
  20079. /**
  20080. * @caution Danger!! Only used in dataStack.
  20081. */
  20082. DataStore.prototype.modify = function (dims, cb) {
  20083. this._updateDims(this, dims, cb);
  20084. };
  20085. DataStore.prototype._updateDims = function (target, dims, cb) {
  20086. var targetChunks = target._chunks;
  20087. var tmpRetValue = [];
  20088. var dimSize = dims.length;
  20089. var dataCount = target.count();
  20090. var values = [];
  20091. var rawExtent = target._rawExtent;
  20092. for (var i = 0; i < dims.length; i++) {
  20093. rawExtent[dims[i]] = getInitialExtent();
  20094. }
  20095. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  20096. var rawIndex = target.getRawIndex(dataIndex);
  20097. for (var k = 0; k < dimSize; k++) {
  20098. values[k] = targetChunks[dims[k]][rawIndex];
  20099. }
  20100. values[dimSize] = dataIndex;
  20101. var retValue = cb && cb.apply(null, values);
  20102. if (retValue != null) {
  20103. // a number or string (in oridinal dimension)?
  20104. if (typeof retValue !== 'object') {
  20105. tmpRetValue[0] = retValue;
  20106. retValue = tmpRetValue;
  20107. }
  20108. for (var i = 0; i < retValue.length; i++) {
  20109. var dim = dims[i];
  20110. var val = retValue[i];
  20111. var rawExtentOnDim = rawExtent[dim];
  20112. var dimStore = targetChunks[dim];
  20113. if (dimStore) {
  20114. dimStore[rawIndex] = val;
  20115. }
  20116. if (val < rawExtentOnDim[0]) {
  20117. rawExtentOnDim[0] = val;
  20118. }
  20119. if (val > rawExtentOnDim[1]) {
  20120. rawExtentOnDim[1] = val;
  20121. }
  20122. }
  20123. }
  20124. }
  20125. };
  20126. /**
  20127. * Large data down sampling using largest-triangle-three-buckets
  20128. * @param {string} valueDimension
  20129. * @param {number} targetCount
  20130. */
  20131. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  20132. var target = this.clone([valueDimension], true);
  20133. var targetStorage = target._chunks;
  20134. var dimStore = targetStorage[valueDimension];
  20135. var len = this.count();
  20136. var sampledIndex = 0;
  20137. var frameSize = Math.floor(1 / rate);
  20138. var currentRawIndex = this.getRawIndex(0);
  20139. var maxArea;
  20140. var area;
  20141. var nextRawIndex;
  20142. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len)); // First frame use the first data.
  20143. newIndices[sampledIndex++] = currentRawIndex;
  20144. for (var i = 1; i < len - 1; i += frameSize) {
  20145. var nextFrameStart = Math.min(i + frameSize, len - 1);
  20146. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  20147. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  20148. var avgY = 0;
  20149. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  20150. var rawIndex = this.getRawIndex(idx);
  20151. var y = dimStore[rawIndex];
  20152. if (isNaN(y)) {
  20153. continue;
  20154. }
  20155. avgY += y;
  20156. }
  20157. avgY /= nextFrameEnd - nextFrameStart;
  20158. var frameStart = i;
  20159. var frameEnd = Math.min(i + frameSize, len);
  20160. var pointAX = i - 1;
  20161. var pointAY = dimStore[currentRawIndex];
  20162. maxArea = -1;
  20163. nextRawIndex = frameStart;
  20164. var firstNaNIndex = -1;
  20165. var countNaN = 0; // Find a point from current frame that construct a triangel with largest area with previous selected point
  20166. // And the average of next frame.
  20167. for (var idx = frameStart; idx < frameEnd; idx++) {
  20168. var rawIndex = this.getRawIndex(idx);
  20169. var y = dimStore[rawIndex];
  20170. if (isNaN(y)) {
  20171. countNaN++;
  20172. if (firstNaNIndex < 0) {
  20173. firstNaNIndex = rawIndex;
  20174. }
  20175. continue;
  20176. } // Calculate triangle area over three buckets
  20177. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  20178. if (area > maxArea) {
  20179. maxArea = area;
  20180. nextRawIndex = rawIndex; // Next a is this b
  20181. }
  20182. }
  20183. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  20184. // Append first NaN point in every bucket.
  20185. // It is necessary to ensure the correct order of indices.
  20186. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  20187. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  20188. }
  20189. newIndices[sampledIndex++] = nextRawIndex;
  20190. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  20191. } // First frame use the last data.
  20192. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  20193. target._count = sampledIndex;
  20194. target._indices = newIndices;
  20195. target.getRawIndex = this._getRawIdx;
  20196. return target;
  20197. };
  20198. /**
  20199. * Large data down sampling on given dimension
  20200. * @param sampleIndex Sample index for name and id
  20201. */
  20202. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  20203. var target = this.clone([dimension], true);
  20204. var targetStorage = target._chunks;
  20205. var frameValues = [];
  20206. var frameSize = Math.floor(1 / rate);
  20207. var dimStore = targetStorage[dimension];
  20208. var len = this.count();
  20209. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  20210. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  20211. var offset = 0;
  20212. for (var i = 0; i < len; i += frameSize) {
  20213. // Last frame
  20214. if (frameSize > len - i) {
  20215. frameSize = len - i;
  20216. frameValues.length = frameSize;
  20217. }
  20218. for (var k = 0; k < frameSize; k++) {
  20219. var dataIdx = this.getRawIndex(i + k);
  20220. frameValues[k] = dimStore[dataIdx];
  20221. }
  20222. var value = sampleValue(frameValues);
  20223. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  20224. dimStore[sampleFrameIdx] = value;
  20225. if (value < rawExtentOnDim[0]) {
  20226. rawExtentOnDim[0] = value;
  20227. }
  20228. if (value > rawExtentOnDim[1]) {
  20229. rawExtentOnDim[1] = value;
  20230. }
  20231. newIndices[offset++] = sampleFrameIdx;
  20232. }
  20233. target._count = offset;
  20234. target._indices = newIndices;
  20235. target._updateGetRawIdx();
  20236. return target;
  20237. };
  20238. /**
  20239. * Data iteration
  20240. * @param ctx default this
  20241. * @example
  20242. * list.each('x', function (x, idx) {});
  20243. * list.each(['x', 'y'], function (x, y, idx) {});
  20244. * list.each(function (idx) {})
  20245. */
  20246. DataStore.prototype.each = function (dims, cb) {
  20247. if (!this._count) {
  20248. return;
  20249. }
  20250. var dimSize = dims.length;
  20251. var chunks = this._chunks;
  20252. for (var i = 0, len = this.count(); i < len; i++) {
  20253. var rawIdx = this.getRawIndex(i); // Simple optimization
  20254. switch (dimSize) {
  20255. case 0:
  20256. cb(i);
  20257. break;
  20258. case 1:
  20259. cb(chunks[dims[0]][rawIdx], i);
  20260. break;
  20261. case 2:
  20262. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  20263. break;
  20264. default:
  20265. var k = 0;
  20266. var value = [];
  20267. for (; k < dimSize; k++) {
  20268. value[k] = chunks[dims[k]][rawIdx];
  20269. } // Index
  20270. value[k] = i;
  20271. cb.apply(null, value);
  20272. }
  20273. }
  20274. };
  20275. /**
  20276. * Get extent of data in one dimension
  20277. */
  20278. DataStore.prototype.getDataExtent = function (dim) {
  20279. // Make sure use concrete dim as cache name.
  20280. var dimData = this._chunks[dim];
  20281. var initialExtent = getInitialExtent();
  20282. if (!dimData) {
  20283. return initialExtent;
  20284. } // Make more strict checkings to ensure hitting cache.
  20285. var currEnd = this.count(); // Consider the most cases when using data zoom, `getDataExtent`
  20286. // happened before filtering. We cache raw extent, which is not
  20287. // necessary to be cleared and recalculated when restore data.
  20288. var useRaw = !this._indices;
  20289. var dimExtent;
  20290. if (useRaw) {
  20291. return this._rawExtent[dim].slice();
  20292. }
  20293. dimExtent = this._extent[dim];
  20294. if (dimExtent) {
  20295. return dimExtent.slice();
  20296. }
  20297. dimExtent = initialExtent;
  20298. var min = dimExtent[0];
  20299. var max = dimExtent[1];
  20300. for (var i = 0; i < currEnd; i++) {
  20301. var rawIdx = this.getRawIndex(i);
  20302. var value = dimData[rawIdx];
  20303. value < min && (min = value);
  20304. value > max && (max = value);
  20305. }
  20306. dimExtent = [min, max];
  20307. this._extent[dim] = dimExtent;
  20308. return dimExtent;
  20309. };
  20310. /**
  20311. * Get raw data item
  20312. */
  20313. DataStore.prototype.getRawDataItem = function (idx) {
  20314. var rawIdx = this.getRawIndex(idx);
  20315. if (!this._provider.persistent) {
  20316. var val = [];
  20317. var chunks = this._chunks;
  20318. for (var i = 0; i < chunks.length; i++) {
  20319. val.push(chunks[i][rawIdx]);
  20320. }
  20321. return val;
  20322. } else {
  20323. return this._provider.getItem(rawIdx);
  20324. }
  20325. };
  20326. /**
  20327. * Clone shallow.
  20328. *
  20329. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  20330. */
  20331. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  20332. var target = new DataStore();
  20333. var chunks = this._chunks;
  20334. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  20335. obj[dimIdx] = true;
  20336. return obj;
  20337. }, {});
  20338. if (clonedDimsMap) {
  20339. for (var i = 0; i < chunks.length; i++) {
  20340. // Not clone if dim is not picked.
  20341. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  20342. }
  20343. } else {
  20344. target._chunks = chunks;
  20345. }
  20346. this._copyCommonProps(target);
  20347. if (!ignoreIndices) {
  20348. target._indices = this._cloneIndices();
  20349. }
  20350. target._updateGetRawIdx();
  20351. return target;
  20352. };
  20353. DataStore.prototype._copyCommonProps = function (target) {
  20354. target._count = this._count;
  20355. target._rawCount = this._rawCount;
  20356. target._provider = this._provider;
  20357. target._dimensions = this._dimensions;
  20358. target._extent = clone(this._extent);
  20359. target._rawExtent = clone(this._rawExtent);
  20360. };
  20361. DataStore.prototype._cloneIndices = function () {
  20362. if (this._indices) {
  20363. var Ctor = this._indices.constructor;
  20364. var indices = void 0;
  20365. if (Ctor === Array) {
  20366. var thisCount = this._indices.length;
  20367. indices = new Ctor(thisCount);
  20368. for (var i = 0; i < thisCount; i++) {
  20369. indices[i] = this._indices[i];
  20370. }
  20371. } else {
  20372. indices = new Ctor(this._indices);
  20373. }
  20374. return indices;
  20375. }
  20376. return null;
  20377. };
  20378. DataStore.prototype._getRawIdxIdentity = function (idx) {
  20379. return idx;
  20380. };
  20381. DataStore.prototype._getRawIdx = function (idx) {
  20382. if (idx < this._count && idx >= 0) {
  20383. return this._indices[idx];
  20384. }
  20385. return -1;
  20386. };
  20387. DataStore.prototype._updateGetRawIdx = function () {
  20388. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  20389. };
  20390. DataStore.internalField = function () {
  20391. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  20392. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  20393. }
  20394. defaultDimValueGetters = {
  20395. arrayRows: getDimValueSimply,
  20396. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  20397. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  20398. },
  20399. keyedColumns: getDimValueSimply,
  20400. original: function (dataItem, property, dataIndex, dimIndex) {
  20401. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20402. // If dataItem is an plain object with no value field, the let `value`
  20403. // will be assigned with the object, but it will be tread correctly
  20404. // in the `convertValue`.
  20405. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20406. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  20407. : value, this._dimensions[dimIndex]);
  20408. },
  20409. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  20410. return dataItem[dimIndex];
  20411. }
  20412. };
  20413. }();
  20414. return DataStore;
  20415. }();
  20416. /**
  20417. * [REQUIREMENT_MEMO]:
  20418. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  20419. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  20420. * `root-dataset`. Them on `series` has higher priority.
  20421. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  20422. * confuse users: whether those props indicate how to visit the upstream source or visit
  20423. * the transform result source, and some transforms has nothing to do with these props,
  20424. * and some transforms might have multiple upstream.
  20425. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  20426. * declared in `root-dataset`.
  20427. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  20428. * That is for reducing complexity in transfroms.
  20429. * PENDING: Whether to provide transposition transform?
  20430. *
  20431. * [IMPLEMENTAION_MEMO]:
  20432. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  20433. * They will not be calculated until `source` is about to be visited (to prevent from
  20434. * duplicate calcuation). `source` is visited only in series and input to transforms.
  20435. *
  20436. * [DIMENSION_INHERIT_RULE]:
  20437. * By default the dimensions are inherited from ancestors, unless a transform return
  20438. * a new dimensions definition.
  20439. * Consider the case:
  20440. * ```js
  20441. * dataset: [{
  20442. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  20443. * }, {
  20444. * transform: { type: 'filter', ... }
  20445. * }]
  20446. * dataset: [{
  20447. * dimension: ['Product', 'Sales', 'Prise'],
  20448. * source: [ ['Cookies', 321, 44.21], ...]
  20449. * }, {
  20450. * transform: { type: 'filter', ... }
  20451. * }]
  20452. * ```
  20453. * The two types of option should have the same behavior after transform.
  20454. *
  20455. *
  20456. * [SCENARIO]:
  20457. * (1) Provide source data directly:
  20458. * ```js
  20459. * series: {
  20460. * encode: {...},
  20461. * dimensions: [...]
  20462. * seriesLayoutBy: 'row',
  20463. * data: [[...]]
  20464. * }
  20465. * ```
  20466. * (2) Series refer to dataset.
  20467. * ```js
  20468. * series: [{
  20469. * encode: {...}
  20470. * // Ignore datasetIndex means `datasetIndex: 0`
  20471. * // and the dimensions defination in dataset is used
  20472. * }, {
  20473. * encode: {...},
  20474. * seriesLayoutBy: 'column',
  20475. * datasetIndex: 1
  20476. * }]
  20477. * ```
  20478. * (3) dataset transform
  20479. * ```js
  20480. * dataset: [{
  20481. * source: [...]
  20482. * }, {
  20483. * source: [...]
  20484. * }, {
  20485. * // By default from 0.
  20486. * transform: { type: 'filter', config: {...} }
  20487. * }, {
  20488. * // Piped.
  20489. * transform: [
  20490. * { type: 'filter', config: {...} },
  20491. * { type: 'sort', config: {...} }
  20492. * ]
  20493. * }, {
  20494. * id: 'regressionData',
  20495. * fromDatasetIndex: 1,
  20496. * // Third-party transform
  20497. * transform: { type: 'ecStat:regression', config: {...} }
  20498. * }, {
  20499. * // retrieve the extra result.
  20500. * id: 'regressionFormula',
  20501. * fromDatasetId: 'regressionData',
  20502. * fromTransformResult: 1
  20503. * }]
  20504. * ```
  20505. */
  20506. var SourceManager =
  20507. /** @class */
  20508. function () {
  20509. function SourceManager(sourceHost) {
  20510. // Cached source. Do not repeat calculating if not dirty.
  20511. this._sourceList = [];
  20512. this._storeList = []; // version sign of each upstream source manager.
  20513. this._upstreamSignList = [];
  20514. this._versionSignBase = 0;
  20515. this._dirty = true;
  20516. this._sourceHost = sourceHost;
  20517. }
  20518. /**
  20519. * Mark dirty.
  20520. */
  20521. SourceManager.prototype.dirty = function () {
  20522. this._setLocalSource([], []);
  20523. this._storeList = [];
  20524. this._dirty = true;
  20525. };
  20526. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  20527. this._sourceList = sourceList;
  20528. this._upstreamSignList = upstreamSignList;
  20529. this._versionSignBase++;
  20530. if (this._versionSignBase > 9e10) {
  20531. this._versionSignBase = 0;
  20532. }
  20533. };
  20534. /**
  20535. * For detecting whether the upstream source is dirty, so that
  20536. * the local cached source (in `_sourceList`) should be discarded.
  20537. */
  20538. SourceManager.prototype._getVersionSign = function () {
  20539. return this._sourceHost.uid + '_' + this._versionSignBase;
  20540. };
  20541. /**
  20542. * Always return a source instance. Otherwise throw error.
  20543. */
  20544. SourceManager.prototype.prepareSource = function () {
  20545. // For the case that call `setOption` multiple time but no data changed,
  20546. // cache the result source to prevent from repeating transform.
  20547. if (this._isDirty()) {
  20548. this._createSource();
  20549. this._dirty = false;
  20550. }
  20551. };
  20552. SourceManager.prototype._createSource = function () {
  20553. this._setLocalSource([], []);
  20554. var sourceHost = this._sourceHost;
  20555. var upSourceMgrList = this._getUpstreamSourceManagers();
  20556. var hasUpstream = !!upSourceMgrList.length;
  20557. var resultSourceList;
  20558. var upstreamSignList;
  20559. if (isSeries(sourceHost)) {
  20560. var seriesModel = sourceHost;
  20561. var data = void 0;
  20562. var sourceFormat = void 0;
  20563. var upSource = void 0; // Has upstream dataset
  20564. if (hasUpstream) {
  20565. var upSourceMgr = upSourceMgrList[0];
  20566. upSourceMgr.prepareSource();
  20567. upSource = upSourceMgr.getSource();
  20568. data = upSource.data;
  20569. sourceFormat = upSource.sourceFormat;
  20570. upstreamSignList = [upSourceMgr._getVersionSign()];
  20571. } // Series data is from own.
  20572. else {
  20573. data = seriesModel.get('data', true);
  20574. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  20575. upstreamSignList = [];
  20576. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  20577. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  20578. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  20579. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  20580. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  20581. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  20582. // but series need `seriesLayoutBy: 'row'`.
  20583. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions); // We share source with dataset as much as possible
  20584. // to avoid extra memroy cost of high dimensional data.
  20585. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  20586. resultSourceList = needsCreateSource ? [createSource(data, {
  20587. seriesLayoutBy: seriesLayoutBy,
  20588. sourceHeader: sourceHeader,
  20589. dimensions: dimensions
  20590. }, sourceFormat)] : [];
  20591. } else {
  20592. var datasetModel = sourceHost; // Has upstream dataset.
  20593. if (hasUpstream) {
  20594. var result = this._applyTransform(upSourceMgrList);
  20595. resultSourceList = result.sourceList;
  20596. upstreamSignList = result.upstreamSignList;
  20597. } // Is root dataset.
  20598. else {
  20599. var sourceData = datasetModel.get('source', true);
  20600. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  20601. upstreamSignList = [];
  20602. }
  20603. }
  20604. if ("development" !== 'production') {
  20605. assert(resultSourceList && upstreamSignList);
  20606. }
  20607. this._setLocalSource(resultSourceList, upstreamSignList);
  20608. };
  20609. SourceManager.prototype._applyTransform = function (upMgrList) {
  20610. var datasetModel = this._sourceHost;
  20611. var transformOption = datasetModel.get('transform', true);
  20612. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  20613. if ("development" !== 'production') {
  20614. assert(fromTransformResult != null || transformOption != null);
  20615. }
  20616. if (fromTransformResult != null) {
  20617. var errMsg = '';
  20618. if (upMgrList.length !== 1) {
  20619. if ("development" !== 'production') {
  20620. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  20621. }
  20622. doThrow(errMsg);
  20623. }
  20624. }
  20625. var sourceList;
  20626. var upSourceList = [];
  20627. var upstreamSignList = [];
  20628. each(upMgrList, function (upMgr) {
  20629. upMgr.prepareSource();
  20630. var upSource = upMgr.getSource(fromTransformResult || 0);
  20631. var errMsg = '';
  20632. if (fromTransformResult != null && !upSource) {
  20633. if ("development" !== 'production') {
  20634. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  20635. }
  20636. doThrow(errMsg);
  20637. }
  20638. upSourceList.push(upSource);
  20639. upstreamSignList.push(upMgr._getVersionSign());
  20640. });
  20641. if (transformOption) {
  20642. sourceList = applyDataTransform(transformOption, upSourceList, {
  20643. datasetIndex: datasetModel.componentIndex
  20644. });
  20645. } else if (fromTransformResult != null) {
  20646. sourceList = [cloneSourceShallow(upSourceList[0])];
  20647. }
  20648. return {
  20649. sourceList: sourceList,
  20650. upstreamSignList: upstreamSignList
  20651. };
  20652. };
  20653. SourceManager.prototype._isDirty = function () {
  20654. if (this._dirty) {
  20655. return true;
  20656. } // All sourceList is from the some upsteam.
  20657. var upSourceMgrList = this._getUpstreamSourceManagers();
  20658. for (var i = 0; i < upSourceMgrList.length; i++) {
  20659. var upSrcMgr = upSourceMgrList[i];
  20660. if ( // Consider the case that there is ancestor diry, call it recursively.
  20661. // The performance is probably not an issue because usually the chain is not long.
  20662. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  20663. return true;
  20664. }
  20665. }
  20666. };
  20667. /**
  20668. * @param sourceIndex By defualt 0, means "main source".
  20669. * Most cases there is only one source.
  20670. */
  20671. SourceManager.prototype.getSource = function (sourceIndex) {
  20672. sourceIndex = sourceIndex || 0;
  20673. var source = this._sourceList[sourceIndex];
  20674. if (!source) {
  20675. // Series may share source instance with dataset.
  20676. var upSourceMgrList = this._getUpstreamSourceManagers();
  20677. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  20678. }
  20679. return source;
  20680. };
  20681. /**
  20682. *
  20683. * Get a data store which can be shared across series.
  20684. * Only available for series.
  20685. *
  20686. * @param seriesDimRequest Dimensions that are generated in series.
  20687. * Should have been sorted by `storeDimIndex` asc.
  20688. */
  20689. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  20690. if ("development" !== 'production') {
  20691. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  20692. }
  20693. var schema = seriesDimRequest.makeStoreSchema();
  20694. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  20695. };
  20696. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  20697. // TODO Can use other sourceIndex?
  20698. var sourceIndex = 0;
  20699. var storeList = this._storeList;
  20700. var cachedStoreMap = storeList[sourceIndex];
  20701. if (!cachedStoreMap) {
  20702. cachedStoreMap = storeList[sourceIndex] = {};
  20703. }
  20704. var cachedStore = cachedStoreMap[sourceReadKey];
  20705. if (!cachedStore) {
  20706. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  20707. if (isSeries(this._sourceHost) && upSourceMgr) {
  20708. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  20709. } else {
  20710. cachedStore = new DataStore(); // Always create store from source of series.
  20711. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  20712. }
  20713. cachedStoreMap[sourceReadKey] = cachedStore;
  20714. }
  20715. return cachedStore;
  20716. };
  20717. /**
  20718. * PEDING: Is it fast enough?
  20719. * If no upstream, return empty array.
  20720. */
  20721. SourceManager.prototype._getUpstreamSourceManagers = function () {
  20722. // Always get the relationship from the raw option.
  20723. // Do not cache the link of the dependency graph, so that
  20724. // no need to update them when change happen.
  20725. var sourceHost = this._sourceHost;
  20726. if (isSeries(sourceHost)) {
  20727. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  20728. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  20729. } else {
  20730. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  20731. return datasetModel.getSourceManager();
  20732. });
  20733. }
  20734. };
  20735. SourceManager.prototype._getSourceMetaRawOption = function () {
  20736. var sourceHost = this._sourceHost;
  20737. var seriesLayoutBy;
  20738. var sourceHeader;
  20739. var dimensions;
  20740. if (isSeries(sourceHost)) {
  20741. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  20742. sourceHeader = sourceHost.get('sourceHeader', true);
  20743. dimensions = sourceHost.get('dimensions', true);
  20744. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  20745. else if (!this._getUpstreamSourceManagers().length) {
  20746. var model = sourceHost;
  20747. seriesLayoutBy = model.get('seriesLayoutBy', true);
  20748. sourceHeader = model.get('sourceHeader', true);
  20749. dimensions = model.get('dimensions', true);
  20750. }
  20751. return {
  20752. seriesLayoutBy: seriesLayoutBy,
  20753. sourceHeader: sourceHeader,
  20754. dimensions: dimensions
  20755. };
  20756. };
  20757. return SourceManager;
  20758. }();
  20759. // disable the transform merge, but do not disable transfrom clone from rawOption.
  20760. function disableTransformOptionMerge(datasetModel) {
  20761. var transformOption = datasetModel.option.transform;
  20762. transformOption && setAsPrimitive(datasetModel.option.transform);
  20763. }
  20764. function isSeries(sourceHost) {
  20765. // Avoid circular dependency with Series.ts
  20766. return sourceHost.mainType === 'series';
  20767. }
  20768. function doThrow(errMsg) {
  20769. throw new Error(errMsg);
  20770. }
  20771. function createTooltipMarkup(type, option) {
  20772. option.type = type;
  20773. return option;
  20774. }
  20775. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  20776. var style = series.getData().getItemVisual(dataIndex, 'style');
  20777. var color = style[series.visualDrawType];
  20778. return convertToColorString(color);
  20779. }
  20780. function defaultSeriesFormatTooltip(opt) {
  20781. var series = opt.series;
  20782. var dataIndex = opt.dataIndex;
  20783. var multipleSeries = opt.multipleSeries;
  20784. var data = series.getData();
  20785. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  20786. var tooltipDimLen = tooltipDims.length;
  20787. var value = series.getRawValue(dataIndex);
  20788. var isValueArr = isArray(value);
  20789. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  20790. var inlineValue;
  20791. var inlineValueType;
  20792. var subBlocks;
  20793. var sortParam;
  20794. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  20795. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  20796. inlineValue = formatArrResult.inlineValues;
  20797. inlineValueType = formatArrResult.inlineValueTypes;
  20798. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  20799. sortParam = formatArrResult.inlineValues[0];
  20800. } else if (tooltipDimLen) {
  20801. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  20802. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  20803. inlineValueType = dimInfo.type;
  20804. } else {
  20805. sortParam = inlineValue = isValueArr ? value[0] : value;
  20806. } // Do not show generated series name. It might not be readable.
  20807. var seriesNameSpecified = isNameSpecified(series);
  20808. var seriesName = seriesNameSpecified && series.name || '';
  20809. var itemName = data.getName(dataIndex);
  20810. var inlineName = multipleSeries ? seriesName : itemName;
  20811. return createTooltipMarkup('section', {
  20812. header: seriesName,
  20813. // When series name not specified, do not show a header line with only '-'.
  20814. // This case alway happen in tooltip.trigger: 'item'.
  20815. noHeader: multipleSeries || !seriesNameSpecified,
  20816. sortParam: sortParam,
  20817. blocks: [createTooltipMarkup('nameValue', {
  20818. markerType: 'item',
  20819. markerColor: markerColor,
  20820. // Do not mix display seriesName and itemName in one tooltip,
  20821. // which might confuses users.
  20822. name: inlineName,
  20823. // name dimension might be auto assigned, where the name might
  20824. // be not readable. So we check trim here.
  20825. noName: !trim(inlineName),
  20826. value: inlineValue,
  20827. valueType: inlineValueType
  20828. })].concat(subBlocks || [])
  20829. });
  20830. }
  20831. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  20832. // check: category-no-encode-has-axis-data in dataset.html
  20833. var data = series.getData();
  20834. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  20835. var dimItem = data.getDimensionInfo(idx);
  20836. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20837. }, false);
  20838. var inlineValues = [];
  20839. var inlineValueTypes = [];
  20840. var blocks = [];
  20841. tooltipDims.length ? each(tooltipDims, function (dim) {
  20842. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20843. }) // By default, all dims is used on tooltip.
  20844. : each(value, setEachItem);
  20845. function setEachItem(val, dim) {
  20846. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  20847. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20848. return;
  20849. }
  20850. if (isValueMultipleLine) {
  20851. blocks.push(createTooltipMarkup('nameValue', {
  20852. markerType: 'subItem',
  20853. markerColor: colorStr,
  20854. name: dimInfo.displayName,
  20855. value: val,
  20856. valueType: dimInfo.type
  20857. }));
  20858. } else {
  20859. inlineValues.push(val);
  20860. inlineValueTypes.push(dimInfo.type);
  20861. }
  20862. }
  20863. return {
  20864. inlineValues: inlineValues,
  20865. inlineValueTypes: inlineValueTypes,
  20866. blocks: blocks
  20867. };
  20868. }
  20869. var inner$1 = makeInner();
  20870. function getSelectionKey(data, dataIndex) {
  20871. return data.getName(dataIndex) || data.getId(dataIndex);
  20872. }
  20873. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  20874. var SeriesModel =
  20875. /** @class */
  20876. function (_super) {
  20877. __extends(SeriesModel, _super);
  20878. function SeriesModel() {
  20879. // [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`,
  20880. // the class members must not be initialized in constructor or declaration place.
  20881. // Otherwise there is bad case:
  20882. // class A {xxx = 1;}
  20883. // enableClassExtend(A);
  20884. // class B extends A {}
  20885. // var C = B.extend({xxx: 5});
  20886. // var c = new C();
  20887. // console.log(c.xxx); // expect 5 but always 1.
  20888. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  20889. // Props about data selection
  20890. // ---------------------------------------
  20891. _this._selectedDataIndicesMap = {};
  20892. return _this;
  20893. }
  20894. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  20895. this.seriesIndex = this.componentIndex;
  20896. this.dataTask = createTask({
  20897. count: dataTaskCount,
  20898. reset: dataTaskReset
  20899. });
  20900. this.dataTask.context = {
  20901. model: this
  20902. };
  20903. this.mergeDefaultAndTheme(option, ecModel);
  20904. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  20905. sourceManager.prepareSource();
  20906. var data = this.getInitialData(option, ecModel);
  20907. wrapData(data, this);
  20908. this.dataTask.context.data = data;
  20909. if ("development" !== 'production') {
  20910. assert(data, 'getInitialData returned invalid data.');
  20911. }
  20912. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  20913. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20914. // cause data.graph.data !== data when using
  20915. // module:echarts/data/Graph or module:echarts/data/Tree.
  20916. // See module:echarts/data/helper/linkSeriesData
  20917. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20918. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20919. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20920. // Call `seriesModel.getRawData()` instead.
  20921. // this.restoreData();
  20922. autoSeriesName(this);
  20923. this._initSelectedMapFromData(data);
  20924. };
  20925. /**
  20926. * Util for merge default and theme to option
  20927. */
  20928. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  20929. var layoutMode = fetchLayoutMode(this);
  20930. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  20931. // But if name duplicate between series subType
  20932. // (for example: parallel) add component mainType,
  20933. // add suffix 'Series'.
  20934. var themeSubType = this.subType;
  20935. if (ComponentModel.hasClass(themeSubType)) {
  20936. themeSubType += 'Series';
  20937. }
  20938. merge(option, ecModel.getTheme().get(this.subType));
  20939. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  20940. defaultEmphasis(option, 'label', ['show']);
  20941. this.fillDataTextStyle(option.data);
  20942. if (layoutMode) {
  20943. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20944. }
  20945. };
  20946. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  20947. // this.settingTask.dirty();
  20948. newSeriesOption = merge(this.option, newSeriesOption, true);
  20949. this.fillDataTextStyle(newSeriesOption.data);
  20950. var layoutMode = fetchLayoutMode(this);
  20951. if (layoutMode) {
  20952. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20953. }
  20954. var sourceManager = inner$1(this).sourceManager;
  20955. sourceManager.dirty();
  20956. sourceManager.prepareSource();
  20957. var data = this.getInitialData(newSeriesOption, ecModel);
  20958. wrapData(data, this);
  20959. this.dataTask.dirty();
  20960. this.dataTask.context.data = data;
  20961. inner$1(this).dataBeforeProcessed = data;
  20962. autoSeriesName(this);
  20963. this._initSelectedMapFromData(data);
  20964. };
  20965. SeriesModel.prototype.fillDataTextStyle = function (data) {
  20966. // Default data label emphasis `show`
  20967. // FIXME Tree structure data ?
  20968. // FIXME Performance ?
  20969. if (data && !isTypedArray(data)) {
  20970. var props = ['show'];
  20971. for (var i = 0; i < data.length; i++) {
  20972. if (data[i] && data[i].label) {
  20973. defaultEmphasis(data[i], 'label', props);
  20974. }
  20975. }
  20976. }
  20977. };
  20978. /**
  20979. * Init a data structure from data related option in series
  20980. * Must be overriden.
  20981. */
  20982. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  20983. return;
  20984. };
  20985. /**
  20986. * Append data to list
  20987. */
  20988. SeriesModel.prototype.appendData = function (params) {
  20989. // FIXME ???
  20990. // (1) If data from dataset, forbidden append.
  20991. // (2) support append data of dataset.
  20992. var data = this.getRawData();
  20993. data.appendData(params.data);
  20994. };
  20995. /**
  20996. * Consider some method like `filter`, `map` need make new data,
  20997. * We should make sure that `seriesModel.getData()` get correct
  20998. * data in the stream procedure. So we fetch data from upstream
  20999. * each time `task.perform` called.
  21000. */
  21001. SeriesModel.prototype.getData = function (dataType) {
  21002. var task = getCurrentTask(this);
  21003. if (task) {
  21004. var data = task.context.data;
  21005. return dataType == null ? data : data.getLinkedData(dataType);
  21006. } else {
  21007. // When series is not alive (that may happen when click toolbox
  21008. // restore or setOption with not merge mode), series data may
  21009. // be still need to judge animation or something when graphic
  21010. // elements want to know whether fade out.
  21011. return inner$1(this).data;
  21012. }
  21013. };
  21014. SeriesModel.prototype.getAllData = function () {
  21015. var mainData = this.getData();
  21016. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  21017. data: mainData
  21018. }];
  21019. };
  21020. SeriesModel.prototype.setData = function (data) {
  21021. var task = getCurrentTask(this);
  21022. if (task) {
  21023. var context = task.context; // Consider case: filter, data sample.
  21024. // FIXME:TS never used, so comment it
  21025. // if (context.data !== data && task.modifyOutputEnd) {
  21026. // task.setOutputEnd(data.count());
  21027. // }
  21028. context.outputData = data; // Caution: setData should update context.data,
  21029. // Because getData may be called multiply in a
  21030. // single stage and expect to get the data just
  21031. // set. (For example, AxisProxy, x y both call
  21032. // getData and setDate sequentially).
  21033. // So the context.data should be fetched from
  21034. // upstream each time when a stage starts to be
  21035. // performed.
  21036. if (task !== this.dataTask) {
  21037. context.data = data;
  21038. }
  21039. }
  21040. inner$1(this).data = data;
  21041. };
  21042. SeriesModel.prototype.getEncode = function () {
  21043. var encode = this.get('encode', true);
  21044. if (encode) {
  21045. return createHashMap(encode);
  21046. }
  21047. };
  21048. SeriesModel.prototype.getSourceManager = function () {
  21049. return inner$1(this).sourceManager;
  21050. };
  21051. SeriesModel.prototype.getSource = function () {
  21052. return this.getSourceManager().getSource();
  21053. };
  21054. /**
  21055. * Get data before processed
  21056. */
  21057. SeriesModel.prototype.getRawData = function () {
  21058. return inner$1(this).dataBeforeProcessed;
  21059. };
  21060. SeriesModel.prototype.getColorBy = function () {
  21061. var colorBy = this.get('colorBy');
  21062. return colorBy || 'series';
  21063. };
  21064. SeriesModel.prototype.isColorBySeries = function () {
  21065. return this.getColorBy() === 'series';
  21066. };
  21067. /**
  21068. * Get base axis if has coordinate system and has axis.
  21069. * By default use coordSys.getBaseAxis();
  21070. * Can be overrided for some chart.
  21071. * @return {type} description
  21072. */
  21073. SeriesModel.prototype.getBaseAxis = function () {
  21074. var coordSys = this.coordinateSystem; // @ts-ignore
  21075. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21076. };
  21077. /**
  21078. * Default tooltip formatter
  21079. *
  21080. * @param dataIndex
  21081. * @param multipleSeries
  21082. * @param dataType
  21083. * @param renderMode valid values: 'html'(by default) and 'richText'.
  21084. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21085. * string is used as DOM HTML content.
  21086. * 'richText' is used for rendering tooltip in rich text form, for those where
  21087. * DOM operation is not supported.
  21088. * @return formatted tooltip with `html` and `markers`
  21089. * Notice: The override method can also return string
  21090. */
  21091. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  21092. return defaultSeriesFormatTooltip({
  21093. series: this,
  21094. dataIndex: dataIndex,
  21095. multipleSeries: multipleSeries
  21096. });
  21097. };
  21098. SeriesModel.prototype.isAnimationEnabled = function () {
  21099. var ecModel = this.ecModel; // Disable animation if using echarts in node but not give ssr flag.
  21100. // In ssr mode, renderToString will generate svg with css animation.
  21101. if (env.node && !(ecModel && ecModel.ssr)) {
  21102. return false;
  21103. }
  21104. var animationEnabled = this.getShallow('animation');
  21105. if (animationEnabled) {
  21106. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21107. animationEnabled = false;
  21108. }
  21109. }
  21110. return !!animationEnabled;
  21111. };
  21112. SeriesModel.prototype.restoreData = function () {
  21113. this.dataTask.dirty();
  21114. };
  21115. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  21116. var ecModel = this.ecModel; // PENDING
  21117. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  21118. if (!color) {
  21119. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21120. }
  21121. return color;
  21122. };
  21123. /**
  21124. * Use `data.mapDimensionsAll(coordDim)` instead.
  21125. * @deprecated
  21126. */
  21127. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  21128. return this.getRawData().mapDimensionsAll(coordDim);
  21129. };
  21130. /**
  21131. * Get progressive rendering count each step
  21132. */
  21133. SeriesModel.prototype.getProgressive = function () {
  21134. return this.get('progressive');
  21135. };
  21136. /**
  21137. * Get progressive rendering count each step
  21138. */
  21139. SeriesModel.prototype.getProgressiveThreshold = function () {
  21140. return this.get('progressiveThreshold');
  21141. }; // PENGING If selectedMode is null ?
  21142. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  21143. this._innerSelect(this.getData(dataType), innerDataIndices);
  21144. };
  21145. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  21146. var selectedMap = this.option.selectedMap;
  21147. if (!selectedMap) {
  21148. return;
  21149. }
  21150. var selectedMode = this.option.selectedMode;
  21151. var data = this.getData(dataType);
  21152. if (selectedMode === 'series' || selectedMap === 'all') {
  21153. this.option.selectedMap = {};
  21154. this._selectedDataIndicesMap = {};
  21155. return;
  21156. }
  21157. for (var i = 0; i < innerDataIndices.length; i++) {
  21158. var dataIndex = innerDataIndices[i];
  21159. var nameOrId = getSelectionKey(data, dataIndex);
  21160. selectedMap[nameOrId] = false;
  21161. this._selectedDataIndicesMap[nameOrId] = -1;
  21162. }
  21163. };
  21164. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  21165. var tmpArr = [];
  21166. for (var i = 0; i < innerDataIndices.length; i++) {
  21167. tmpArr[0] = innerDataIndices[i];
  21168. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  21169. }
  21170. };
  21171. SeriesModel.prototype.getSelectedDataIndices = function () {
  21172. if (this.option.selectedMap === 'all') {
  21173. return [].slice.call(this.getData().getIndices());
  21174. }
  21175. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  21176. var nameOrIds = keys(selectedDataIndicesMap);
  21177. var dataIndices = [];
  21178. for (var i = 0; i < nameOrIds.length; i++) {
  21179. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  21180. if (dataIndex >= 0) {
  21181. dataIndices.push(dataIndex);
  21182. }
  21183. }
  21184. return dataIndices;
  21185. };
  21186. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  21187. var selectedMap = this.option.selectedMap;
  21188. if (!selectedMap) {
  21189. return false;
  21190. }
  21191. var data = this.getData(dataType);
  21192. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  21193. };
  21194. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  21195. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  21196. return true;
  21197. }
  21198. var universalTransitionOpt = this.option.universalTransition; // Quick reject
  21199. if (!universalTransitionOpt) {
  21200. return false;
  21201. }
  21202. if (universalTransitionOpt === true) {
  21203. return true;
  21204. } // Can be simply 'universalTransition: true'
  21205. return universalTransitionOpt && universalTransitionOpt.enabled;
  21206. };
  21207. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  21208. var _a, _b;
  21209. var option = this.option;
  21210. var selectedMode = option.selectedMode;
  21211. var len = innerDataIndices.length;
  21212. if (!selectedMode || !len) {
  21213. return;
  21214. }
  21215. if (selectedMode === 'series') {
  21216. option.selectedMap = 'all';
  21217. } else if (selectedMode === 'multiple') {
  21218. if (!isObject(option.selectedMap)) {
  21219. option.selectedMap = {};
  21220. }
  21221. var selectedMap = option.selectedMap;
  21222. for (var i = 0; i < len; i++) {
  21223. var dataIndex = innerDataIndices[i]; // TODO diffrent types of data share same object.
  21224. var nameOrId = getSelectionKey(data, dataIndex);
  21225. selectedMap[nameOrId] = true;
  21226. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  21227. }
  21228. } else if (selectedMode === 'single' || selectedMode === true) {
  21229. var lastDataIndex = innerDataIndices[len - 1];
  21230. var nameOrId = getSelectionKey(data, lastDataIndex);
  21231. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  21232. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  21233. }
  21234. };
  21235. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  21236. // Ignore select info in data if selectedMap exists.
  21237. // NOTE It's only for legacy usage. edge data is not supported.
  21238. if (this.option.selectedMap) {
  21239. return;
  21240. }
  21241. var dataIndices = [];
  21242. if (data.hasItemOption) {
  21243. data.each(function (idx) {
  21244. var rawItem = data.getRawDataItem(idx);
  21245. if (rawItem && rawItem.selected) {
  21246. dataIndices.push(idx);
  21247. }
  21248. });
  21249. }
  21250. if (dataIndices.length > 0) {
  21251. this._innerSelect(data, dataIndices);
  21252. }
  21253. }; // /**
  21254. // * @see {module:echarts/stream/Scheduler}
  21255. // */
  21256. // abstract pipeTask: null
  21257. SeriesModel.registerClass = function (clz) {
  21258. return ComponentModel.registerClass(clz);
  21259. };
  21260. SeriesModel.protoInitialize = function () {
  21261. var proto = SeriesModel.prototype;
  21262. proto.type = 'series.__base__';
  21263. proto.seriesIndex = 0;
  21264. proto.ignoreStyleOnData = false;
  21265. proto.hasSymbolVisual = false;
  21266. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  21267. proto.visualStyleAccessPath = 'itemStyle';
  21268. proto.visualDrawType = 'fill';
  21269. }();
  21270. return SeriesModel;
  21271. }(ComponentModel);
  21272. mixin(SeriesModel, DataFormatMixin);
  21273. mixin(SeriesModel, PaletteMixin);
  21274. mountExtend(SeriesModel, ComponentModel);
  21275. /**
  21276. * MUST be called after `prepareSource` called
  21277. * Here we need to make auto series, especially for auto legend. But we
  21278. * do not modify series.name in option to avoid side effects.
  21279. */
  21280. function autoSeriesName(seriesModel) {
  21281. // User specified name has higher priority, otherwise it may cause
  21282. // series can not be queried unexpectedly.
  21283. var name = seriesModel.name;
  21284. if (!isNameSpecified(seriesModel)) {
  21285. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21286. }
  21287. }
  21288. function getSeriesAutoName(seriesModel) {
  21289. var data = seriesModel.getRawData();
  21290. var dataDims = data.mapDimensionsAll('seriesName');
  21291. var nameArr = [];
  21292. each(dataDims, function (dataDim) {
  21293. var dimInfo = data.getDimensionInfo(dataDim);
  21294. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21295. });
  21296. return nameArr.join(' ');
  21297. }
  21298. function dataTaskCount(context) {
  21299. return context.model.getRawData().count();
  21300. }
  21301. function dataTaskReset(context) {
  21302. var seriesModel = context.model;
  21303. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21304. return dataTaskProgress;
  21305. }
  21306. function dataTaskProgress(param, context) {
  21307. // Avoid repead cloneShallow when data just created in reset.
  21308. if (context.outputData && param.end > context.outputData.count()) {
  21309. context.model.getRawData().cloneShallow(context.outputData);
  21310. }
  21311. } // TODO refactor
  21312. function wrapData(data, seriesModel) {
  21313. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  21314. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  21315. });
  21316. }
  21317. function onDataChange(seriesModel, newList) {
  21318. var task = getCurrentTask(seriesModel);
  21319. if (task) {
  21320. // Consider case: filter, selectRange
  21321. task.setOutputEnd((newList || this).count());
  21322. }
  21323. return newList;
  21324. }
  21325. function getCurrentTask(seriesModel) {
  21326. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21327. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21328. if (pipeline) {
  21329. // When pipline finished, the currrentTask keep the last
  21330. // task (renderTask).
  21331. var task = pipeline.currentTask;
  21332. if (task) {
  21333. var agentStubMap = task.agentStubMap;
  21334. if (agentStubMap) {
  21335. task = agentStubMap.get(seriesModel.uid);
  21336. }
  21337. }
  21338. return task;
  21339. }
  21340. }
  21341. var ComponentView =
  21342. /** @class */
  21343. function () {
  21344. function ComponentView() {
  21345. this.group = new Group();
  21346. this.uid = getUID('viewComponent');
  21347. }
  21348. ComponentView.prototype.init = function (ecModel, api) {};
  21349. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  21350. ComponentView.prototype.dispose = function (ecModel, api) {};
  21351. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  21352. };
  21353. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  21354. };
  21355. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  21356. };
  21357. /**
  21358. * Hook for toggle blur target series.
  21359. * Can be used in marker for blur or leave blur the markers
  21360. */
  21361. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {// Do nothing;
  21362. };
  21363. /**
  21364. * Traverse the new rendered elements.
  21365. *
  21366. * It will traverse the new added element in progressive rendering.
  21367. * And traverse all in normal rendering.
  21368. */
  21369. ComponentView.prototype.eachRendered = function (cb) {
  21370. var group = this.group;
  21371. if (group) {
  21372. group.traverse(cb);
  21373. }
  21374. };
  21375. return ComponentView;
  21376. }();
  21377. enableClassExtend(ComponentView);
  21378. enableClassManagement(ComponentView);
  21379. /**
  21380. * @return {string} If large mode changed, return string 'reset';
  21381. */
  21382. function createRenderPlanner() {
  21383. var inner = makeInner();
  21384. return function (seriesModel) {
  21385. var fields = inner(seriesModel);
  21386. var pipelineContext = seriesModel.pipelineContext;
  21387. var originalLarge = !!fields.large;
  21388. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  21389. // exists. See #11611 . Probably we need to modify this structure, see the comment
  21390. // on `performRawSeries` in `Schedular.js`.
  21391. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  21392. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  21393. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  21394. };
  21395. }
  21396. var inner$2 = makeInner();
  21397. var renderPlanner = createRenderPlanner();
  21398. var ChartView =
  21399. /** @class */
  21400. function () {
  21401. function ChartView() {
  21402. this.group = new Group();
  21403. this.uid = getUID('viewChart');
  21404. this.renderTask = createTask({
  21405. plan: renderTaskPlan,
  21406. reset: renderTaskReset
  21407. });
  21408. this.renderTask.context = {
  21409. view: this
  21410. };
  21411. }
  21412. ChartView.prototype.init = function (ecModel, api) {};
  21413. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  21414. if ("development" !== 'production') {
  21415. throw new Error('render method must been implemented');
  21416. }
  21417. };
  21418. /**
  21419. * Highlight series or specified data item.
  21420. */
  21421. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  21422. var data = seriesModel.getData(payload && payload.dataType);
  21423. if (!data) {
  21424. if ("development" !== 'production') {
  21425. error("Unknown dataType " + payload.dataType);
  21426. }
  21427. return;
  21428. }
  21429. toggleHighlight(data, payload, 'emphasis');
  21430. };
  21431. /**
  21432. * Downplay series or specified data item.
  21433. */
  21434. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  21435. var data = seriesModel.getData(payload && payload.dataType);
  21436. if (!data) {
  21437. if ("development" !== 'production') {
  21438. error("Unknown dataType " + payload.dataType);
  21439. }
  21440. return;
  21441. }
  21442. toggleHighlight(data, payload, 'normal');
  21443. };
  21444. /**
  21445. * Remove self.
  21446. */
  21447. ChartView.prototype.remove = function (ecModel, api) {
  21448. this.group.removeAll();
  21449. };
  21450. /**
  21451. * Dispose self.
  21452. */
  21453. ChartView.prototype.dispose = function (ecModel, api) {};
  21454. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  21455. this.render(seriesModel, ecModel, api, payload);
  21456. }; // FIXME never used?
  21457. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  21458. this.render(seriesModel, ecModel, api, payload);
  21459. }; // FIXME never used?
  21460. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  21461. this.render(seriesModel, ecModel, api, payload);
  21462. };
  21463. /**
  21464. * Traverse the new rendered elements.
  21465. *
  21466. * It will traverse the new added element in progressive rendering.
  21467. * And traverse all in normal rendering.
  21468. */
  21469. ChartView.prototype.eachRendered = function (cb) {
  21470. traverseElements(this.group, cb);
  21471. };
  21472. ChartView.markUpdateMethod = function (payload, methodName) {
  21473. inner$2(payload).updateMethod = methodName;
  21474. };
  21475. ChartView.protoInitialize = function () {
  21476. var proto = ChartView.prototype;
  21477. proto.type = 'chart';
  21478. }();
  21479. return ChartView;
  21480. }();
  21481. /**
  21482. * Set state of single element
  21483. */
  21484. function elSetState(el, state, highlightDigit) {
  21485. if (el && isHighDownDispatcher(el)) {
  21486. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  21487. }
  21488. }
  21489. function toggleHighlight(data, payload, state) {
  21490. var dataIndex = queryDataIndex(data, payload);
  21491. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  21492. if (dataIndex != null) {
  21493. each(normalizeToArray(dataIndex), function (dataIdx) {
  21494. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  21495. });
  21496. } else {
  21497. data.eachItemGraphicEl(function (el) {
  21498. elSetState(el, state, highlightDigit);
  21499. });
  21500. }
  21501. }
  21502. enableClassExtend(ChartView, ['dispose']);
  21503. enableClassManagement(ChartView);
  21504. function renderTaskPlan(context) {
  21505. return renderPlanner(context.model);
  21506. }
  21507. function renderTaskReset(context) {
  21508. var seriesModel = context.model;
  21509. var ecModel = context.ecModel;
  21510. var api = context.api;
  21511. var payload = context.payload; // FIXME: remove updateView updateVisual
  21512. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21513. var view = context.view;
  21514. var updateMethod = payload && inner$2(payload).updateMethod;
  21515. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  21516. // is less than progressive threshold.
  21517. : 'render';
  21518. if (methodName !== 'render') {
  21519. view[methodName](seriesModel, ecModel, api, payload);
  21520. }
  21521. return progressMethodMap[methodName];
  21522. }
  21523. var progressMethodMap = {
  21524. incrementalPrepareRender: {
  21525. progress: function (params, context) {
  21526. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  21527. }
  21528. },
  21529. render: {
  21530. // Put view.render in `progress` to support appendData. But in this case
  21531. // view.render should not be called in reset, otherwise it will be called
  21532. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21533. // in any cases.
  21534. forceFirstProgress: true,
  21535. progress: function (params, context) {
  21536. context.view.render(context.model, context.ecModel, context.api, context.payload);
  21537. }
  21538. }
  21539. };
  21540. /**
  21541. * @public
  21542. * @param {(Function)} fn
  21543. * @param {number} [delay=0] Unit: ms.
  21544. * @param {boolean} [debounce=false]
  21545. * true: If call interval less than `delay`, only the last call works.
  21546. * false: If call interval less than `delay, call works on fixed rate.
  21547. * @return {(Function)} throttled fn.
  21548. */
  21549. function throttle(fn, delay, debounce) {
  21550. var currCall;
  21551. var lastCall = 0;
  21552. var lastExec = 0;
  21553. var timer = null;
  21554. var diff;
  21555. var scope;
  21556. var args;
  21557. var debounceNextCall;
  21558. delay = delay || 0;
  21559. function exec() {
  21560. lastExec = new Date().getTime();
  21561. timer = null;
  21562. fn.apply(scope, args || []);
  21563. }
  21564. var cb = function () {
  21565. var cbArgs = [];
  21566. for (var _i = 0; _i < arguments.length; _i++) {
  21567. cbArgs[_i] = arguments[_i];
  21568. }
  21569. currCall = new Date().getTime();
  21570. scope = this;
  21571. args = cbArgs;
  21572. var thisDelay = debounceNextCall || delay;
  21573. var thisDebounce = debounceNextCall || debounce;
  21574. debounceNextCall = null;
  21575. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21576. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  21577. // than a new call of `cb`, that is, preserving the command order. Consider
  21578. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21579. // happens, either the `exec` is called dierectly, or the call is delayed.
  21580. // But the delayed call should never be later than next call of `cb`. Under
  21581. // this assurance, we can simply update view state each time `dispatchAction`
  21582. // triggered by user roaming, but not need to add extra code to avoid the
  21583. // state being "rolled-back".
  21584. if (thisDebounce) {
  21585. timer = setTimeout(exec, thisDelay);
  21586. } else {
  21587. if (diff >= 0) {
  21588. exec();
  21589. } else {
  21590. timer = setTimeout(exec, -diff);
  21591. }
  21592. }
  21593. lastCall = currCall;
  21594. };
  21595. /**
  21596. * Clear throttle.
  21597. * @public
  21598. */
  21599. cb.clear = function () {
  21600. if (timer) {
  21601. clearTimeout(timer);
  21602. timer = null;
  21603. }
  21604. };
  21605. /**
  21606. * Enable debounce once.
  21607. */
  21608. cb.debounceNextCall = function (debounceDelay) {
  21609. debounceNextCall = debounceDelay;
  21610. };
  21611. return cb;
  21612. }
  21613. var inner$3 = makeInner();
  21614. var defaultStyleMappers = {
  21615. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  21616. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  21617. };
  21618. var defaultColorKey = {
  21619. lineStyle: 'stroke',
  21620. itemStyle: 'fill'
  21621. };
  21622. function getStyleMapper(seriesModel, stylePath) {
  21623. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  21624. if (!styleMapper) {
  21625. console.warn("Unkown style type '" + stylePath + "'.");
  21626. return defaultStyleMappers.itemStyle;
  21627. }
  21628. return styleMapper;
  21629. }
  21630. function getDefaultColorKey(seriesModel, stylePath) {
  21631. // return defaultColorKey[stylePath] ||
  21632. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  21633. if (!colorKey) {
  21634. console.warn("Unkown style type '" + stylePath + "'.");
  21635. return 'fill';
  21636. }
  21637. return colorKey;
  21638. }
  21639. var seriesStyleTask = {
  21640. createOnAllSeries: true,
  21641. performRawSeries: true,
  21642. reset: function (seriesModel, ecModel) {
  21643. var data = seriesModel.getData();
  21644. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  21645. var styleModel = seriesModel.getModel(stylePath);
  21646. var getStyle = getStyleMapper(seriesModel, stylePath);
  21647. var globalStyle = getStyle(styleModel);
  21648. var decalOption = styleModel.getShallow('decal');
  21649. if (decalOption) {
  21650. data.setVisual('decal', decalOption);
  21651. decalOption.dirty = true;
  21652. } // TODO
  21653. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  21654. var color = globalStyle[colorKey]; // TODO style callback
  21655. var colorCallback = isFunction(color) ? color : null;
  21656. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto'; // Get from color palette by default.
  21657. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  21658. // Note: if some series has color specified (e.g., by itemStyle.color), we DO NOT
  21659. // make it effect palette. Bacause some scenarios users need to make some series
  21660. // transparent or as background, which should better not effect the palette.
  21661. var colorPalette = seriesModel.getColorFromPalette( // TODO series count changed.
  21662. seriesModel.name, null, ecModel.getSeriesCount());
  21663. if (!globalStyle[colorKey]) {
  21664. globalStyle[colorKey] = colorPalette;
  21665. data.setVisual('colorFromPalette', true);
  21666. }
  21667. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  21668. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  21669. }
  21670. data.setVisual('style', globalStyle);
  21671. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  21672. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  21673. data.setVisual('colorFromPalette', false);
  21674. return {
  21675. dataEach: function (data, idx) {
  21676. var dataParams = seriesModel.getDataParams(idx);
  21677. var itemStyle = extend({}, globalStyle);
  21678. itemStyle[colorKey] = colorCallback(dataParams);
  21679. data.setItemVisual(idx, 'style', itemStyle);
  21680. }
  21681. };
  21682. }
  21683. }
  21684. };
  21685. var sharedModel = new Model();
  21686. var dataStyleTask = {
  21687. createOnAllSeries: true,
  21688. performRawSeries: true,
  21689. reset: function (seriesModel, ecModel) {
  21690. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  21691. return;
  21692. }
  21693. var data = seriesModel.getData();
  21694. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  21695. var getStyle = getStyleMapper(seriesModel, stylePath);
  21696. var colorKey = data.getVisual('drawType');
  21697. return {
  21698. dataEach: data.hasItemOption ? function (data, idx) {
  21699. // Not use getItemModel for performance considuration
  21700. var rawItem = data.getRawDataItem(idx);
  21701. if (rawItem && rawItem[stylePath]) {
  21702. sharedModel.option = rawItem[stylePath];
  21703. var style = getStyle(sharedModel);
  21704. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  21705. extend(existsStyle, style);
  21706. if (sharedModel.option.decal) {
  21707. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  21708. sharedModel.option.decal.dirty = true;
  21709. }
  21710. if (colorKey in style) {
  21711. data.setItemVisual(idx, 'colorFromPalette', false);
  21712. }
  21713. }
  21714. } : null
  21715. };
  21716. }
  21717. }; // Pick color from palette for the data which has not been set with color yet.
  21718. // Note: do not support stream rendering. No such cases yet.
  21719. var dataColorPaletteTask = {
  21720. performRawSeries: true,
  21721. overallReset: function (ecModel) {
  21722. // Each type of series use one scope.
  21723. // Pie and funnel are using diferrent scopes
  21724. var paletteScopeGroupByType = createHashMap();
  21725. ecModel.eachSeries(function (seriesModel) {
  21726. var colorBy = seriesModel.getColorBy();
  21727. if (seriesModel.isColorBySeries()) {
  21728. return;
  21729. }
  21730. var key = seriesModel.type + '-' + colorBy;
  21731. var colorScope = paletteScopeGroupByType.get(key);
  21732. if (!colorScope) {
  21733. colorScope = {};
  21734. paletteScopeGroupByType.set(key, colorScope);
  21735. }
  21736. inner$3(seriesModel).scope = colorScope;
  21737. });
  21738. ecModel.eachSeries(function (seriesModel) {
  21739. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  21740. return;
  21741. }
  21742. var dataAll = seriesModel.getRawData();
  21743. var idxMap = {};
  21744. var data = seriesModel.getData();
  21745. var colorScope = inner$3(seriesModel).scope;
  21746. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  21747. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  21748. data.each(function (idx) {
  21749. var rawIdx = data.getRawIndex(idx);
  21750. idxMap[rawIdx] = idx;
  21751. }); // Iterate on data before filtered. To make sure color from palette can be
  21752. // Consistent when toggling legend.
  21753. dataAll.each(function (rawIdx) {
  21754. var idx = idxMap[rawIdx];
  21755. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  21756. // also picked from color palette. So following situation is not in the case:
  21757. // 1. series.itemStyle.color is set
  21758. // 2. color is encoded by visualMap
  21759. if (fromPalette) {
  21760. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  21761. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  21762. var dataCount = dataAll.count();
  21763. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  21764. }
  21765. });
  21766. });
  21767. }
  21768. };
  21769. var PI$3 = Math.PI;
  21770. /**
  21771. * @param {module:echarts/ExtensionAPI} api
  21772. * @param {Object} [opts]
  21773. * @param {string} [opts.text]
  21774. * @param {string} [opts.color]
  21775. * @param {string} [opts.textColor]
  21776. * @return {module:zrender/Element}
  21777. */
  21778. function defaultLoading(api, opts) {
  21779. opts = opts || {};
  21780. defaults(opts, {
  21781. text: 'loading',
  21782. textColor: '#000',
  21783. fontSize: 12,
  21784. fontWeight: 'normal',
  21785. fontStyle: 'normal',
  21786. fontFamily: 'sans-serif',
  21787. maskColor: 'rgba(255, 255, 255, 0.8)',
  21788. showSpinner: true,
  21789. color: '#5470c6',
  21790. spinnerRadius: 10,
  21791. lineWidth: 5,
  21792. zlevel: 0
  21793. });
  21794. var group = new Group();
  21795. var mask = new Rect({
  21796. style: {
  21797. fill: opts.maskColor
  21798. },
  21799. zlevel: opts.zlevel,
  21800. z: 10000
  21801. });
  21802. group.add(mask);
  21803. var textContent = new ZRText({
  21804. style: {
  21805. text: opts.text,
  21806. fill: opts.textColor,
  21807. fontSize: opts.fontSize,
  21808. fontWeight: opts.fontWeight,
  21809. fontStyle: opts.fontStyle,
  21810. fontFamily: opts.fontFamily
  21811. },
  21812. zlevel: opts.zlevel,
  21813. z: 10001
  21814. });
  21815. var labelRect = new Rect({
  21816. style: {
  21817. fill: 'none'
  21818. },
  21819. textContent: textContent,
  21820. textConfig: {
  21821. position: 'right',
  21822. distance: 10
  21823. },
  21824. zlevel: opts.zlevel,
  21825. z: 10001
  21826. });
  21827. group.add(labelRect);
  21828. var arc;
  21829. if (opts.showSpinner) {
  21830. arc = new Arc({
  21831. shape: {
  21832. startAngle: -PI$3 / 2,
  21833. endAngle: -PI$3 / 2 + 0.1,
  21834. r: opts.spinnerRadius
  21835. },
  21836. style: {
  21837. stroke: opts.color,
  21838. lineCap: 'round',
  21839. lineWidth: opts.lineWidth
  21840. },
  21841. zlevel: opts.zlevel,
  21842. z: 10001
  21843. });
  21844. arc.animateShape(true).when(1000, {
  21845. endAngle: PI$3 * 3 / 2
  21846. }).start('circularInOut');
  21847. arc.animateShape(true).when(1000, {
  21848. startAngle: PI$3 * 3 / 2
  21849. }).delay(300).start('circularInOut');
  21850. group.add(arc);
  21851. } // Inject resize
  21852. group.resize = function () {
  21853. var textWidth = textContent.getBoundingRect().width;
  21854. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  21855. // textDistance needs to be calculated when both animation and text exist
  21856. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  21857. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  21858. + (textWidth ? 0 : r);
  21859. var cy = api.getHeight() / 2;
  21860. opts.showSpinner && arc.setShape({
  21861. cx: cx,
  21862. cy: cy
  21863. });
  21864. labelRect.setShape({
  21865. x: cx - r,
  21866. y: cy - r,
  21867. width: r * 2,
  21868. height: r * 2
  21869. });
  21870. mask.setShape({
  21871. x: 0,
  21872. y: 0,
  21873. width: api.getWidth(),
  21874. height: api.getHeight()
  21875. });
  21876. };
  21877. group.resize();
  21878. return group;
  21879. }
  21880. var Scheduler =
  21881. /** @class */
  21882. function () {
  21883. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21884. // key: handlerUID
  21885. this._stageTaskMap = createHashMap();
  21886. this.ecInstance = ecInstance;
  21887. this.api = api; // Fix current processors in case that in some rear cases that
  21888. // processors might be registered after echarts instance created.
  21889. // Register processors incrementally for a echarts instance is
  21890. // not supported by this stream architecture.
  21891. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21892. visualHandlers = this._visualHandlers = visualHandlers.slice();
  21893. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21894. }
  21895. Scheduler.prototype.restoreData = function (ecModel, payload) {
  21896. // TODO: Only restore needed series and components, but not all components.
  21897. // Currently `restoreData` of all of the series and component will be called.
  21898. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21899. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21900. // and some components like coordinate system, axes, dataZoom, visualMap only
  21901. // need their target series refresh.
  21902. // (1) If we are implementing this feature some day, we should consider these cases:
  21903. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21904. // on the settings of `dataZoom`), it should be re-performed if the component
  21905. // is modified by `setOption`.
  21906. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21907. // it should be re-performed when the result array of `getTargetSeries` changed.
  21908. // We use `dependencies` to cover these issues.
  21909. // (3) How to update target series when coordinate system related components modified.
  21910. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21911. // and this case all of the tasks will be set as dirty.
  21912. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  21913. // depends on all of the series.
  21914. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21915. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21916. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21917. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21918. // probably cause state chaos (consider `dataZoomProcessor`).
  21919. this._stageTaskMap.each(function (taskRecord) {
  21920. var overallTask = taskRecord.overallTask;
  21921. overallTask && overallTask.dirty();
  21922. });
  21923. }; // If seriesModel provided, incremental threshold is check by series data.
  21924. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  21925. // For overall task
  21926. if (!task.__pipeline) {
  21927. return;
  21928. }
  21929. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21930. var pCtx = pipeline.context;
  21931. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  21932. var step = incremental ? pipeline.step : null;
  21933. var modDataCount = pCtx && pCtx.modDataCount;
  21934. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21935. return {
  21936. step: step,
  21937. modBy: modBy,
  21938. modDataCount: modDataCount
  21939. };
  21940. };
  21941. Scheduler.prototype.getPipeline = function (pipelineId) {
  21942. return this._pipelineMap.get(pipelineId);
  21943. };
  21944. /**
  21945. * Current, progressive rendering starts from visual and layout.
  21946. * Always detect render mode in the same stage, avoiding that incorrect
  21947. * detection caused by data filtering.
  21948. * Caution:
  21949. * `updateStreamModes` use `seriesModel.getData()`.
  21950. */
  21951. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  21952. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21953. var data = seriesModel.getData();
  21954. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  21955. // animation frame. Note that some types of series do not provide
  21956. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21957. // use the term `incremental` but not `progressive` to describe the
  21958. // case that `chart.appendData`.
  21959. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  21960. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21961. // see `test/candlestick-large3.html`
  21962. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21963. seriesModel.pipelineContext = pipeline.context = {
  21964. progressiveRender: progressiveRender,
  21965. modDataCount: modDataCount,
  21966. large: large
  21967. };
  21968. };
  21969. Scheduler.prototype.restorePipelines = function (ecModel) {
  21970. var scheduler = this;
  21971. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21972. ecModel.eachSeries(function (seriesModel) {
  21973. var progressive = seriesModel.getProgressive();
  21974. var pipelineId = seriesModel.uid;
  21975. pipelineMap.set(pipelineId, {
  21976. id: pipelineId,
  21977. head: null,
  21978. tail: null,
  21979. threshold: seriesModel.getProgressiveThreshold(),
  21980. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21981. blockIndex: -1,
  21982. step: Math.round(progressive || 700),
  21983. count: 0
  21984. });
  21985. scheduler._pipe(seriesModel, seriesModel.dataTask);
  21986. });
  21987. };
  21988. Scheduler.prototype.prepareStageTasks = function () {
  21989. var stageTaskMap = this._stageTaskMap;
  21990. var ecModel = this.api.getModel();
  21991. var api = this.api;
  21992. each(this._allHandlers, function (handler) {
  21993. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  21994. var errMsg = '';
  21995. if ("development" !== 'production') {
  21996. // Currently do not need to support to sepecify them both.
  21997. errMsg = '"reset" and "overallReset" must not be both specified.';
  21998. }
  21999. assert(!(handler.reset && handler.overallReset), errMsg);
  22000. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  22001. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  22002. }, this);
  22003. };
  22004. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  22005. var renderTask = view.renderTask;
  22006. var context = renderTask.context;
  22007. context.model = model;
  22008. context.ecModel = ecModel;
  22009. context.api = api;
  22010. renderTask.__block = !view.incrementalPrepareRender;
  22011. this._pipe(model, renderTask);
  22012. };
  22013. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  22014. // If we do not use `block` here, it should be considered when to update modes.
  22015. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  22016. block: true
  22017. });
  22018. };
  22019. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  22020. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  22021. };
  22022. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  22023. opt = opt || {};
  22024. var unfinished = false;
  22025. var scheduler = this;
  22026. each(stageHandlers, function (stageHandler, idx) {
  22027. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22028. return;
  22029. }
  22030. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22031. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22032. var overallTask = stageHandlerRecord.overallTask;
  22033. if (overallTask) {
  22034. var overallNeedDirty_1;
  22035. var agentStubMap = overallTask.agentStubMap;
  22036. agentStubMap.each(function (stub) {
  22037. if (needSetDirty(opt, stub)) {
  22038. stub.dirty();
  22039. overallNeedDirty_1 = true;
  22040. }
  22041. });
  22042. overallNeedDirty_1 && overallTask.dirty();
  22043. scheduler.updatePayload(overallTask, payload);
  22044. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  22045. // then execute the overall task. And stub will call seriesModel.setData,
  22046. // which ensures that in the overallTask seriesModel.getData() will not
  22047. // return incorrect data.
  22048. agentStubMap.each(function (stub) {
  22049. stub.perform(performArgs_1);
  22050. });
  22051. if (overallTask.perform(performArgs_1)) {
  22052. unfinished = true;
  22053. }
  22054. } else if (seriesTaskMap) {
  22055. seriesTaskMap.each(function (task, pipelineId) {
  22056. if (needSetDirty(opt, task)) {
  22057. task.dirty();
  22058. }
  22059. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  22060. // if intending to decalare `performRawSeries` in handlers, only
  22061. // stream-independent (specifically, data item independent) operations can be
  22062. // performed. Because is a series is filtered, most of the tasks will not
  22063. // be performed. A stream-dependent operation probably cause wrong biz logic.
  22064. // Perhaps we should not provide a separate callback for this case instead
  22065. // of providing the config `performRawSeries`. The stream-dependent operaions
  22066. // and stream-independent operations should better not be mixed.
  22067. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  22068. scheduler.updatePayload(task, payload);
  22069. if (task.perform(performArgs)) {
  22070. unfinished = true;
  22071. }
  22072. });
  22073. }
  22074. });
  22075. function needSetDirty(opt, task) {
  22076. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22077. }
  22078. this.unfinished = unfinished || this.unfinished;
  22079. };
  22080. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  22081. var unfinished;
  22082. ecModel.eachSeries(function (seriesModel) {
  22083. // Progress to the end for dataInit and dataRestore.
  22084. unfinished = seriesModel.dataTask.perform() || unfinished;
  22085. });
  22086. this.unfinished = unfinished || this.unfinished;
  22087. };
  22088. Scheduler.prototype.plan = function () {
  22089. // Travel pipelines, check block.
  22090. this._pipelineMap.each(function (pipeline) {
  22091. var task = pipeline.tail;
  22092. do {
  22093. if (task.__block) {
  22094. pipeline.blockIndex = task.__idxInPipeline;
  22095. break;
  22096. }
  22097. task = task.getUpstream();
  22098. } while (task);
  22099. });
  22100. };
  22101. Scheduler.prototype.updatePayload = function (task, payload) {
  22102. payload !== 'remain' && (task.context.payload = payload);
  22103. };
  22104. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  22105. var scheduler = this;
  22106. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  22107. // do not need to reuse the map.
  22108. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  22109. var seriesType = stageHandler.seriesType;
  22110. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22111. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22112. // it works but it may cause other irrelevant charts blocked.
  22113. if (stageHandler.createOnAllSeries) {
  22114. ecModel.eachRawSeries(create);
  22115. } else if (seriesType) {
  22116. ecModel.eachRawSeriesByType(seriesType, create);
  22117. } else if (getTargetSeries) {
  22118. getTargetSeries(ecModel, api).each(create);
  22119. }
  22120. function create(seriesModel) {
  22121. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  22122. // Reuse original task instance.
  22123. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  22124. plan: seriesTaskPlan,
  22125. reset: seriesTaskReset,
  22126. count: seriesTaskCount
  22127. }));
  22128. task.context = {
  22129. model: seriesModel,
  22130. ecModel: ecModel,
  22131. api: api,
  22132. // PENDING: `useClearVisual` not used?
  22133. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22134. plan: stageHandler.plan,
  22135. reset: stageHandler.reset,
  22136. scheduler: scheduler
  22137. };
  22138. scheduler._pipe(seriesModel, task);
  22139. }
  22140. };
  22141. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  22142. var scheduler = this;
  22143. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  22144. || createTask({
  22145. reset: overallTaskReset
  22146. });
  22147. overallTask.context = {
  22148. ecModel: ecModel,
  22149. api: api,
  22150. overallReset: stageHandler.overallReset,
  22151. scheduler: scheduler
  22152. };
  22153. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  22154. // do not need to reuse the map.
  22155. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  22156. var seriesType = stageHandler.seriesType;
  22157. var getTargetSeries = stageHandler.getTargetSeries;
  22158. var overallProgress = true;
  22159. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  22160. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  22161. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22162. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22163. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22164. // we set the pipeline block.
  22165. var errMsg = '';
  22166. if ("development" !== 'production') {
  22167. errMsg = '"createOnAllSeries" do not supported for "overallReset", ' + 'becuase it will block all streams.';
  22168. }
  22169. assert(!stageHandler.createOnAllSeries, errMsg);
  22170. if (seriesType) {
  22171. ecModel.eachRawSeriesByType(seriesType, createStub);
  22172. } else if (getTargetSeries) {
  22173. getTargetSeries(ecModel, api).each(createStub);
  22174. } // Otherwise, (usually it is legancy case), the overall task will only be
  22175. // executed when upstream dirty. Otherwise the progressive rendering of all
  22176. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22177. // dirty info from upsteam.
  22178. else {
  22179. overallProgress = false;
  22180. each(ecModel.getSeries(), createStub);
  22181. }
  22182. function createStub(seriesModel) {
  22183. var pipelineId = seriesModel.uid;
  22184. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  22185. // should be set as dirty and re-performed.
  22186. shouldOverallTaskDirty = true, createTask({
  22187. reset: stubReset,
  22188. onDirty: stubOnDirty
  22189. })));
  22190. stub.context = {
  22191. model: seriesModel,
  22192. overallProgress: overallProgress // FIXME:TS never used, so comment it
  22193. // modifyOutputEnd: modifyOutputEnd
  22194. };
  22195. stub.agent = overallTask;
  22196. stub.__block = overallProgress;
  22197. scheduler._pipe(seriesModel, stub);
  22198. }
  22199. if (shouldOverallTaskDirty) {
  22200. overallTask.dirty();
  22201. }
  22202. };
  22203. Scheduler.prototype._pipe = function (seriesModel, task) {
  22204. var pipelineId = seriesModel.uid;
  22205. var pipeline = this._pipelineMap.get(pipelineId);
  22206. !pipeline.head && (pipeline.head = task);
  22207. pipeline.tail && pipeline.tail.pipe(task);
  22208. pipeline.tail = task;
  22209. task.__idxInPipeline = pipeline.count++;
  22210. task.__pipeline = pipeline;
  22211. };
  22212. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22213. if (isFunction(stageHandler)) {
  22214. stageHandler = {
  22215. overallReset: stageHandler,
  22216. seriesType: detectSeriseType(stageHandler)
  22217. };
  22218. }
  22219. stageHandler.uid = getUID('stageHandler');
  22220. visualType && (stageHandler.visualType = visualType);
  22221. return stageHandler;
  22222. };
  22223. return Scheduler;
  22224. }();
  22225. function overallTaskReset(context) {
  22226. context.overallReset(context.ecModel, context.api, context.payload);
  22227. }
  22228. function stubReset(context) {
  22229. return context.overallProgress && stubProgress;
  22230. }
  22231. function stubProgress() {
  22232. this.agent.dirty();
  22233. this.getDownstream().dirty();
  22234. }
  22235. function stubOnDirty() {
  22236. this.agent && this.agent.dirty();
  22237. }
  22238. function seriesTaskPlan(context) {
  22239. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  22240. }
  22241. function seriesTaskReset(context) {
  22242. if (context.useClearVisual) {
  22243. context.data.clearAllVisual();
  22244. }
  22245. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  22246. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  22247. return makeSeriesTaskProgress(idx);
  22248. }) : singleSeriesTaskProgress;
  22249. }
  22250. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22251. function makeSeriesTaskProgress(resetDefineIdx) {
  22252. return function (params, context) {
  22253. var data = context.data;
  22254. var resetDefine = context.resetDefines[resetDefineIdx];
  22255. if (resetDefine && resetDefine.dataEach) {
  22256. for (var i = params.start; i < params.end; i++) {
  22257. resetDefine.dataEach(data, i);
  22258. }
  22259. } else if (resetDefine && resetDefine.progress) {
  22260. resetDefine.progress(params, data);
  22261. }
  22262. };
  22263. }
  22264. function seriesTaskCount(context) {
  22265. return context.data.count();
  22266. }
  22267. /**
  22268. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22269. * To ensure that they can work normally, they should work in block mode, that is,
  22270. * they should not be started util the previous tasks finished. So they cause the
  22271. * progressive rendering disabled. We try to detect the series type, to narrow down
  22272. * the block range to only the series type they concern, but not all series.
  22273. */
  22274. function detectSeriseType(legacyFunc) {
  22275. seriesType = null;
  22276. try {
  22277. // Assume there is no async when calling `eachSeriesByType`.
  22278. legacyFunc(ecModelMock, apiMock);
  22279. } catch (e) {}
  22280. return seriesType;
  22281. }
  22282. var ecModelMock = {};
  22283. var apiMock = {};
  22284. var seriesType;
  22285. mockMethods(ecModelMock, GlobalModel);
  22286. mockMethods(apiMock, ExtensionAPI);
  22287. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22288. seriesType = type;
  22289. };
  22290. ecModelMock.eachComponent = function (cond) {
  22291. if (cond.mainType === 'series' && cond.subType) {
  22292. seriesType = cond.subType;
  22293. }
  22294. };
  22295. function mockMethods(target, Clz) {
  22296. /* eslint-disable */
  22297. for (var name_1 in Clz.prototype) {
  22298. // Do not use hasOwnProperty
  22299. target[name_1] = noop;
  22300. }
  22301. /* eslint-enable */
  22302. }
  22303. /*
  22304. * Licensed to the Apache Software Foundation (ASF) under one
  22305. * or more contributor license agreements. See the NOTICE file
  22306. * distributed with this work for additional information
  22307. * regarding copyright ownership. The ASF licenses this file
  22308. * to you under the Apache License, Version 2.0 (the
  22309. * "License"); you may not use this file except in compliance
  22310. * with the License. You may obtain a copy of the License at
  22311. *
  22312. * http://www.apache.org/licenses/LICENSE-2.0
  22313. *
  22314. * Unless required by applicable law or agreed to in writing,
  22315. * software distributed under the License is distributed on an
  22316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22317. * KIND, either express or implied. See the License for the
  22318. * specific language governing permissions and limitations
  22319. * under the License.
  22320. */
  22321. /**
  22322. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22323. */
  22324. /*
  22325. * Licensed to the Apache Software Foundation (ASF) under one
  22326. * or more contributor license agreements. See the NOTICE file
  22327. * distributed with this work for additional information
  22328. * regarding copyright ownership. The ASF licenses this file
  22329. * to you under the Apache License, Version 2.0 (the
  22330. * "License"); you may not use this file except in compliance
  22331. * with the License. You may obtain a copy of the License at
  22332. *
  22333. * http://www.apache.org/licenses/LICENSE-2.0
  22334. *
  22335. * Unless required by applicable law or agreed to in writing,
  22336. * software distributed under the License is distributed on an
  22337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22338. * KIND, either express or implied. See the License for the
  22339. * specific language governing permissions and limitations
  22340. * under the License.
  22341. */
  22342. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  22343. var lightTheme = {
  22344. color: colorAll,
  22345. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  22346. };
  22347. /*
  22348. * Licensed to the Apache Software Foundation (ASF) under one
  22349. * or more contributor license agreements. See the NOTICE file
  22350. * distributed with this work for additional information
  22351. * regarding copyright ownership. The ASF licenses this file
  22352. * to you under the Apache License, Version 2.0 (the
  22353. * "License"); you may not use this file except in compliance
  22354. * with the License. You may obtain a copy of the License at
  22355. *
  22356. * http://www.apache.org/licenses/LICENSE-2.0
  22357. *
  22358. * Unless required by applicable law or agreed to in writing,
  22359. * software distributed under the License is distributed on an
  22360. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22361. * KIND, either express or implied. See the License for the
  22362. * specific language governing permissions and limitations
  22363. * under the License.
  22364. */
  22365. /**
  22366. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22367. */
  22368. /*
  22369. * Licensed to the Apache Software Foundation (ASF) under one
  22370. * or more contributor license agreements. See the NOTICE file
  22371. * distributed with this work for additional information
  22372. * regarding copyright ownership. The ASF licenses this file
  22373. * to you under the Apache License, Version 2.0 (the
  22374. * "License"); you may not use this file except in compliance
  22375. * with the License. You may obtain a copy of the License at
  22376. *
  22377. * http://www.apache.org/licenses/LICENSE-2.0
  22378. *
  22379. * Unless required by applicable law or agreed to in writing,
  22380. * software distributed under the License is distributed on an
  22381. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22382. * KIND, either express or implied. See the License for the
  22383. * specific language governing permissions and limitations
  22384. * under the License.
  22385. */
  22386. var contrastColor = '#B9B8CE';
  22387. var backgroundColor = '#100C2A';
  22388. var axisCommon = function () {
  22389. return {
  22390. axisLine: {
  22391. lineStyle: {
  22392. color: contrastColor
  22393. }
  22394. },
  22395. splitLine: {
  22396. lineStyle: {
  22397. color: '#484753'
  22398. }
  22399. },
  22400. splitArea: {
  22401. areaStyle: {
  22402. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  22403. }
  22404. },
  22405. minorSplitLine: {
  22406. lineStyle: {
  22407. color: '#20203B'
  22408. }
  22409. }
  22410. };
  22411. };
  22412. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  22413. var theme = {
  22414. darkMode: true,
  22415. color: colorPalette,
  22416. backgroundColor: backgroundColor,
  22417. axisPointer: {
  22418. lineStyle: {
  22419. color: '#817f91'
  22420. },
  22421. crossStyle: {
  22422. color: '#817f91'
  22423. },
  22424. label: {
  22425. // TODO Contrast of label backgorundColor
  22426. color: '#fff'
  22427. }
  22428. },
  22429. legend: {
  22430. textStyle: {
  22431. color: contrastColor
  22432. }
  22433. },
  22434. textStyle: {
  22435. color: contrastColor
  22436. },
  22437. title: {
  22438. textStyle: {
  22439. color: '#EEF1FA'
  22440. },
  22441. subtextStyle: {
  22442. color: '#B9B8CE'
  22443. }
  22444. },
  22445. toolbox: {
  22446. iconStyle: {
  22447. borderColor: contrastColor
  22448. }
  22449. },
  22450. dataZoom: {
  22451. borderColor: '#71708A',
  22452. textStyle: {
  22453. color: contrastColor
  22454. },
  22455. brushStyle: {
  22456. color: 'rgba(135,163,206,0.3)'
  22457. },
  22458. handleStyle: {
  22459. color: '#353450',
  22460. borderColor: '#C5CBE3'
  22461. },
  22462. moveHandleStyle: {
  22463. color: '#B0B6C3',
  22464. opacity: 0.3
  22465. },
  22466. fillerColor: 'rgba(135,163,206,0.2)',
  22467. emphasis: {
  22468. handleStyle: {
  22469. borderColor: '#91B7F2',
  22470. color: '#4D587D'
  22471. },
  22472. moveHandleStyle: {
  22473. color: '#636D9A',
  22474. opacity: 0.7
  22475. }
  22476. },
  22477. dataBackground: {
  22478. lineStyle: {
  22479. color: '#71708A',
  22480. width: 1
  22481. },
  22482. areaStyle: {
  22483. color: '#71708A'
  22484. }
  22485. },
  22486. selectedDataBackground: {
  22487. lineStyle: {
  22488. color: '#87A3CE'
  22489. },
  22490. areaStyle: {
  22491. color: '#87A3CE'
  22492. }
  22493. }
  22494. },
  22495. visualMap: {
  22496. textStyle: {
  22497. color: contrastColor
  22498. }
  22499. },
  22500. timeline: {
  22501. lineStyle: {
  22502. color: contrastColor
  22503. },
  22504. label: {
  22505. color: contrastColor
  22506. },
  22507. controlStyle: {
  22508. color: contrastColor,
  22509. borderColor: contrastColor
  22510. }
  22511. },
  22512. calendar: {
  22513. itemStyle: {
  22514. color: backgroundColor
  22515. },
  22516. dayLabel: {
  22517. color: contrastColor
  22518. },
  22519. monthLabel: {
  22520. color: contrastColor
  22521. },
  22522. yearLabel: {
  22523. color: contrastColor
  22524. }
  22525. },
  22526. timeAxis: axisCommon(),
  22527. logAxis: axisCommon(),
  22528. valueAxis: axisCommon(),
  22529. categoryAxis: axisCommon(),
  22530. line: {
  22531. symbol: 'circle'
  22532. },
  22533. graph: {
  22534. color: colorPalette
  22535. },
  22536. gauge: {
  22537. title: {
  22538. color: contrastColor
  22539. },
  22540. axisLine: {
  22541. lineStyle: {
  22542. color: [[1, 'rgba(207,212,219,0.2)']]
  22543. }
  22544. },
  22545. axisLabel: {
  22546. color: contrastColor
  22547. },
  22548. detail: {
  22549. color: '#EEF1FA'
  22550. }
  22551. },
  22552. candlestick: {
  22553. itemStyle: {
  22554. color: '#f64e56',
  22555. color0: '#54ea92',
  22556. borderColor: '#f64e56',
  22557. borderColor0: '#54ea92' // borderColor: '#ca2824',
  22558. // borderColor0: '#09a443'
  22559. }
  22560. }
  22561. };
  22562. theme.categoryAxis.splitLine.show = false;
  22563. /**
  22564. * Usage of query:
  22565. * `chart.on('click', query, handler);`
  22566. * The `query` can be:
  22567. * + The component type query string, only `mainType` or `mainType.subType`,
  22568. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  22569. * + The component query object, like:
  22570. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  22571. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  22572. * + The data query object, like:
  22573. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  22574. * + The other query object (cmponent customized query), like:
  22575. * `{element: 'some'}` (only available in custom series).
  22576. *
  22577. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  22578. * same as there is no such prop in the `query` object.
  22579. */
  22580. var ECEventProcessor =
  22581. /** @class */
  22582. function () {
  22583. function ECEventProcessor() {}
  22584. ECEventProcessor.prototype.normalizeQuery = function (query) {
  22585. var cptQuery = {};
  22586. var dataQuery = {};
  22587. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  22588. if (isString(query)) {
  22589. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  22590. cptQuery.mainType = condCptType.main || null;
  22591. cptQuery.subType = condCptType.sub || null;
  22592. } // `query` is an object, convert to {mainType, index, name, id}.
  22593. else {
  22594. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  22595. // can not be used in `compomentModel.filterForExposedEvent`.
  22596. var suffixes_1 = ['Index', 'Name', 'Id'];
  22597. var dataKeys_1 = {
  22598. name: 1,
  22599. dataIndex: 1,
  22600. dataType: 1
  22601. };
  22602. each(query, function (val, key) {
  22603. var reserved = false;
  22604. for (var i = 0; i < suffixes_1.length; i++) {
  22605. var propSuffix = suffixes_1[i];
  22606. var suffixPos = key.lastIndexOf(propSuffix);
  22607. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  22608. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  22609. if (mainType !== 'data') {
  22610. cptQuery.mainType = mainType;
  22611. cptQuery[propSuffix.toLowerCase()] = val;
  22612. reserved = true;
  22613. }
  22614. }
  22615. }
  22616. if (dataKeys_1.hasOwnProperty(key)) {
  22617. dataQuery[key] = val;
  22618. reserved = true;
  22619. }
  22620. if (!reserved) {
  22621. otherQuery[key] = val;
  22622. }
  22623. });
  22624. }
  22625. return {
  22626. cptQuery: cptQuery,
  22627. dataQuery: dataQuery,
  22628. otherQuery: otherQuery
  22629. };
  22630. };
  22631. ECEventProcessor.prototype.filter = function (eventType, query) {
  22632. // They should be assigned before each trigger call.
  22633. var eventInfo = this.eventInfo;
  22634. if (!eventInfo) {
  22635. return true;
  22636. }
  22637. var targetEl = eventInfo.targetEl;
  22638. var packedEvent = eventInfo.packedEvent;
  22639. var model = eventInfo.model;
  22640. var view = eventInfo.view; // For event like 'globalout'.
  22641. if (!model || !view) {
  22642. return true;
  22643. }
  22644. var cptQuery = query.cptQuery;
  22645. var dataQuery = query.dataQuery;
  22646. 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));
  22647. function check(query, host, prop, propOnHost) {
  22648. return query[prop] == null || host[propOnHost || prop] === query[prop];
  22649. }
  22650. };
  22651. ECEventProcessor.prototype.afterTrigger = function () {
  22652. // Make sure the eventInfo wont be used in next trigger.
  22653. this.eventInfo = null;
  22654. };
  22655. return ECEventProcessor;
  22656. }();
  22657. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  22658. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']); // Encoding visual for all series include which is filtered for legend drawing
  22659. var seriesSymbolTask = {
  22660. createOnAllSeries: true,
  22661. // For legend.
  22662. performRawSeries: true,
  22663. reset: function (seriesModel, ecModel) {
  22664. var data = seriesModel.getData();
  22665. if (seriesModel.legendIcon) {
  22666. data.setVisual('legendIcon', seriesModel.legendIcon);
  22667. }
  22668. if (!seriesModel.hasSymbolVisual) {
  22669. return;
  22670. }
  22671. var symbolOptions = {};
  22672. var symbolOptionsCb = {};
  22673. var hasCallback = false;
  22674. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  22675. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  22676. var val = seriesModel.get(symbolPropName);
  22677. if (isFunction(val)) {
  22678. hasCallback = true;
  22679. symbolOptionsCb[symbolPropName] = val;
  22680. } else {
  22681. symbolOptions[symbolPropName] = val;
  22682. }
  22683. }
  22684. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  22685. data.setVisual(extend({
  22686. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  22687. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  22688. }, symbolOptions)); // Only visible series has each data be visual encoded
  22689. if (ecModel.isSeriesFiltered(seriesModel)) {
  22690. return;
  22691. }
  22692. var symbolPropsCb = keys(symbolOptionsCb);
  22693. function dataEach(data, idx) {
  22694. var rawValue = seriesModel.getRawValue(idx);
  22695. var params = seriesModel.getDataParams(idx);
  22696. for (var i = 0; i < symbolPropsCb.length; i++) {
  22697. var symbolPropName = symbolPropsCb[i];
  22698. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  22699. }
  22700. }
  22701. return {
  22702. dataEach: hasCallback ? dataEach : null
  22703. };
  22704. }
  22705. };
  22706. var dataSymbolTask = {
  22707. createOnAllSeries: true,
  22708. // For legend.
  22709. performRawSeries: true,
  22710. reset: function (seriesModel, ecModel) {
  22711. if (!seriesModel.hasSymbolVisual) {
  22712. return;
  22713. } // Only visible series has each data be visual encoded
  22714. if (ecModel.isSeriesFiltered(seriesModel)) {
  22715. return;
  22716. }
  22717. var data = seriesModel.getData();
  22718. function dataEach(data, idx) {
  22719. var itemModel = data.getItemModel(idx);
  22720. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  22721. var symbolPropName = SYMBOL_PROPS[i];
  22722. var val = itemModel.getShallow(symbolPropName, true);
  22723. if (val != null) {
  22724. data.setItemVisual(idx, symbolPropName, val);
  22725. }
  22726. }
  22727. }
  22728. return {
  22729. dataEach: data.hasItemOption ? dataEach : null
  22730. };
  22731. }
  22732. };
  22733. /*
  22734. * Licensed to the Apache Software Foundation (ASF) under one
  22735. * or more contributor license agreements. See the NOTICE file
  22736. * distributed with this work for additional information
  22737. * regarding copyright ownership. The ASF licenses this file
  22738. * to you under the Apache License, Version 2.0 (the
  22739. * "License"); you may not use this file except in compliance
  22740. * with the License. You may obtain a copy of the License at
  22741. *
  22742. * http://www.apache.org/licenses/LICENSE-2.0
  22743. *
  22744. * Unless required by applicable law or agreed to in writing,
  22745. * software distributed under the License is distributed on an
  22746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22747. * KIND, either express or implied. See the License for the
  22748. * specific language governing permissions and limitations
  22749. * under the License.
  22750. */
  22751. /**
  22752. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22753. */
  22754. /*
  22755. * Licensed to the Apache Software Foundation (ASF) under one
  22756. * or more contributor license agreements. See the NOTICE file
  22757. * distributed with this work for additional information
  22758. * regarding copyright ownership. The ASF licenses this file
  22759. * to you under the Apache License, Version 2.0 (the
  22760. * "License"); you may not use this file except in compliance
  22761. * with the License. You may obtain a copy of the License at
  22762. *
  22763. * http://www.apache.org/licenses/LICENSE-2.0
  22764. *
  22765. * Unless required by applicable law or agreed to in writing,
  22766. * software distributed under the License is distributed on an
  22767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22768. * KIND, either express or implied. See the License for the
  22769. * specific language governing permissions and limitations
  22770. * under the License.
  22771. */
  22772. function getItemVisualFromData(data, dataIndex, key) {
  22773. switch (key) {
  22774. case 'color':
  22775. var style = data.getItemVisual(dataIndex, 'style');
  22776. return style[data.getVisual('drawType')];
  22777. case 'opacity':
  22778. return data.getItemVisual(dataIndex, 'style').opacity;
  22779. case 'symbol':
  22780. case 'symbolSize':
  22781. case 'liftZ':
  22782. return data.getItemVisual(dataIndex, key);
  22783. default:
  22784. if ("development" !== 'production') {
  22785. console.warn("Unknown visual type " + key);
  22786. }
  22787. }
  22788. }
  22789. function getVisualFromData(data, key) {
  22790. switch (key) {
  22791. case 'color':
  22792. var style = data.getVisual('style');
  22793. return style[data.getVisual('drawType')];
  22794. case 'opacity':
  22795. return data.getVisual('style').opacity;
  22796. case 'symbol':
  22797. case 'symbolSize':
  22798. case 'liftZ':
  22799. return data.getVisual(key);
  22800. default:
  22801. if ("development" !== 'production') {
  22802. console.warn("Unknown visual type " + key);
  22803. }
  22804. }
  22805. }
  22806. // Inlucdes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  22807. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  22808. function getSeriesIndices(ecModel, payload) {
  22809. var seriesIndices = [];
  22810. ecModel.eachComponent({
  22811. mainType: 'series',
  22812. subType: seriesType,
  22813. query: payload
  22814. }, function (seriesModel) {
  22815. seriesIndices.push(seriesModel.seriesIndex);
  22816. });
  22817. return seriesIndices;
  22818. }
  22819. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  22820. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  22821. payload = extend({}, payload);
  22822. if ("development" !== 'production') {
  22823. deprecateReplaceLog(payload.type, eventsMap[1]);
  22824. }
  22825. api.dispatchAction(extend(payload, {
  22826. type: eventsMap[1],
  22827. seriesIndex: getSeriesIndices(ecModel, payload)
  22828. }));
  22829. });
  22830. });
  22831. }
  22832. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  22833. var legacyEventName = type + eventPostfix;
  22834. if (!ecIns.isSilent(legacyEventName)) {
  22835. if ("development" !== 'production') {
  22836. deprecateLog("event " + legacyEventName + " is deprecated.");
  22837. }
  22838. ecModel.eachComponent({
  22839. mainType: 'series',
  22840. subType: 'pie'
  22841. }, function (seriesModel) {
  22842. var seriesIndex = seriesModel.seriesIndex;
  22843. var selectedMap = seriesModel.option.selectedMap;
  22844. var selected = payload.selected;
  22845. for (var i = 0; i < selected.length; i++) {
  22846. if (selected[i].seriesIndex === seriesIndex) {
  22847. var data = seriesModel.getData();
  22848. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  22849. ecIns.trigger(legacyEventName, {
  22850. type: legacyEventName,
  22851. seriesId: seriesModel.id,
  22852. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  22853. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  22854. });
  22855. }
  22856. }
  22857. });
  22858. }
  22859. }
  22860. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  22861. messageCenter.on('selectchanged', function (params) {
  22862. var ecModel = api.getModel();
  22863. if (params.isFromClick) {
  22864. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  22865. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  22866. } else if (params.fromAction === 'select') {
  22867. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  22868. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  22869. } else if (params.fromAction === 'unselect') {
  22870. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  22871. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  22872. }
  22873. });
  22874. }
  22875. /*
  22876. * Licensed to the Apache Software Foundation (ASF) under one
  22877. * or more contributor license agreements. See the NOTICE file
  22878. * distributed with this work for additional information
  22879. * regarding copyright ownership. The ASF licenses this file
  22880. * to you under the Apache License, Version 2.0 (the
  22881. * "License"); you may not use this file except in compliance
  22882. * with the License. You may obtain a copy of the License at
  22883. *
  22884. * http://www.apache.org/licenses/LICENSE-2.0
  22885. *
  22886. * Unless required by applicable law or agreed to in writing,
  22887. * software distributed under the License is distributed on an
  22888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22889. * KIND, either express or implied. See the License for the
  22890. * specific language governing permissions and limitations
  22891. * under the License.
  22892. */
  22893. /**
  22894. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22895. */
  22896. /*
  22897. * Licensed to the Apache Software Foundation (ASF) under one
  22898. * or more contributor license agreements. See the NOTICE file
  22899. * distributed with this work for additional information
  22900. * regarding copyright ownership. The ASF licenses this file
  22901. * to you under the Apache License, Version 2.0 (the
  22902. * "License"); you may not use this file except in compliance
  22903. * with the License. You may obtain a copy of the License at
  22904. *
  22905. * http://www.apache.org/licenses/LICENSE-2.0
  22906. *
  22907. * Unless required by applicable law or agreed to in writing,
  22908. * software distributed under the License is distributed on an
  22909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22910. * KIND, either express or implied. See the License for the
  22911. * specific language governing permissions and limitations
  22912. * under the License.
  22913. */
  22914. function findEventDispatcher(target, det, returnFirstMatch) {
  22915. var found;
  22916. while (target) {
  22917. if (det(target)) {
  22918. found = target;
  22919. if (returnFirstMatch) {
  22920. break;
  22921. }
  22922. }
  22923. target = target.__hostTarget || target.parent;
  22924. }
  22925. return found;
  22926. }
  22927. var wmUniqueIndex = Math.round(Math.random() * 9);
  22928. var supportDefineProperty = typeof Object.defineProperty === 'function';
  22929. var WeakMap = (function () {
  22930. function WeakMap() {
  22931. this._id = '__ec_inner_' + wmUniqueIndex++;
  22932. }
  22933. WeakMap.prototype.get = function (key) {
  22934. return this._guard(key)[this._id];
  22935. };
  22936. WeakMap.prototype.set = function (key, value) {
  22937. var target = this._guard(key);
  22938. if (supportDefineProperty) {
  22939. Object.defineProperty(target, this._id, {
  22940. value: value,
  22941. enumerable: false,
  22942. configurable: true
  22943. });
  22944. }
  22945. else {
  22946. target[this._id] = value;
  22947. }
  22948. return this;
  22949. };
  22950. WeakMap.prototype["delete"] = function (key) {
  22951. if (this.has(key)) {
  22952. delete this._guard(key)[this._id];
  22953. return true;
  22954. }
  22955. return false;
  22956. };
  22957. WeakMap.prototype.has = function (key) {
  22958. return !!this._guard(key)[this._id];
  22959. };
  22960. WeakMap.prototype._guard = function (key) {
  22961. if (key !== Object(key)) {
  22962. throw TypeError('Value of WeakMap is not a non-null object.');
  22963. }
  22964. return key;
  22965. };
  22966. return WeakMap;
  22967. }());
  22968. /**
  22969. * Triangle shape
  22970. * @inner
  22971. */
  22972. var Triangle = Path.extend({
  22973. type: 'triangle',
  22974. shape: {
  22975. cx: 0,
  22976. cy: 0,
  22977. width: 0,
  22978. height: 0
  22979. },
  22980. buildPath: function (path, shape) {
  22981. var cx = shape.cx;
  22982. var cy = shape.cy;
  22983. var width = shape.width / 2;
  22984. var height = shape.height / 2;
  22985. path.moveTo(cx, cy - height);
  22986. path.lineTo(cx + width, cy + height);
  22987. path.lineTo(cx - width, cy + height);
  22988. path.closePath();
  22989. }
  22990. });
  22991. /**
  22992. * Diamond shape
  22993. * @inner
  22994. */
  22995. var Diamond = Path.extend({
  22996. type: 'diamond',
  22997. shape: {
  22998. cx: 0,
  22999. cy: 0,
  23000. width: 0,
  23001. height: 0
  23002. },
  23003. buildPath: function (path, shape) {
  23004. var cx = shape.cx;
  23005. var cy = shape.cy;
  23006. var width = shape.width / 2;
  23007. var height = shape.height / 2;
  23008. path.moveTo(cx, cy - height);
  23009. path.lineTo(cx + width, cy);
  23010. path.lineTo(cx, cy + height);
  23011. path.lineTo(cx - width, cy);
  23012. path.closePath();
  23013. }
  23014. });
  23015. /**
  23016. * Pin shape
  23017. * @inner
  23018. */
  23019. var Pin = Path.extend({
  23020. type: 'pin',
  23021. shape: {
  23022. // x, y on the cusp
  23023. x: 0,
  23024. y: 0,
  23025. width: 0,
  23026. height: 0
  23027. },
  23028. buildPath: function (path, shape) {
  23029. var x = shape.x;
  23030. var y = shape.y;
  23031. var w = shape.width / 5 * 3; // Height must be larger than width
  23032. var h = Math.max(w, shape.height);
  23033. var r = w / 2; // Dist on y with tangent point and circle center
  23034. var dy = r * r / (h - r);
  23035. var cy = y - h + r + dy;
  23036. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  23037. var dx = Math.cos(angle) * r;
  23038. var tanX = Math.sin(angle);
  23039. var tanY = Math.cos(angle);
  23040. var cpLen = r * 0.6;
  23041. var cpLen2 = r * 0.7;
  23042. path.moveTo(x - dx, cy + dy);
  23043. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  23044. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  23045. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  23046. path.closePath();
  23047. }
  23048. });
  23049. /**
  23050. * Arrow shape
  23051. * @inner
  23052. */
  23053. var Arrow = Path.extend({
  23054. type: 'arrow',
  23055. shape: {
  23056. x: 0,
  23057. y: 0,
  23058. width: 0,
  23059. height: 0
  23060. },
  23061. buildPath: function (ctx, shape) {
  23062. var height = shape.height;
  23063. var width = shape.width;
  23064. var x = shape.x;
  23065. var y = shape.y;
  23066. var dx = width / 3 * 2;
  23067. ctx.moveTo(x, y);
  23068. ctx.lineTo(x + dx, y + height);
  23069. ctx.lineTo(x, y + height / 4 * 3);
  23070. ctx.lineTo(x - dx, y + height);
  23071. ctx.lineTo(x, y);
  23072. ctx.closePath();
  23073. }
  23074. });
  23075. /**
  23076. * Map of path contructors
  23077. */
  23078. // TODO Use function to build symbol path.
  23079. var symbolCtors = {
  23080. line: Line,
  23081. rect: Rect,
  23082. roundRect: Rect,
  23083. square: Rect,
  23084. circle: Circle,
  23085. diamond: Diamond,
  23086. pin: Pin,
  23087. arrow: Arrow,
  23088. triangle: Triangle
  23089. };
  23090. var symbolShapeMakers = {
  23091. line: function (x, y, w, h, shape) {
  23092. shape.x1 = x;
  23093. shape.y1 = y + h / 2;
  23094. shape.x2 = x + w;
  23095. shape.y2 = y + h / 2;
  23096. },
  23097. rect: function (x, y, w, h, shape) {
  23098. shape.x = x;
  23099. shape.y = y;
  23100. shape.width = w;
  23101. shape.height = h;
  23102. },
  23103. roundRect: function (x, y, w, h, shape) {
  23104. shape.x = x;
  23105. shape.y = y;
  23106. shape.width = w;
  23107. shape.height = h;
  23108. shape.r = Math.min(w, h) / 4;
  23109. },
  23110. square: function (x, y, w, h, shape) {
  23111. var size = Math.min(w, h);
  23112. shape.x = x;
  23113. shape.y = y;
  23114. shape.width = size;
  23115. shape.height = size;
  23116. },
  23117. circle: function (x, y, w, h, shape) {
  23118. // Put circle in the center of square
  23119. shape.cx = x + w / 2;
  23120. shape.cy = y + h / 2;
  23121. shape.r = Math.min(w, h) / 2;
  23122. },
  23123. diamond: function (x, y, w, h, shape) {
  23124. shape.cx = x + w / 2;
  23125. shape.cy = y + h / 2;
  23126. shape.width = w;
  23127. shape.height = h;
  23128. },
  23129. pin: function (x, y, w, h, shape) {
  23130. shape.x = x + w / 2;
  23131. shape.y = y + h / 2;
  23132. shape.width = w;
  23133. shape.height = h;
  23134. },
  23135. arrow: function (x, y, w, h, shape) {
  23136. shape.x = x + w / 2;
  23137. shape.y = y + h / 2;
  23138. shape.width = w;
  23139. shape.height = h;
  23140. },
  23141. triangle: function (x, y, w, h, shape) {
  23142. shape.cx = x + w / 2;
  23143. shape.cy = y + h / 2;
  23144. shape.width = w;
  23145. shape.height = h;
  23146. }
  23147. };
  23148. var symbolBuildProxies = {};
  23149. each(symbolCtors, function (Ctor, name) {
  23150. symbolBuildProxies[name] = new Ctor();
  23151. });
  23152. var SymbolClz = Path.extend({
  23153. type: 'symbol',
  23154. shape: {
  23155. symbolType: '',
  23156. x: 0,
  23157. y: 0,
  23158. width: 0,
  23159. height: 0
  23160. },
  23161. calculateTextPosition: function (out, config, rect) {
  23162. var res = calculateTextPosition(out, config, rect);
  23163. var shape = this.shape;
  23164. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  23165. res.y = rect.y + rect.height * 0.4;
  23166. }
  23167. return res;
  23168. },
  23169. buildPath: function (ctx, shape, inBundle) {
  23170. var symbolType = shape.symbolType;
  23171. if (symbolType !== 'none') {
  23172. var proxySymbol = symbolBuildProxies[symbolType];
  23173. if (!proxySymbol) {
  23174. // Default rect
  23175. symbolType = 'rect';
  23176. proxySymbol = symbolBuildProxies[symbolType];
  23177. }
  23178. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  23179. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  23180. }
  23181. }
  23182. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  23183. function symbolPathSetColor(color, innerColor) {
  23184. if (this.type !== 'image') {
  23185. var symbolStyle = this.style;
  23186. if (this.__isEmptyBrush) {
  23187. symbolStyle.stroke = color;
  23188. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView
  23189. symbolStyle.lineWidth = 2;
  23190. } else if (this.shape.symbolType === 'line') {
  23191. symbolStyle.stroke = color;
  23192. } else {
  23193. symbolStyle.fill = color;
  23194. }
  23195. this.markRedraw();
  23196. }
  23197. }
  23198. /**
  23199. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  23200. */
  23201. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  23202. keepAspect) {
  23203. // TODO Support image object, DynamicImage.
  23204. var isEmpty = symbolType.indexOf('empty') === 0;
  23205. if (isEmpty) {
  23206. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  23207. }
  23208. var symbolPath;
  23209. if (symbolType.indexOf('image://') === 0) {
  23210. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23211. } else if (symbolType.indexOf('path://') === 0) {
  23212. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23213. } else {
  23214. symbolPath = new SymbolClz({
  23215. shape: {
  23216. symbolType: symbolType,
  23217. x: x,
  23218. y: y,
  23219. width: w,
  23220. height: h
  23221. }
  23222. });
  23223. }
  23224. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  23225. symbolPath.setColor = symbolPathSetColor;
  23226. if (color) {
  23227. symbolPath.setColor(color);
  23228. }
  23229. return symbolPath;
  23230. }
  23231. function normalizeSymbolSize(symbolSize) {
  23232. if (!isArray(symbolSize)) {
  23233. symbolSize = [+symbolSize, +symbolSize];
  23234. }
  23235. return [symbolSize[0] || 0, symbolSize[1] || 0];
  23236. }
  23237. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  23238. if (symbolOffset == null) {
  23239. return;
  23240. }
  23241. if (!isArray(symbolOffset)) {
  23242. symbolOffset = [symbolOffset, symbolOffset];
  23243. }
  23244. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  23245. }
  23246. function isSafeNum(num) {
  23247. return isFinite(num);
  23248. }
  23249. function createLinearGradient(ctx, obj, rect) {
  23250. var x = obj.x == null ? 0 : obj.x;
  23251. var x2 = obj.x2 == null ? 1 : obj.x2;
  23252. var y = obj.y == null ? 0 : obj.y;
  23253. var y2 = obj.y2 == null ? 0 : obj.y2;
  23254. if (!obj.global) {
  23255. x = x * rect.width + rect.x;
  23256. x2 = x2 * rect.width + rect.x;
  23257. y = y * rect.height + rect.y;
  23258. y2 = y2 * rect.height + rect.y;
  23259. }
  23260. x = isSafeNum(x) ? x : 0;
  23261. x2 = isSafeNum(x2) ? x2 : 1;
  23262. y = isSafeNum(y) ? y : 0;
  23263. y2 = isSafeNum(y2) ? y2 : 0;
  23264. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  23265. return canvasGradient;
  23266. }
  23267. function createRadialGradient(ctx, obj, rect) {
  23268. var width = rect.width;
  23269. var height = rect.height;
  23270. var min = Math.min(width, height);
  23271. var x = obj.x == null ? 0.5 : obj.x;
  23272. var y = obj.y == null ? 0.5 : obj.y;
  23273. var r = obj.r == null ? 0.5 : obj.r;
  23274. if (!obj.global) {
  23275. x = x * width + rect.x;
  23276. y = y * height + rect.y;
  23277. r = r * min;
  23278. }
  23279. x = isSafeNum(x) ? x : 0.5;
  23280. y = isSafeNum(y) ? y : 0.5;
  23281. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  23282. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  23283. return canvasGradient;
  23284. }
  23285. function getCanvasGradient(ctx, obj, rect) {
  23286. var canvasGradient = obj.type === 'radial'
  23287. ? createRadialGradient(ctx, obj, rect)
  23288. : createLinearGradient(ctx, obj, rect);
  23289. var colorStops = obj.colorStops;
  23290. for (var i = 0; i < colorStops.length; i++) {
  23291. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  23292. }
  23293. return canvasGradient;
  23294. }
  23295. function isClipPathChanged(clipPaths, prevClipPaths) {
  23296. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  23297. return false;
  23298. }
  23299. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  23300. return true;
  23301. }
  23302. for (var i = 0; i < clipPaths.length; i++) {
  23303. if (clipPaths[i] !== prevClipPaths[i]) {
  23304. return true;
  23305. }
  23306. }
  23307. return false;
  23308. }
  23309. function parseInt10(val) {
  23310. return parseInt(val, 10);
  23311. }
  23312. function getSize(root, whIdx, opts) {
  23313. var wh = ['width', 'height'][whIdx];
  23314. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  23315. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  23316. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  23317. if (opts[wh] != null && opts[wh] !== 'auto') {
  23318. return parseFloat(opts[wh]);
  23319. }
  23320. var stl = document.defaultView.getComputedStyle(root);
  23321. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  23322. - (parseInt10(stl[plt]) || 0)
  23323. - (parseInt10(stl[prb]) || 0)) | 0;
  23324. }
  23325. function normalizeLineDash(lineType, lineWidth) {
  23326. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  23327. return null;
  23328. }
  23329. return lineType === 'dashed'
  23330. ? [4 * lineWidth, 2 * lineWidth]
  23331. : lineType === 'dotted'
  23332. ? [lineWidth]
  23333. : isNumber(lineType)
  23334. ? [lineType] : isArray(lineType) ? lineType : null;
  23335. }
  23336. function getLineDash(el) {
  23337. var style = el.style;
  23338. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  23339. var lineDashOffset = style.lineDashOffset;
  23340. if (lineDash) {
  23341. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  23342. if (lineScale_1 && lineScale_1 !== 1) {
  23343. lineDash = map(lineDash, function (rawVal) {
  23344. return rawVal / lineScale_1;
  23345. });
  23346. lineDashOffset /= lineScale_1;
  23347. }
  23348. }
  23349. return [lineDash, lineDashOffset];
  23350. }
  23351. var pathProxyForDraw = new PathProxy(true);
  23352. function styleHasStroke(style) {
  23353. var stroke = style.stroke;
  23354. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  23355. }
  23356. function isValidStrokeFillStyle(strokeOrFill) {
  23357. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  23358. }
  23359. function styleHasFill(style) {
  23360. var fill = style.fill;
  23361. return fill != null && fill !== 'none';
  23362. }
  23363. function doFillPath(ctx, style) {
  23364. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  23365. var originalGlobalAlpha = ctx.globalAlpha;
  23366. ctx.globalAlpha = style.fillOpacity * style.opacity;
  23367. ctx.fill();
  23368. ctx.globalAlpha = originalGlobalAlpha;
  23369. }
  23370. else {
  23371. ctx.fill();
  23372. }
  23373. }
  23374. function doStrokePath(ctx, style) {
  23375. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  23376. var originalGlobalAlpha = ctx.globalAlpha;
  23377. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  23378. ctx.stroke();
  23379. ctx.globalAlpha = originalGlobalAlpha;
  23380. }
  23381. else {
  23382. ctx.stroke();
  23383. }
  23384. }
  23385. function createCanvasPattern(ctx, pattern, el) {
  23386. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  23387. if (isImageReady(image)) {
  23388. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  23389. if (typeof DOMMatrix === 'function'
  23390. && canvasPattern
  23391. && canvasPattern.setTransform) {
  23392. var matrix = new DOMMatrix();
  23393. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  23394. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  23395. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  23396. canvasPattern.setTransform(matrix);
  23397. }
  23398. return canvasPattern;
  23399. }
  23400. }
  23401. function brushPath(ctx, el, style, inBatch) {
  23402. var _a;
  23403. var hasStroke = styleHasStroke(style);
  23404. var hasFill = styleHasFill(style);
  23405. var strokePercent = style.strokePercent;
  23406. var strokePart = strokePercent < 1;
  23407. var firstDraw = !el.path;
  23408. if ((!el.silent || strokePart) && firstDraw) {
  23409. el.createPathProxy();
  23410. }
  23411. var path = el.path || pathProxyForDraw;
  23412. var dirtyFlag = el.__dirty;
  23413. if (!inBatch) {
  23414. var fill = style.fill;
  23415. var stroke = style.stroke;
  23416. var hasFillGradient = hasFill && !!fill.colorStops;
  23417. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  23418. var hasFillPattern = hasFill && !!fill.image;
  23419. var hasStrokePattern = hasStroke && !!stroke.image;
  23420. var fillGradient = void 0;
  23421. var strokeGradient = void 0;
  23422. var fillPattern = void 0;
  23423. var strokePattern = void 0;
  23424. var rect = void 0;
  23425. if (hasFillGradient || hasStrokeGradient) {
  23426. rect = el.getBoundingRect();
  23427. }
  23428. if (hasFillGradient) {
  23429. fillGradient = dirtyFlag
  23430. ? getCanvasGradient(ctx, fill, rect)
  23431. : el.__canvasFillGradient;
  23432. el.__canvasFillGradient = fillGradient;
  23433. }
  23434. if (hasStrokeGradient) {
  23435. strokeGradient = dirtyFlag
  23436. ? getCanvasGradient(ctx, stroke, rect)
  23437. : el.__canvasStrokeGradient;
  23438. el.__canvasStrokeGradient = strokeGradient;
  23439. }
  23440. if (hasFillPattern) {
  23441. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  23442. ? createCanvasPattern(ctx, fill, el)
  23443. : el.__canvasFillPattern;
  23444. el.__canvasFillPattern = fillPattern;
  23445. }
  23446. if (hasStrokePattern) {
  23447. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  23448. ? createCanvasPattern(ctx, stroke, el)
  23449. : el.__canvasStrokePattern;
  23450. el.__canvasStrokePattern = fillPattern;
  23451. }
  23452. if (hasFillGradient) {
  23453. ctx.fillStyle = fillGradient;
  23454. }
  23455. else if (hasFillPattern) {
  23456. if (fillPattern) {
  23457. ctx.fillStyle = fillPattern;
  23458. }
  23459. else {
  23460. hasFill = false;
  23461. }
  23462. }
  23463. if (hasStrokeGradient) {
  23464. ctx.strokeStyle = strokeGradient;
  23465. }
  23466. else if (hasStrokePattern) {
  23467. if (strokePattern) {
  23468. ctx.strokeStyle = strokePattern;
  23469. }
  23470. else {
  23471. hasStroke = false;
  23472. }
  23473. }
  23474. }
  23475. var scale = el.getGlobalScale();
  23476. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  23477. var lineDash;
  23478. var lineDashOffset;
  23479. if (ctx.setLineDash && style.lineDash) {
  23480. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  23481. }
  23482. var needsRebuild = true;
  23483. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  23484. path.setDPR(ctx.dpr);
  23485. if (strokePart) {
  23486. path.setContext(null);
  23487. }
  23488. else {
  23489. path.setContext(ctx);
  23490. needsRebuild = false;
  23491. }
  23492. path.reset();
  23493. el.buildPath(path, el.shape, inBatch);
  23494. path.toStatic();
  23495. el.pathUpdated();
  23496. }
  23497. if (needsRebuild) {
  23498. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  23499. }
  23500. if (lineDash) {
  23501. ctx.setLineDash(lineDash);
  23502. ctx.lineDashOffset = lineDashOffset;
  23503. }
  23504. if (!inBatch) {
  23505. if (style.strokeFirst) {
  23506. if (hasStroke) {
  23507. doStrokePath(ctx, style);
  23508. }
  23509. if (hasFill) {
  23510. doFillPath(ctx, style);
  23511. }
  23512. }
  23513. else {
  23514. if (hasFill) {
  23515. doFillPath(ctx, style);
  23516. }
  23517. if (hasStroke) {
  23518. doStrokePath(ctx, style);
  23519. }
  23520. }
  23521. }
  23522. if (lineDash) {
  23523. ctx.setLineDash([]);
  23524. }
  23525. }
  23526. function brushImage(ctx, el, style) {
  23527. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  23528. if (!image || !isImageReady(image)) {
  23529. return;
  23530. }
  23531. var x = style.x || 0;
  23532. var y = style.y || 0;
  23533. var width = el.getWidth();
  23534. var height = el.getHeight();
  23535. var aspect = image.width / image.height;
  23536. if (width == null && height != null) {
  23537. width = height * aspect;
  23538. }
  23539. else if (height == null && width != null) {
  23540. height = width / aspect;
  23541. }
  23542. else if (width == null && height == null) {
  23543. width = image.width;
  23544. height = image.height;
  23545. }
  23546. if (style.sWidth && style.sHeight) {
  23547. var sx = style.sx || 0;
  23548. var sy = style.sy || 0;
  23549. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  23550. }
  23551. else if (style.sx && style.sy) {
  23552. var sx = style.sx;
  23553. var sy = style.sy;
  23554. var sWidth = width - sx;
  23555. var sHeight = height - sy;
  23556. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  23557. }
  23558. else {
  23559. ctx.drawImage(image, x, y, width, height);
  23560. }
  23561. }
  23562. function brushText(ctx, el, style) {
  23563. var _a;
  23564. var text = style.text;
  23565. text != null && (text += '');
  23566. if (text) {
  23567. ctx.font = style.font || DEFAULT_FONT;
  23568. ctx.textAlign = style.textAlign;
  23569. ctx.textBaseline = style.textBaseline;
  23570. var lineDash = void 0;
  23571. var lineDashOffset = void 0;
  23572. if (ctx.setLineDash && style.lineDash) {
  23573. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  23574. }
  23575. if (lineDash) {
  23576. ctx.setLineDash(lineDash);
  23577. ctx.lineDashOffset = lineDashOffset;
  23578. }
  23579. if (style.strokeFirst) {
  23580. if (styleHasStroke(style)) {
  23581. ctx.strokeText(text, style.x, style.y);
  23582. }
  23583. if (styleHasFill(style)) {
  23584. ctx.fillText(text, style.x, style.y);
  23585. }
  23586. }
  23587. else {
  23588. if (styleHasFill(style)) {
  23589. ctx.fillText(text, style.x, style.y);
  23590. }
  23591. if (styleHasStroke(style)) {
  23592. ctx.strokeText(text, style.x, style.y);
  23593. }
  23594. }
  23595. if (lineDash) {
  23596. ctx.setLineDash([]);
  23597. }
  23598. }
  23599. }
  23600. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  23601. var STROKE_PROPS = [
  23602. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  23603. ];
  23604. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  23605. var styleChanged = false;
  23606. if (!forceSetAll) {
  23607. prevStyle = prevStyle || {};
  23608. if (style === prevStyle) {
  23609. return false;
  23610. }
  23611. }
  23612. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  23613. flushPathDrawn(ctx, scope);
  23614. styleChanged = true;
  23615. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  23616. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  23617. }
  23618. if (forceSetAll || style.blend !== prevStyle.blend) {
  23619. if (!styleChanged) {
  23620. flushPathDrawn(ctx, scope);
  23621. styleChanged = true;
  23622. }
  23623. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  23624. }
  23625. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  23626. var propName = SHADOW_NUMBER_PROPS[i];
  23627. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  23628. if (!styleChanged) {
  23629. flushPathDrawn(ctx, scope);
  23630. styleChanged = true;
  23631. }
  23632. ctx[propName] = ctx.dpr * (style[propName] || 0);
  23633. }
  23634. }
  23635. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  23636. if (!styleChanged) {
  23637. flushPathDrawn(ctx, scope);
  23638. styleChanged = true;
  23639. }
  23640. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  23641. }
  23642. return styleChanged;
  23643. }
  23644. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  23645. var style = getStyle(el, scope.inHover);
  23646. var prevStyle = forceSetAll
  23647. ? null
  23648. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  23649. if (style === prevStyle) {
  23650. return false;
  23651. }
  23652. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  23653. if (forceSetAll || style.fill !== prevStyle.fill) {
  23654. if (!styleChanged) {
  23655. flushPathDrawn(ctx, scope);
  23656. styleChanged = true;
  23657. }
  23658. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  23659. }
  23660. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  23661. if (!styleChanged) {
  23662. flushPathDrawn(ctx, scope);
  23663. styleChanged = true;
  23664. }
  23665. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  23666. }
  23667. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  23668. if (!styleChanged) {
  23669. flushPathDrawn(ctx, scope);
  23670. styleChanged = true;
  23671. }
  23672. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  23673. }
  23674. if (el.hasStroke()) {
  23675. var lineWidth = style.lineWidth;
  23676. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  23677. if (ctx.lineWidth !== newLineWidth) {
  23678. if (!styleChanged) {
  23679. flushPathDrawn(ctx, scope);
  23680. styleChanged = true;
  23681. }
  23682. ctx.lineWidth = newLineWidth;
  23683. }
  23684. }
  23685. for (var i = 0; i < STROKE_PROPS.length; i++) {
  23686. var prop = STROKE_PROPS[i];
  23687. var propName = prop[0];
  23688. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  23689. if (!styleChanged) {
  23690. flushPathDrawn(ctx, scope);
  23691. styleChanged = true;
  23692. }
  23693. ctx[propName] = style[propName] || prop[1];
  23694. }
  23695. }
  23696. return styleChanged;
  23697. }
  23698. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  23699. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  23700. }
  23701. function setContextTransform(ctx, el) {
  23702. var m = el.transform;
  23703. var dpr = ctx.dpr || 1;
  23704. if (m) {
  23705. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  23706. }
  23707. else {
  23708. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  23709. }
  23710. }
  23711. function updateClipStatus(clipPaths, ctx, scope) {
  23712. var allClipped = false;
  23713. for (var i = 0; i < clipPaths.length; i++) {
  23714. var clipPath = clipPaths[i];
  23715. allClipped = allClipped || clipPath.isZeroArea();
  23716. setContextTransform(ctx, clipPath);
  23717. ctx.beginPath();
  23718. clipPath.buildPath(ctx, clipPath.shape);
  23719. ctx.clip();
  23720. }
  23721. scope.allClipped = allClipped;
  23722. }
  23723. function isTransformChanged(m0, m1) {
  23724. if (m0 && m1) {
  23725. return m0[0] !== m1[0]
  23726. || m0[1] !== m1[1]
  23727. || m0[2] !== m1[2]
  23728. || m0[3] !== m1[3]
  23729. || m0[4] !== m1[4]
  23730. || m0[5] !== m1[5];
  23731. }
  23732. else if (!m0 && !m1) {
  23733. return false;
  23734. }
  23735. return true;
  23736. }
  23737. var DRAW_TYPE_PATH = 1;
  23738. var DRAW_TYPE_IMAGE = 2;
  23739. var DRAW_TYPE_TEXT = 3;
  23740. var DRAW_TYPE_INCREMENTAL = 4;
  23741. function canPathBatch(style) {
  23742. var hasFill = styleHasFill(style);
  23743. var hasStroke = styleHasStroke(style);
  23744. return !(style.lineDash
  23745. || !(+hasFill ^ +hasStroke)
  23746. || (hasFill && typeof style.fill !== 'string')
  23747. || (hasStroke && typeof style.stroke !== 'string')
  23748. || style.strokePercent < 1
  23749. || style.strokeOpacity < 1
  23750. || style.fillOpacity < 1);
  23751. }
  23752. function flushPathDrawn(ctx, scope) {
  23753. scope.batchFill && ctx.fill();
  23754. scope.batchStroke && ctx.stroke();
  23755. scope.batchFill = '';
  23756. scope.batchStroke = '';
  23757. }
  23758. function getStyle(el, inHover) {
  23759. return inHover ? (el.__hoverStyle || el.style) : el.style;
  23760. }
  23761. function brushSingle(ctx, el) {
  23762. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  23763. }
  23764. function brush(ctx, el, scope, isLast) {
  23765. var m = el.transform;
  23766. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  23767. el.__dirty &= ~REDRAW_BIT;
  23768. el.__isRendered = false;
  23769. return;
  23770. }
  23771. var clipPaths = el.__clipPaths;
  23772. var prevElClipPaths = scope.prevElClipPaths;
  23773. var forceSetTransform = false;
  23774. var forceSetStyle = false;
  23775. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  23776. if (prevElClipPaths && prevElClipPaths.length) {
  23777. flushPathDrawn(ctx, scope);
  23778. ctx.restore();
  23779. forceSetStyle = forceSetTransform = true;
  23780. scope.prevElClipPaths = null;
  23781. scope.allClipped = false;
  23782. scope.prevEl = null;
  23783. }
  23784. if (clipPaths && clipPaths.length) {
  23785. flushPathDrawn(ctx, scope);
  23786. ctx.save();
  23787. updateClipStatus(clipPaths, ctx, scope);
  23788. forceSetTransform = true;
  23789. }
  23790. scope.prevElClipPaths = clipPaths;
  23791. }
  23792. if (scope.allClipped) {
  23793. el.__isRendered = false;
  23794. return;
  23795. }
  23796. el.beforeBrush && el.beforeBrush();
  23797. el.innerBeforeBrush();
  23798. var prevEl = scope.prevEl;
  23799. if (!prevEl) {
  23800. forceSetStyle = forceSetTransform = true;
  23801. }
  23802. var canBatchPath = el instanceof Path
  23803. && el.autoBatch
  23804. && canPathBatch(el.style);
  23805. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  23806. flushPathDrawn(ctx, scope);
  23807. setContextTransform(ctx, el);
  23808. }
  23809. else if (!canBatchPath) {
  23810. flushPathDrawn(ctx, scope);
  23811. }
  23812. var style = getStyle(el, scope.inHover);
  23813. if (el instanceof Path) {
  23814. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  23815. forceSetStyle = true;
  23816. scope.lastDrawType = DRAW_TYPE_PATH;
  23817. }
  23818. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  23819. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  23820. ctx.beginPath();
  23821. }
  23822. brushPath(ctx, el, style, canBatchPath);
  23823. if (canBatchPath) {
  23824. scope.batchFill = style.fill || '';
  23825. scope.batchStroke = style.stroke || '';
  23826. }
  23827. }
  23828. else {
  23829. if (el instanceof TSpan) {
  23830. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  23831. forceSetStyle = true;
  23832. scope.lastDrawType = DRAW_TYPE_TEXT;
  23833. }
  23834. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  23835. brushText(ctx, el, style);
  23836. }
  23837. else if (el instanceof ZRImage) {
  23838. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  23839. forceSetStyle = true;
  23840. scope.lastDrawType = DRAW_TYPE_IMAGE;
  23841. }
  23842. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  23843. brushImage(ctx, el, style);
  23844. }
  23845. else if (el.getTemporalDisplayables) {
  23846. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  23847. forceSetStyle = true;
  23848. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  23849. }
  23850. brushIncremental(ctx, el, scope);
  23851. }
  23852. }
  23853. if (canBatchPath && isLast) {
  23854. flushPathDrawn(ctx, scope);
  23855. }
  23856. el.innerAfterBrush();
  23857. el.afterBrush && el.afterBrush();
  23858. scope.prevEl = el;
  23859. el.__dirty = 0;
  23860. el.__isRendered = true;
  23861. }
  23862. function brushIncremental(ctx, el, scope) {
  23863. var displayables = el.getDisplayables();
  23864. var temporalDisplayables = el.getTemporalDisplayables();
  23865. ctx.save();
  23866. var innerScope = {
  23867. prevElClipPaths: null,
  23868. prevEl: null,
  23869. allClipped: false,
  23870. viewWidth: scope.viewWidth,
  23871. viewHeight: scope.viewHeight,
  23872. inHover: scope.inHover
  23873. };
  23874. var i;
  23875. var len;
  23876. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  23877. var displayable = displayables[i];
  23878. displayable.beforeBrush && displayable.beforeBrush();
  23879. displayable.innerBeforeBrush();
  23880. brush(ctx, displayable, innerScope, i === len - 1);
  23881. displayable.innerAfterBrush();
  23882. displayable.afterBrush && displayable.afterBrush();
  23883. innerScope.prevEl = displayable;
  23884. }
  23885. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  23886. var displayable = temporalDisplayables[i_1];
  23887. displayable.beforeBrush && displayable.beforeBrush();
  23888. displayable.innerBeforeBrush();
  23889. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  23890. displayable.innerAfterBrush();
  23891. displayable.afterBrush && displayable.afterBrush();
  23892. innerScope.prevEl = displayable;
  23893. }
  23894. el.clearTemporalDisplayables();
  23895. el.notClear = true;
  23896. ctx.restore();
  23897. }
  23898. var decalMap = new WeakMap();
  23899. var decalCache = new LRU(100);
  23900. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  23901. /**
  23902. * Create or update pattern image from decal options
  23903. *
  23904. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  23905. * @return {Pattern} pattern with generated image, null if no decal
  23906. */
  23907. function createOrUpdatePatternFromDecal(decalObject, api) {
  23908. if (decalObject === 'none') {
  23909. return null;
  23910. }
  23911. var dpr = api.getDevicePixelRatio();
  23912. var zr = api.getZr();
  23913. var isSVG = zr.painter.type === 'svg';
  23914. if (decalObject.dirty) {
  23915. decalMap["delete"](decalObject);
  23916. }
  23917. var oldPattern = decalMap.get(decalObject);
  23918. if (oldPattern) {
  23919. return oldPattern;
  23920. }
  23921. var decalOpt = defaults(decalObject, {
  23922. symbol: 'rect',
  23923. symbolSize: 1,
  23924. symbolKeepAspect: true,
  23925. color: 'rgba(0, 0, 0, 0.2)',
  23926. backgroundColor: null,
  23927. dashArrayX: 5,
  23928. dashArrayY: 5,
  23929. rotation: 0,
  23930. maxTileWidth: 512,
  23931. maxTileHeight: 512
  23932. });
  23933. if (decalOpt.backgroundColor === 'none') {
  23934. decalOpt.backgroundColor = null;
  23935. }
  23936. var pattern = {
  23937. repeat: 'repeat'
  23938. };
  23939. setPatternnSource(pattern);
  23940. pattern.rotation = decalOpt.rotation;
  23941. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  23942. decalMap.set(decalObject, pattern);
  23943. decalObject.dirty = false;
  23944. return pattern;
  23945. function setPatternnSource(pattern) {
  23946. var keys = [dpr];
  23947. var isValidKey = true;
  23948. for (var i = 0; i < decalKeys.length; ++i) {
  23949. var value = decalOpt[decalKeys[i]];
  23950. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  23951. isValidKey = false;
  23952. break;
  23953. }
  23954. keys.push(value);
  23955. }
  23956. var cacheKey;
  23957. if (isValidKey) {
  23958. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  23959. var cache = decalCache.get(cacheKey);
  23960. if (cache) {
  23961. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  23962. }
  23963. }
  23964. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  23965. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  23966. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  23967. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  23968. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  23969. var canvas = !isSVG && platformApi.createCanvas();
  23970. var svgRoot = isSVG && {
  23971. tag: 'g',
  23972. attrs: {},
  23973. key: 'dcl',
  23974. children: []
  23975. };
  23976. var pSize = getPatternSize();
  23977. var ctx;
  23978. if (canvas) {
  23979. canvas.width = pSize.width * dpr;
  23980. canvas.height = pSize.height * dpr;
  23981. ctx = canvas.getContext('2d');
  23982. }
  23983. brushDecal();
  23984. if (isValidKey) {
  23985. decalCache.put(cacheKey, canvas || svgRoot);
  23986. }
  23987. pattern.image = canvas;
  23988. pattern.svgElement = svgRoot;
  23989. pattern.svgWidth = pSize.width;
  23990. pattern.svgHeight = pSize.height;
  23991. /**
  23992. * Get minumum length that can make a repeatable pattern.
  23993. *
  23994. * @return {Object} pattern width and height
  23995. */
  23996. function getPatternSize() {
  23997. /**
  23998. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  23999. * |--- --- --- --- --- ...
  24000. * |-- -- -- -- -- -- -- -- ...
  24001. * |--- --- --- --- --- ...
  24002. * |-- -- -- -- -- -- -- -- ...
  24003. * So the minumum length of X is 15,
  24004. * which is the least common multiple of `3 + 2` and `2 + 1`
  24005. * |--- --- --- |--- --- ...
  24006. * |-- -- -- -- -- |-- -- -- ...
  24007. */
  24008. var width = 1;
  24009. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  24010. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  24011. }
  24012. var symbolRepeats = 1;
  24013. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  24014. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  24015. }
  24016. width *= symbolRepeats;
  24017. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  24018. if ("development" !== 'production') {
  24019. var warn = function (attrName) {
  24020. /* eslint-disable-next-line */
  24021. 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.");
  24022. };
  24023. if (width > decalOpt.maxTileWidth) {
  24024. warn('maxTileWidth');
  24025. }
  24026. if (height > decalOpt.maxTileHeight) {
  24027. warn('maxTileHeight');
  24028. }
  24029. }
  24030. return {
  24031. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  24032. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  24033. };
  24034. }
  24035. function brushDecal() {
  24036. if (ctx) {
  24037. ctx.clearRect(0, 0, canvas.width, canvas.height);
  24038. if (decalOpt.backgroundColor) {
  24039. ctx.fillStyle = decalOpt.backgroundColor;
  24040. ctx.fillRect(0, 0, canvas.width, canvas.height);
  24041. }
  24042. }
  24043. var ySum = 0;
  24044. for (var i = 0; i < dashArrayY.length; ++i) {
  24045. ySum += dashArrayY[i];
  24046. }
  24047. if (ySum <= 0) {
  24048. // dashArrayY is 0, draw nothing
  24049. return;
  24050. }
  24051. var y = -lineBlockLengthY;
  24052. var yId = 0;
  24053. var yIdTotal = 0;
  24054. var xId0 = 0;
  24055. while (y < pSize.height) {
  24056. if (yId % 2 === 0) {
  24057. var symbolYId = yIdTotal / 2 % symbolArray.length;
  24058. var x = 0;
  24059. var xId1 = 0;
  24060. var xId1Total = 0;
  24061. while (x < pSize.width * 2) {
  24062. var xSum = 0;
  24063. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  24064. xSum += dashArrayX[xId0][i];
  24065. }
  24066. if (xSum <= 0) {
  24067. // Skip empty line
  24068. break;
  24069. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  24070. if (xId1 % 2 === 0) {
  24071. var size = (1 - decalOpt.symbolSize) * 0.5;
  24072. var left = x + dashArrayX[xId0][xId1] * size;
  24073. var top_1 = y + dashArrayY[yId] * size;
  24074. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  24075. var height = dashArrayY[yId] * decalOpt.symbolSize;
  24076. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  24077. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  24078. }
  24079. x += dashArrayX[xId0][xId1];
  24080. ++xId1Total;
  24081. ++xId1;
  24082. if (xId1 === dashArrayX[xId0].length) {
  24083. xId1 = 0;
  24084. }
  24085. }
  24086. ++xId0;
  24087. if (xId0 === dashArrayX.length) {
  24088. xId0 = 0;
  24089. }
  24090. }
  24091. y += dashArrayY[yId];
  24092. ++yIdTotal;
  24093. ++yId;
  24094. if (yId === dashArrayY.length) {
  24095. yId = 0;
  24096. }
  24097. }
  24098. function brushSymbol(x, y, width, height, symbolType) {
  24099. var scale = isSVG ? 1 : dpr;
  24100. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  24101. if (isSVG) {
  24102. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  24103. if (symbolVNode) {
  24104. svgRoot.children.push(symbolVNode);
  24105. }
  24106. } else {
  24107. // Paint to canvas for all other renderers.
  24108. brushSingle(ctx, symbol);
  24109. }
  24110. }
  24111. }
  24112. }
  24113. }
  24114. /**
  24115. * Convert symbol array into normalized array
  24116. *
  24117. * @param {string | (string | string[])[]} symbol symbol input
  24118. * @return {string[][]} normolized symbol array
  24119. */
  24120. function normalizeSymbolArray(symbol) {
  24121. if (!symbol || symbol.length === 0) {
  24122. return [['rect']];
  24123. }
  24124. if (isString(symbol)) {
  24125. return [[symbol]];
  24126. }
  24127. var isAllString = true;
  24128. for (var i = 0; i < symbol.length; ++i) {
  24129. if (!isString(symbol[i])) {
  24130. isAllString = false;
  24131. break;
  24132. }
  24133. }
  24134. if (isAllString) {
  24135. return normalizeSymbolArray([symbol]);
  24136. }
  24137. var result = [];
  24138. for (var i = 0; i < symbol.length; ++i) {
  24139. if (isString(symbol[i])) {
  24140. result.push([symbol[i]]);
  24141. } else {
  24142. result.push(symbol[i]);
  24143. }
  24144. }
  24145. return result;
  24146. }
  24147. /**
  24148. * Convert dash input into dashArray
  24149. *
  24150. * @param {DecalDashArrayX} dash dash input
  24151. * @return {number[][]} normolized dash array
  24152. */
  24153. function normalizeDashArrayX(dash) {
  24154. if (!dash || dash.length === 0) {
  24155. return [[0, 0]];
  24156. }
  24157. if (isNumber(dash)) {
  24158. var dashValue = Math.ceil(dash);
  24159. return [[dashValue, dashValue]];
  24160. }
  24161. /**
  24162. * [20, 5] should be normalized into [[20, 5]],
  24163. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  24164. */
  24165. var isAllNumber = true;
  24166. for (var i = 0; i < dash.length; ++i) {
  24167. if (!isNumber(dash[i])) {
  24168. isAllNumber = false;
  24169. break;
  24170. }
  24171. }
  24172. if (isAllNumber) {
  24173. return normalizeDashArrayX([dash]);
  24174. }
  24175. var result = [];
  24176. for (var i = 0; i < dash.length; ++i) {
  24177. if (isNumber(dash[i])) {
  24178. var dashValue = Math.ceil(dash[i]);
  24179. result.push([dashValue, dashValue]);
  24180. } else {
  24181. var dashValue = map(dash[i], function (n) {
  24182. return Math.ceil(n);
  24183. });
  24184. if (dashValue.length % 2 === 1) {
  24185. // [4, 2, 1] means |---- - -- |---- - -- |
  24186. // so normalize it to be [4, 2, 1, 4, 2, 1]
  24187. result.push(dashValue.concat(dashValue));
  24188. } else {
  24189. result.push(dashValue);
  24190. }
  24191. }
  24192. }
  24193. return result;
  24194. }
  24195. /**
  24196. * Convert dash input into dashArray
  24197. *
  24198. * @param {DecalDashArrayY} dash dash input
  24199. * @return {number[]} normolized dash array
  24200. */
  24201. function normalizeDashArrayY(dash) {
  24202. if (!dash || typeof dash === 'object' && dash.length === 0) {
  24203. return [0, 0];
  24204. }
  24205. if (isNumber(dash)) {
  24206. var dashValue_1 = Math.ceil(dash);
  24207. return [dashValue_1, dashValue_1];
  24208. }
  24209. var dashValue = map(dash, function (n) {
  24210. return Math.ceil(n);
  24211. });
  24212. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  24213. }
  24214. /**
  24215. * Get block length of each line. A block is the length of dash line and space.
  24216. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  24217. * that, so the block length of this line is 5.
  24218. *
  24219. * @param {number[][]} dash dash arrary of X or Y
  24220. * @return {number[]} block length of each line
  24221. */
  24222. function getLineBlockLengthX(dash) {
  24223. return map(dash, function (line) {
  24224. return getLineBlockLengthY(line);
  24225. });
  24226. }
  24227. function getLineBlockLengthY(dash) {
  24228. var blockLength = 0;
  24229. for (var i = 0; i < dash.length; ++i) {
  24230. blockLength += dash[i];
  24231. }
  24232. if (dash.length % 2 === 1) {
  24233. // [4, 2, 1] means |---- - -- |---- - -- |
  24234. // So total length is (4 + 2 + 1) * 2
  24235. return blockLength * 2;
  24236. }
  24237. return blockLength;
  24238. }
  24239. function decalVisual(ecModel, api) {
  24240. ecModel.eachRawSeries(function (seriesModel) {
  24241. if (ecModel.isSeriesFiltered(seriesModel)) {
  24242. return;
  24243. }
  24244. var data = seriesModel.getData();
  24245. if (data.hasItemVisual()) {
  24246. data.each(function (idx) {
  24247. var decal = data.getItemVisual(idx, 'decal');
  24248. if (decal) {
  24249. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  24250. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  24251. }
  24252. });
  24253. }
  24254. var decal = data.getVisual('decal');
  24255. if (decal) {
  24256. var style = data.getVisual('style');
  24257. style.decal = createOrUpdatePatternFromDecal(decal, api);
  24258. }
  24259. });
  24260. }
  24261. var lifecycle = new Eventful();
  24262. // The implentations will be registered when installing the component.
  24263. // Avoid these code being bundled to the core module.
  24264. var implsStore = {}; // TODO Type
  24265. function registerImpl(name, impl) {
  24266. if ("development" !== 'production') {
  24267. if (implsStore[name]) {
  24268. error("Already has an implementation of " + name + ".");
  24269. }
  24270. }
  24271. implsStore[name] = impl;
  24272. }
  24273. function getImpl(name) {
  24274. if ("development" !== 'production') {
  24275. if (!implsStore[name]) {
  24276. error("Implementation of " + name + " doesn't exists.");
  24277. }
  24278. }
  24279. return implsStore[name];
  24280. }
  24281. var hasWindow = typeof window !== 'undefined';
  24282. var version$1 = '5.3.3';
  24283. var dependencies = {
  24284. zrender: '5.3.2'
  24285. };
  24286. var TEST_FRAME_REMAIN_TIME = 1;
  24287. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  24288. // So data stack stage should be in front of data processing stage.
  24289. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  24290. // put at the begining of data processing.
  24291. var PRIORITY_PROCESSOR_FILTER = 1000;
  24292. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  24293. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24294. var PRIORITY_VISUAL_LAYOUT = 1000;
  24295. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24296. var PRIORITY_VISUAL_GLOBAL = 2000;
  24297. var PRIORITY_VISUAL_CHART = 3000;
  24298. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  24299. // overwrite the viusal result of component (like `visualMap`)
  24300. // using data item specific setting (like itemStyle.xxx on data item)
  24301. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  24302. // visual result like `symbolSize`.
  24303. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  24304. var PRIORITY_VISUAL_BRUSH = 5000;
  24305. var PRIORITY_VISUAL_ARIA = 6000;
  24306. var PRIORITY_VISUAL_DECAL = 7000;
  24307. var PRIORITY = {
  24308. PROCESSOR: {
  24309. FILTER: PRIORITY_PROCESSOR_FILTER,
  24310. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24311. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24312. },
  24313. VISUAL: {
  24314. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24315. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24316. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24317. CHART: PRIORITY_VISUAL_CHART,
  24318. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24319. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24320. BRUSH: PRIORITY_VISUAL_BRUSH,
  24321. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  24322. ARIA: PRIORITY_VISUAL_ARIA,
  24323. DECAL: PRIORITY_VISUAL_DECAL
  24324. }
  24325. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24326. // where they must not be invoked nestedly, except the only case: invoke
  24327. // dispatchAction with updateMethod "none" in main process.
  24328. // This flag is used to carry out this rule.
  24329. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24330. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  24331. var PENDING_UPDATE = '__pendingUpdate';
  24332. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  24333. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24334. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  24335. var CONNECT_STATUS_PENDING = 0;
  24336. var CONNECT_STATUS_UPDATING = 1;
  24337. var CONNECT_STATUS_UPDATED = 2;
  24338. function createRegisterEventWithLowercaseECharts(method) {
  24339. return function () {
  24340. var args = [];
  24341. for (var _i = 0; _i < arguments.length; _i++) {
  24342. args[_i] = arguments[_i];
  24343. }
  24344. if (this.isDisposed()) {
  24345. disposedWarning(this.id);
  24346. return;
  24347. }
  24348. return toLowercaseNameAndCallEventful(this, method, args);
  24349. };
  24350. }
  24351. function createRegisterEventWithLowercaseMessageCenter(method) {
  24352. return function () {
  24353. var args = [];
  24354. for (var _i = 0; _i < arguments.length; _i++) {
  24355. args[_i] = arguments[_i];
  24356. }
  24357. return toLowercaseNameAndCallEventful(this, method, args);
  24358. };
  24359. }
  24360. function toLowercaseNameAndCallEventful(host, method, args) {
  24361. // `args[0]` is event name. Event name is all lowercase.
  24362. args[0] = args[0] && args[0].toLowerCase();
  24363. return Eventful.prototype[method].apply(host, args);
  24364. }
  24365. var MessageCenter =
  24366. /** @class */
  24367. function (_super) {
  24368. __extends(MessageCenter, _super);
  24369. function MessageCenter() {
  24370. return _super !== null && _super.apply(this, arguments) || this;
  24371. }
  24372. return MessageCenter;
  24373. }(Eventful);
  24374. var messageCenterProto = MessageCenter.prototype;
  24375. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  24376. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  24377. // Internal method names for class ECharts
  24378. // ---------------------------------------
  24379. var prepare;
  24380. var prepareView;
  24381. var updateDirectly;
  24382. var updateMethods;
  24383. var doConvertPixel;
  24384. var updateStreamModes;
  24385. var doDispatchAction;
  24386. var flushPendingActions;
  24387. var triggerUpdatedEvent;
  24388. var bindRenderedEvent;
  24389. var bindMouseEvent;
  24390. var render;
  24391. var renderComponents;
  24392. var renderSeries;
  24393. var createExtensionAPI;
  24394. var enableConnect;
  24395. var markStatusToUpdate;
  24396. var applyChangedStates;
  24397. var ECharts =
  24398. /** @class */
  24399. function (_super) {
  24400. __extends(ECharts, _super);
  24401. function ECharts(dom, // Theme name or themeOption.
  24402. theme, opts) {
  24403. var _this = _super.call(this, new ECEventProcessor()) || this;
  24404. _this._chartsViews = [];
  24405. _this._chartsMap = {};
  24406. _this._componentsViews = [];
  24407. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  24408. _this._pendingActions = [];
  24409. opts = opts || {}; // Get theme by name
  24410. if (isString(theme)) {
  24411. theme = themeStorage[theme];
  24412. }
  24413. _this._dom = dom;
  24414. var defaultRenderer = 'canvas';
  24415. var defaultUseDirtyRect = false;
  24416. if ("development" !== 'production') {
  24417. var root =
  24418. /* eslint-disable-next-line */
  24419. hasWindow ? window : global;
  24420. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24421. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  24422. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  24423. }
  24424. var zr = _this._zr = init(dom, {
  24425. renderer: opts.renderer || defaultRenderer,
  24426. devicePixelRatio: opts.devicePixelRatio,
  24427. width: opts.width,
  24428. height: opts.height,
  24429. ssr: opts.ssr,
  24430. useDirtyRect: opts.useDirtyRect == null ? defaultUseDirtyRect : opts.useDirtyRect
  24431. });
  24432. _this._ssr = opts.ssr; // Expect 60 fps.
  24433. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24434. theme = clone(theme);
  24435. theme && globalBackwardCompat(theme, true);
  24436. _this._theme = theme;
  24437. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  24438. _this._coordSysMgr = new CoordinateSystemManager();
  24439. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  24440. function prioritySortFunc(a, b) {
  24441. return a.__prio - b.__prio;
  24442. }
  24443. sort(visualFuncs, prioritySortFunc);
  24444. sort(dataProcessorFuncs, prioritySortFunc);
  24445. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  24446. _this._messageCenter = new MessageCenter(); // Init mouse events
  24447. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  24448. _this.resize = bind(_this.resize, _this);
  24449. zr.animation.on('frame', _this._onframe, _this);
  24450. bindRenderedEvent(zr, _this);
  24451. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  24452. setAsPrimitive(_this);
  24453. return _this;
  24454. }
  24455. ECharts.prototype._onframe = function () {
  24456. if (this._disposed) {
  24457. return;
  24458. }
  24459. applyChangedStates(this);
  24460. var scheduler = this._scheduler; // Lazy update
  24461. if (this[PENDING_UPDATE]) {
  24462. var silent = this[PENDING_UPDATE].silent;
  24463. this[IN_MAIN_PROCESS_KEY] = true;
  24464. try {
  24465. prepare(this);
  24466. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  24467. } catch (e) {
  24468. this[IN_MAIN_PROCESS_KEY] = false;
  24469. this[PENDING_UPDATE] = null;
  24470. throw e;
  24471. } // At present, in each frame, zrender performs:
  24472. // (1) animation step forward.
  24473. // (2) trigger('frame') (where this `_onframe` is called)
  24474. // (3) zrender flush (render).
  24475. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  24476. // will render the final state of the elements before the real animation started.
  24477. this._zr.flush();
  24478. this[IN_MAIN_PROCESS_KEY] = false;
  24479. this[PENDING_UPDATE] = null;
  24480. flushPendingActions.call(this, silent);
  24481. triggerUpdatedEvent.call(this, silent);
  24482. } // Avoid do both lazy update and progress in one frame.
  24483. else if (scheduler.unfinished) {
  24484. // Stream progress.
  24485. var remainTime = TEST_FRAME_REMAIN_TIME;
  24486. var ecModel = this._model;
  24487. var api = this._api;
  24488. scheduler.unfinished = false;
  24489. do {
  24490. var startTime = +new Date();
  24491. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  24492. scheduler.performDataProcessorTasks(ecModel);
  24493. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  24494. // each frame is not a good user experience. So we follow the rule that
  24495. // the extent of the coordinate system is determin in the first frame (the
  24496. // frame is executed immedietely after task reset.
  24497. // this._coordSysMgr.update(ecModel, api);
  24498. // console.log('--- ec frame visual ---', remainTime);
  24499. scheduler.performVisualTasks(ecModel);
  24500. renderSeries(this, this._model, api, 'remain', {});
  24501. remainTime -= +new Date() - startTime;
  24502. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  24503. if (!scheduler.unfinished) {
  24504. this._zr.flush();
  24505. } // Else, zr flushing be ensue within the same frame,
  24506. // because zr flushing is after onframe event.
  24507. }
  24508. };
  24509. ECharts.prototype.getDom = function () {
  24510. return this._dom;
  24511. };
  24512. ECharts.prototype.getId = function () {
  24513. return this.id;
  24514. };
  24515. ECharts.prototype.getZr = function () {
  24516. return this._zr;
  24517. };
  24518. ECharts.prototype.isSSR = function () {
  24519. return this._ssr;
  24520. };
  24521. /* eslint-disable-next-line */
  24522. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  24523. if (this[IN_MAIN_PROCESS_KEY]) {
  24524. if ("development" !== 'production') {
  24525. error('`setOption` should not be called during main process.');
  24526. }
  24527. return;
  24528. }
  24529. if (this._disposed) {
  24530. disposedWarning(this.id);
  24531. return;
  24532. }
  24533. var silent;
  24534. var replaceMerge;
  24535. var transitionOpt;
  24536. if (isObject(notMerge)) {
  24537. lazyUpdate = notMerge.lazyUpdate;
  24538. silent = notMerge.silent;
  24539. replaceMerge = notMerge.replaceMerge;
  24540. transitionOpt = notMerge.transition;
  24541. notMerge = notMerge.notMerge;
  24542. }
  24543. this[IN_MAIN_PROCESS_KEY] = true;
  24544. if (!this._model || notMerge) {
  24545. var optionManager = new OptionManager(this._api);
  24546. var theme = this._theme;
  24547. var ecModel = this._model = new GlobalModel();
  24548. ecModel.scheduler = this._scheduler;
  24549. ecModel.ssr = this._ssr;
  24550. ecModel.init(null, null, null, theme, this._locale, optionManager);
  24551. }
  24552. this._model.setOption(option, {
  24553. replaceMerge: replaceMerge
  24554. }, optionPreprocessorFuncs);
  24555. var updateParams = {
  24556. seriesTransition: transitionOpt,
  24557. optionChanged: true
  24558. };
  24559. if (lazyUpdate) {
  24560. this[PENDING_UPDATE] = {
  24561. silent: silent,
  24562. updateParams: updateParams
  24563. };
  24564. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  24565. // It should wake it up to make sure zrender start to render at the next frame.
  24566. this.getZr().wakeUp();
  24567. } else {
  24568. try {
  24569. prepare(this);
  24570. updateMethods.update.call(this, null, updateParams);
  24571. } catch (e) {
  24572. this[PENDING_UPDATE] = null;
  24573. this[IN_MAIN_PROCESS_KEY] = false;
  24574. throw e;
  24575. } // Ensure zr refresh sychronously, and then pixel in canvas can be
  24576. // fetched after `setOption`.
  24577. if (!this._ssr) {
  24578. // not use flush when using ssr mode.
  24579. this._zr.flush();
  24580. }
  24581. this[PENDING_UPDATE] = null;
  24582. this[IN_MAIN_PROCESS_KEY] = false;
  24583. flushPendingActions.call(this, silent);
  24584. triggerUpdatedEvent.call(this, silent);
  24585. }
  24586. };
  24587. /**
  24588. * @deprecated
  24589. */
  24590. ECharts.prototype.setTheme = function () {
  24591. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24592. }; // We don't want developers to use getModel directly.
  24593. ECharts.prototype.getModel = function () {
  24594. return this._model;
  24595. };
  24596. ECharts.prototype.getOption = function () {
  24597. return this._model && this._model.getOption();
  24598. };
  24599. ECharts.prototype.getWidth = function () {
  24600. return this._zr.getWidth();
  24601. };
  24602. ECharts.prototype.getHeight = function () {
  24603. return this._zr.getHeight();
  24604. };
  24605. ECharts.prototype.getDevicePixelRatio = function () {
  24606. return this._zr.painter.dpr
  24607. /* eslint-disable-next-line */
  24608. || hasWindow && window.devicePixelRatio || 1;
  24609. };
  24610. /**
  24611. * Get canvas which has all thing rendered
  24612. * @deprecated Use renderToCanvas instead.
  24613. */
  24614. ECharts.prototype.getRenderedCanvas = function (opts) {
  24615. if ("development" !== 'production') {
  24616. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  24617. }
  24618. return this.renderToCanvas(opts);
  24619. };
  24620. ECharts.prototype.renderToCanvas = function (opts) {
  24621. opts = opts || {};
  24622. var painter = this._zr.painter;
  24623. if ("development" !== 'production') {
  24624. if (painter.type !== 'canvas') {
  24625. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  24626. }
  24627. }
  24628. return painter.getRenderedCanvas({
  24629. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  24630. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  24631. });
  24632. };
  24633. ECharts.prototype.renderToSVGString = function (opts) {
  24634. opts = opts || {};
  24635. var painter = this._zr.painter;
  24636. if ("development" !== 'production') {
  24637. if (painter.type !== 'svg') {
  24638. throw new Error('renderToSVGString can only be used in the svg renderer.');
  24639. }
  24640. }
  24641. return painter.renderToString({
  24642. useViewBox: opts.useViewBox
  24643. });
  24644. };
  24645. /**
  24646. * Get svg data url
  24647. */
  24648. ECharts.prototype.getSvgDataURL = function () {
  24649. if (!env.svgSupported) {
  24650. return;
  24651. }
  24652. var zr = this._zr;
  24653. var list = zr.storage.getDisplayList(); // Stop animations
  24654. each(list, function (el) {
  24655. el.stopAnimation(null, true);
  24656. });
  24657. return zr.painter.toDataURL();
  24658. };
  24659. ECharts.prototype.getDataURL = function (opts) {
  24660. if (this._disposed) {
  24661. disposedWarning(this.id);
  24662. return;
  24663. }
  24664. opts = opts || {};
  24665. var excludeComponents = opts.excludeComponents;
  24666. var ecModel = this._model;
  24667. var excludesComponentViews = [];
  24668. var self = this;
  24669. each(excludeComponents, function (componentType) {
  24670. ecModel.eachComponent({
  24671. mainType: componentType
  24672. }, function (component) {
  24673. var view = self._componentsMap[component.__viewId];
  24674. if (!view.group.ignore) {
  24675. excludesComponentViews.push(view);
  24676. view.group.ignore = true;
  24677. }
  24678. });
  24679. });
  24680. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  24681. each(excludesComponentViews, function (view) {
  24682. view.group.ignore = false;
  24683. });
  24684. return url;
  24685. };
  24686. ECharts.prototype.getConnectedDataURL = function (opts) {
  24687. if (this._disposed) {
  24688. disposedWarning(this.id);
  24689. return;
  24690. }
  24691. var isSvg = opts.type === 'svg';
  24692. var groupId = this.group;
  24693. var mathMin = Math.min;
  24694. var mathMax = Math.max;
  24695. var MAX_NUMBER = Infinity;
  24696. if (connectedGroups[groupId]) {
  24697. var left_1 = MAX_NUMBER;
  24698. var top_1 = MAX_NUMBER;
  24699. var right_1 = -MAX_NUMBER;
  24700. var bottom_1 = -MAX_NUMBER;
  24701. var canvasList_1 = [];
  24702. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  24703. each(instances$1, function (chart, id) {
  24704. if (chart.group === groupId) {
  24705. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  24706. var boundingRect = chart.getDom().getBoundingClientRect();
  24707. left_1 = mathMin(boundingRect.left, left_1);
  24708. top_1 = mathMin(boundingRect.top, top_1);
  24709. right_1 = mathMax(boundingRect.right, right_1);
  24710. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  24711. canvasList_1.push({
  24712. dom: canvas,
  24713. left: boundingRect.left,
  24714. top: boundingRect.top
  24715. });
  24716. }
  24717. });
  24718. left_1 *= dpr_1;
  24719. top_1 *= dpr_1;
  24720. right_1 *= dpr_1;
  24721. bottom_1 *= dpr_1;
  24722. var width = right_1 - left_1;
  24723. var height = bottom_1 - top_1;
  24724. var targetCanvas = platformApi.createCanvas();
  24725. var zr_1 = init(targetCanvas, {
  24726. renderer: isSvg ? 'svg' : 'canvas'
  24727. });
  24728. zr_1.resize({
  24729. width: width,
  24730. height: height
  24731. });
  24732. if (isSvg) {
  24733. var content_1 = '';
  24734. each(canvasList_1, function (item) {
  24735. var x = item.left - left_1;
  24736. var y = item.top - top_1;
  24737. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  24738. });
  24739. zr_1.painter.getSvgRoot().innerHTML = content_1;
  24740. if (opts.connectedBackgroundColor) {
  24741. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  24742. }
  24743. zr_1.refreshImmediately();
  24744. return zr_1.painter.toDataURL();
  24745. } else {
  24746. // Background between the charts
  24747. if (opts.connectedBackgroundColor) {
  24748. zr_1.add(new Rect({
  24749. shape: {
  24750. x: 0,
  24751. y: 0,
  24752. width: width,
  24753. height: height
  24754. },
  24755. style: {
  24756. fill: opts.connectedBackgroundColor
  24757. }
  24758. }));
  24759. }
  24760. each(canvasList_1, function (item) {
  24761. var img = new ZRImage({
  24762. style: {
  24763. x: item.left * dpr_1 - left_1,
  24764. y: item.top * dpr_1 - top_1,
  24765. image: item.dom
  24766. }
  24767. });
  24768. zr_1.add(img);
  24769. });
  24770. zr_1.refreshImmediately();
  24771. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24772. }
  24773. } else {
  24774. return this.getDataURL(opts);
  24775. }
  24776. };
  24777. ECharts.prototype.convertToPixel = function (finder, value) {
  24778. return doConvertPixel(this, 'convertToPixel', finder, value);
  24779. };
  24780. ECharts.prototype.convertFromPixel = function (finder, value) {
  24781. return doConvertPixel(this, 'convertFromPixel', finder, value);
  24782. };
  24783. /**
  24784. * Is the specified coordinate systems or components contain the given pixel point.
  24785. * @param {Array|number} value
  24786. * @return {boolean} result
  24787. */
  24788. ECharts.prototype.containPixel = function (finder, value) {
  24789. if (this._disposed) {
  24790. disposedWarning(this.id);
  24791. return;
  24792. }
  24793. var ecModel = this._model;
  24794. var result;
  24795. var findResult = parseFinder(ecModel, finder);
  24796. each(findResult, function (models, key) {
  24797. key.indexOf('Models') >= 0 && each(models, function (model) {
  24798. var coordSys = model.coordinateSystem;
  24799. if (coordSys && coordSys.containPoint) {
  24800. result = result || !!coordSys.containPoint(value);
  24801. } else if (key === 'seriesModels') {
  24802. var view = this._chartsMap[model.__viewId];
  24803. if (view && view.containPoint) {
  24804. result = result || view.containPoint(value, model);
  24805. } else {
  24806. if ("development" !== 'production') {
  24807. console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  24808. }
  24809. }
  24810. } else {
  24811. if ("development" !== 'production') {
  24812. console.warn(key + ': containPoint is not supported');
  24813. }
  24814. }
  24815. }, this);
  24816. }, this);
  24817. return !!result;
  24818. };
  24819. /**
  24820. * Get visual from series or data.
  24821. * @param finder
  24822. * If string, e.g., 'series', means {seriesIndex: 0}.
  24823. * If Object, could contain some of these properties below:
  24824. * {
  24825. * seriesIndex / seriesId / seriesName,
  24826. * dataIndex / dataIndexInside
  24827. * }
  24828. * If dataIndex is not specified, series visual will be fetched,
  24829. * but not data item visual.
  24830. * If all of seriesIndex, seriesId, seriesName are not specified,
  24831. * visual will be fetched from first series.
  24832. * @param visualType 'color', 'symbol', 'symbolSize'
  24833. */
  24834. ECharts.prototype.getVisual = function (finder, visualType) {
  24835. var ecModel = this._model;
  24836. var parsedFinder = parseFinder(ecModel, finder, {
  24837. defaultMainType: 'series'
  24838. });
  24839. var seriesModel = parsedFinder.seriesModel;
  24840. if ("development" !== 'production') {
  24841. if (!seriesModel) {
  24842. console.warn('There is no specified seires model');
  24843. }
  24844. }
  24845. var data = seriesModel.getData();
  24846. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  24847. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  24848. };
  24849. /**
  24850. * Get view of corresponding component model
  24851. */
  24852. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  24853. return this._componentsMap[componentModel.__viewId];
  24854. };
  24855. /**
  24856. * Get view of corresponding series model
  24857. */
  24858. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  24859. return this._chartsMap[seriesModel.__viewId];
  24860. };
  24861. ECharts.prototype._initEvents = function () {
  24862. var _this = this;
  24863. each(MOUSE_EVENT_NAMES, function (eveName) {
  24864. var handler = function (e) {
  24865. var ecModel = _this.getModel();
  24866. var el = e.target;
  24867. var params;
  24868. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  24869. if (isGlobalOut) {
  24870. params = {};
  24871. } else {
  24872. el && findEventDispatcher(el, function (parent) {
  24873. var ecData = getECData(parent);
  24874. if (ecData && ecData.dataIndex != null) {
  24875. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  24876. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  24877. return true;
  24878. } // If element has custom eventData of components
  24879. else if (ecData.eventData) {
  24880. params = extend({}, ecData.eventData);
  24881. return true;
  24882. }
  24883. }, true);
  24884. } // Contract: if params prepared in mouse event,
  24885. // these properties must be specified:
  24886. // {
  24887. // componentType: string (component main type)
  24888. // componentIndex: number
  24889. // }
  24890. // Otherwise event query can not work.
  24891. if (params) {
  24892. var componentType = params.componentType;
  24893. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  24894. // markLine/markPoint/markArea, the componentType is
  24895. // 'markLine'/'markPoint'/'markArea', but we should better
  24896. // enable them to be queried by seriesIndex, since their
  24897. // option is set in each series.
  24898. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  24899. componentType = 'series';
  24900. componentIndex = params.seriesIndex;
  24901. }
  24902. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  24903. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  24904. if ("development" !== 'production') {
  24905. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24906. // be missed, otherwise there is no way to distinguish source component.
  24907. // See `dataFormat.getDataParams`.
  24908. if (!isGlobalOut && !(model && view)) {
  24909. console.warn('model or view can not be found by params');
  24910. }
  24911. }
  24912. params.event = e;
  24913. params.type = eveName;
  24914. _this._$eventProcessor.eventInfo = {
  24915. targetEl: el,
  24916. packedEvent: params,
  24917. model: model,
  24918. view: view
  24919. };
  24920. _this.trigger(eveName, params);
  24921. }
  24922. }; // Consider that some component (like tooltip, brush, ...)
  24923. // register zr event handler, but user event handler might
  24924. // do anything, such as call `setOption` or `dispatchAction`,
  24925. // which probably update any of the content and probably
  24926. // cause problem if it is called previous other inner handlers.
  24927. handler.zrEventfulCallAtLast = true;
  24928. _this._zr.on(eveName, handler, _this);
  24929. });
  24930. each(eventActionMap, function (actionType, eventType) {
  24931. _this._messageCenter.on(eventType, function (event) {
  24932. this.trigger(eventType, event);
  24933. }, _this);
  24934. }); // Extra events
  24935. // TODO register?
  24936. each(['selectchanged'], function (eventType) {
  24937. _this._messageCenter.on(eventType, function (event) {
  24938. this.trigger(eventType, event);
  24939. }, _this);
  24940. });
  24941. handleLegacySelectEvents(this._messageCenter, this, this._api);
  24942. };
  24943. ECharts.prototype.isDisposed = function () {
  24944. return this._disposed;
  24945. };
  24946. ECharts.prototype.clear = function () {
  24947. if (this._disposed) {
  24948. disposedWarning(this.id);
  24949. return;
  24950. }
  24951. this.setOption({
  24952. series: []
  24953. }, true);
  24954. };
  24955. ECharts.prototype.dispose = function () {
  24956. if (this._disposed) {
  24957. disposedWarning(this.id);
  24958. return;
  24959. }
  24960. this._disposed = true;
  24961. var dom = this.getDom();
  24962. if (dom) {
  24963. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24964. }
  24965. var chart = this;
  24966. var api = chart._api;
  24967. var ecModel = chart._model;
  24968. each(chart._componentsViews, function (component) {
  24969. component.dispose(ecModel, api);
  24970. });
  24971. each(chart._chartsViews, function (chart) {
  24972. chart.dispose(ecModel, api);
  24973. }); // Dispose after all views disposed
  24974. chart._zr.dispose(); // Set properties to null.
  24975. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  24976. 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;
  24977. delete instances$1[chart.id];
  24978. };
  24979. /**
  24980. * Resize the chart
  24981. */
  24982. ECharts.prototype.resize = function (opts) {
  24983. if (this[IN_MAIN_PROCESS_KEY]) {
  24984. if ("development" !== 'production') {
  24985. error('`resize` should not be called during main process.');
  24986. }
  24987. return;
  24988. }
  24989. if (this._disposed) {
  24990. disposedWarning(this.id);
  24991. return;
  24992. }
  24993. this._zr.resize(opts);
  24994. var ecModel = this._model; // Resize loading effect
  24995. this._loadingFX && this._loadingFX.resize();
  24996. if (!ecModel) {
  24997. return;
  24998. }
  24999. var needPrepare = ecModel.resetOption('media');
  25000. var silent = opts && opts.silent; // There is some real cases that:
  25001. // chart.setOption(option, { lazyUpdate: true });
  25002. // chart.resize();
  25003. if (this[PENDING_UPDATE]) {
  25004. if (silent == null) {
  25005. silent = this[PENDING_UPDATE].silent;
  25006. }
  25007. needPrepare = true;
  25008. this[PENDING_UPDATE] = null;
  25009. }
  25010. this[IN_MAIN_PROCESS_KEY] = true;
  25011. try {
  25012. needPrepare && prepare(this);
  25013. updateMethods.update.call(this, {
  25014. type: 'resize',
  25015. animation: extend({
  25016. // Disable animation
  25017. duration: 0
  25018. }, opts && opts.animation)
  25019. });
  25020. } catch (e) {
  25021. this[IN_MAIN_PROCESS_KEY] = false;
  25022. throw e;
  25023. }
  25024. this[IN_MAIN_PROCESS_KEY] = false;
  25025. flushPendingActions.call(this, silent);
  25026. triggerUpdatedEvent.call(this, silent);
  25027. };
  25028. ECharts.prototype.showLoading = function (name, cfg) {
  25029. if (this._disposed) {
  25030. disposedWarning(this.id);
  25031. return;
  25032. }
  25033. if (isObject(name)) {
  25034. cfg = name;
  25035. name = '';
  25036. }
  25037. name = name || 'default';
  25038. this.hideLoading();
  25039. if (!loadingEffects[name]) {
  25040. if ("development" !== 'production') {
  25041. console.warn('Loading effects ' + name + ' not exists.');
  25042. }
  25043. return;
  25044. }
  25045. var el = loadingEffects[name](this._api, cfg);
  25046. var zr = this._zr;
  25047. this._loadingFX = el;
  25048. zr.add(el);
  25049. };
  25050. /**
  25051. * Hide loading effect
  25052. */
  25053. ECharts.prototype.hideLoading = function () {
  25054. if (this._disposed) {
  25055. disposedWarning(this.id);
  25056. return;
  25057. }
  25058. this._loadingFX && this._zr.remove(this._loadingFX);
  25059. this._loadingFX = null;
  25060. };
  25061. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  25062. var payload = extend({}, eventObj);
  25063. payload.type = eventActionMap[eventObj.type];
  25064. return payload;
  25065. };
  25066. /**
  25067. * @param opt If pass boolean, means opt.silent
  25068. * @param opt.silent Default `false`. Whether trigger events.
  25069. * @param opt.flush Default `undefined`.
  25070. * true: Flush immediately, and then pixel in canvas can be fetched
  25071. * immediately. Caution: it might affect performance.
  25072. * false: Not flush.
  25073. * undefined: Auto decide whether perform flush.
  25074. */
  25075. ECharts.prototype.dispatchAction = function (payload, opt) {
  25076. if (this._disposed) {
  25077. disposedWarning(this.id);
  25078. return;
  25079. }
  25080. if (!isObject(opt)) {
  25081. opt = {
  25082. silent: !!opt
  25083. };
  25084. }
  25085. if (!actions[payload.type]) {
  25086. return;
  25087. } // Avoid dispatch action before setOption. Especially in `connect`.
  25088. if (!this._model) {
  25089. return;
  25090. } // May dispatchAction in rendering procedure
  25091. if (this[IN_MAIN_PROCESS_KEY]) {
  25092. this._pendingActions.push(payload);
  25093. return;
  25094. }
  25095. var silent = opt.silent;
  25096. doDispatchAction.call(this, payload, silent);
  25097. var flush = opt.flush;
  25098. if (flush) {
  25099. this._zr.flush();
  25100. } else if (flush !== false && env.browser.weChat) {
  25101. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25102. // hang when sliding page (on touch event), which cause that zr does not
  25103. // refresh util user interaction finished, which is not expected.
  25104. // But `dispatchAction` may be called too frequently when pan on touch
  25105. // screen, which impacts performance if do not throttle them.
  25106. this._throttledZrFlush();
  25107. }
  25108. flushPendingActions.call(this, silent);
  25109. triggerUpdatedEvent.call(this, silent);
  25110. };
  25111. ECharts.prototype.updateLabelLayout = function () {
  25112. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  25113. // Not adding series labels.
  25114. // TODO
  25115. updatedSeries: []
  25116. });
  25117. };
  25118. ECharts.prototype.appendData = function (params) {
  25119. if (this._disposed) {
  25120. disposedWarning(this.id);
  25121. return;
  25122. }
  25123. var seriesIndex = params.seriesIndex;
  25124. var ecModel = this.getModel();
  25125. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25126. if ("development" !== 'production') {
  25127. assert(params.data && seriesModel);
  25128. }
  25129. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  25130. // system, util some scenario require that. In the expected usage of
  25131. // `appendData`, the initial extent of coordinate system should better
  25132. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25133. // the extent changed while `appendData`, the location of the painted
  25134. // graphic elements have to be changed, which make the usage of
  25135. // `appendData` meaningless.
  25136. this._scheduler.unfinished = true;
  25137. this.getZr().wakeUp();
  25138. }; // A work around for no `internal` modifier in ts yet but
  25139. // need to strictly hide private methods to JS users.
  25140. ECharts.internalField = function () {
  25141. prepare = function (ecIns) {
  25142. var scheduler = ecIns._scheduler;
  25143. scheduler.restorePipelines(ecIns._model);
  25144. scheduler.prepareStageTasks();
  25145. prepareView(ecIns, true);
  25146. prepareView(ecIns, false);
  25147. scheduler.plan();
  25148. };
  25149. /**
  25150. * Prepare view instances of charts and components
  25151. */
  25152. prepareView = function (ecIns, isComponent) {
  25153. var ecModel = ecIns._model;
  25154. var scheduler = ecIns._scheduler;
  25155. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25156. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25157. var zr = ecIns._zr;
  25158. var api = ecIns._api;
  25159. for (var i = 0; i < viewList.length; i++) {
  25160. viewList[i].__alive = false;
  25161. }
  25162. isComponent ? ecModel.eachComponent(function (componentType, model) {
  25163. componentType !== 'series' && doPrepare(model);
  25164. }) : ecModel.eachSeries(doPrepare);
  25165. function doPrepare(model) {
  25166. // By defaut view will be reused if possible for the case that `setOption` with "notMerge"
  25167. // mode and need to enable transition animation. (Usually, when they have the same id, or
  25168. // especially no id but have the same type & name & index. See the `model.id` generation
  25169. // rule in `makeIdAndName` and `viewId` generation rule here).
  25170. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  25171. // the new model has nothing to do with the old model.
  25172. var requireNewView = model.__requireNewView; // This command should not work twice.
  25173. model.__requireNewView = false; // Consider: id same and type changed.
  25174. var viewId = '_ec_' + model.id + '_' + model.type;
  25175. var view = !requireNewView && viewMap[viewId];
  25176. if (!view) {
  25177. var classType = parseClassType(model.type);
  25178. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  25179. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  25180. // For backward compat, still support a chart type declared as only subType
  25181. // like "liquidfill", but recommend "series.liquidfill"
  25182. // But need a base class to make a type series.
  25183. ChartView.getClass(classType.sub);
  25184. if ("development" !== 'production') {
  25185. assert(Clazz, classType.sub + ' does not exist.');
  25186. }
  25187. view = new Clazz();
  25188. view.init(ecModel, api);
  25189. viewMap[viewId] = view;
  25190. viewList.push(view);
  25191. zr.add(view.group);
  25192. }
  25193. model.__viewId = view.__id = viewId;
  25194. view.__alive = true;
  25195. view.__model = model;
  25196. view.group.__ecComponentInfo = {
  25197. mainType: model.mainType,
  25198. index: model.componentIndex
  25199. };
  25200. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25201. }
  25202. for (var i = 0; i < viewList.length;) {
  25203. var view = viewList[i];
  25204. if (!view.__alive) {
  25205. !isComponent && view.renderTask.dispose();
  25206. zr.remove(view.group);
  25207. view.dispose(ecModel, api);
  25208. viewList.splice(i, 1);
  25209. if (viewMap[view.__id] === view) {
  25210. delete viewMap[view.__id];
  25211. }
  25212. view.__id = view.group.__ecComponentInfo = null;
  25213. } else {
  25214. i++;
  25215. }
  25216. }
  25217. };
  25218. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  25219. var ecModel = ecIns._model;
  25220. ecModel.setUpdatePayload(payload); // broadcast
  25221. if (!mainType) {
  25222. // FIXME
  25223. // Chart will not be update directly here, except set dirty.
  25224. // But there is no such scenario now.
  25225. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  25226. return;
  25227. }
  25228. var query = {};
  25229. query[mainType + 'Id'] = payload[mainType + 'Id'];
  25230. query[mainType + 'Index'] = payload[mainType + 'Index'];
  25231. query[mainType + 'Name'] = payload[mainType + 'Name'];
  25232. var condition = {
  25233. mainType: mainType,
  25234. query: query
  25235. };
  25236. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  25237. var excludeSeriesId = payload.excludeSeriesId;
  25238. var excludeSeriesIdMap;
  25239. if (excludeSeriesId != null) {
  25240. excludeSeriesIdMap = createHashMap();
  25241. each(normalizeToArray(excludeSeriesId), function (id) {
  25242. var modelId = convertOptionIdName(id, null);
  25243. if (modelId != null) {
  25244. excludeSeriesIdMap.set(modelId, true);
  25245. }
  25246. });
  25247. } // If dispatchAction before setOption, do nothing.
  25248. ecModel && ecModel.eachComponent(condition, function (model) {
  25249. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) !== null;
  25250. if (isExcluded) {
  25251. return;
  25252. }
  25253. if (isHighDownPayload(payload)) {
  25254. if (model instanceof SeriesModel) {
  25255. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  25256. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  25257. }
  25258. } else {
  25259. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  25260. focusSelf = _a.focusSelf,
  25261. dispatchers = _a.dispatchers;
  25262. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  25263. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  25264. } // PENDING:
  25265. // Whether to put this "enter emphasis" code in `ComponentView`,
  25266. // which will be the same as `ChartView` but might be not necessary
  25267. // and will be far from this logic.
  25268. if (dispatchers) {
  25269. each(dispatchers, function (dispatcher) {
  25270. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  25271. });
  25272. }
  25273. }
  25274. } else if (isSelectChangePayload(payload)) {
  25275. // TODO geo
  25276. if (model instanceof SeriesModel) {
  25277. toggleSelectionFromPayload(model, payload, ecIns._api);
  25278. updateSeriesElementSelection(model);
  25279. markStatusToUpdate(ecIns);
  25280. }
  25281. }
  25282. }, ecIns);
  25283. ecModel && ecModel.eachComponent(condition, function (model) {
  25284. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) !== null;
  25285. if (isExcluded) {
  25286. return;
  25287. }
  25288. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  25289. }, ecIns);
  25290. function callView(view) {
  25291. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  25292. }
  25293. };
  25294. updateMethods = {
  25295. prepareAndUpdate: function (payload) {
  25296. prepare(this);
  25297. updateMethods.update.call(this, payload, {
  25298. // Needs to mark option changed if newOption is given.
  25299. // It's from MagicType.
  25300. // TODO If use a separate flag optionChanged in payload?
  25301. optionChanged: payload.newOption != null
  25302. });
  25303. },
  25304. update: function (payload, updateParams) {
  25305. var ecModel = this._model;
  25306. var api = this._api;
  25307. var zr = this._zr;
  25308. var coordSysMgr = this._coordSysMgr;
  25309. var scheduler = this._scheduler; // update before setOption
  25310. if (!ecModel) {
  25311. return;
  25312. }
  25313. ecModel.setUpdatePayload(payload);
  25314. scheduler.restoreData(ecModel, payload);
  25315. scheduler.performSeriesTasks(ecModel); // TODO
  25316. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  25317. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  25318. // Create new coordinate system each update
  25319. // In LineView may save the old coordinate system and use it to get the orignal point
  25320. coordSysMgr.create(ecModel, api);
  25321. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  25322. // stream modes after data processing, where the filtered data is used to
  25323. // deteming whether use progressive rendering.
  25324. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  25325. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  25326. // the drawback is the full coord info can not be fetched. Fortunately this full
  25327. // coord is not requied in stream mode updater currently.
  25328. coordSysMgr.update(ecModel, api);
  25329. clearColorPalette(ecModel);
  25330. scheduler.performVisualTasks(ecModel, payload);
  25331. render(this, ecModel, api, payload, updateParams); // Set background
  25332. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  25333. var darkMode = ecModel.get('darkMode');
  25334. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  25335. if (darkMode != null && darkMode !== 'auto') {
  25336. zr.setDarkMode(darkMode);
  25337. }
  25338. lifecycle.trigger('afterupdate', ecModel, api);
  25339. },
  25340. updateTransform: function (payload) {
  25341. var _this = this;
  25342. var ecModel = this._model;
  25343. var api = this._api; // update before setOption
  25344. if (!ecModel) {
  25345. return;
  25346. }
  25347. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  25348. var componentDirtyList = [];
  25349. ecModel.eachComponent(function (componentType, componentModel) {
  25350. if (componentType === 'series') {
  25351. return;
  25352. }
  25353. var componentView = _this.getViewOfComponentModel(componentModel);
  25354. if (componentView && componentView.__alive) {
  25355. if (componentView.updateTransform) {
  25356. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  25357. result && result.update && componentDirtyList.push(componentView);
  25358. } else {
  25359. componentDirtyList.push(componentView);
  25360. }
  25361. }
  25362. });
  25363. var seriesDirtyMap = createHashMap();
  25364. ecModel.eachSeries(function (seriesModel) {
  25365. var chartView = _this._chartsMap[seriesModel.__viewId];
  25366. if (chartView.updateTransform) {
  25367. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  25368. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  25369. } else {
  25370. seriesDirtyMap.set(seriesModel.uid, 1);
  25371. }
  25372. });
  25373. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25374. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  25375. this._scheduler.performVisualTasks(ecModel, payload, {
  25376. setDirty: true,
  25377. dirtyMap: seriesDirtyMap
  25378. }); // Currently, not call render of components. Geo render cost a lot.
  25379. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  25380. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  25381. lifecycle.trigger('afterupdate', ecModel, api);
  25382. },
  25383. updateView: function (payload) {
  25384. var ecModel = this._model; // update before setOption
  25385. if (!ecModel) {
  25386. return;
  25387. }
  25388. ecModel.setUpdatePayload(payload);
  25389. ChartView.markUpdateMethod(payload, 'updateView');
  25390. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25391. this._scheduler.performVisualTasks(ecModel, payload, {
  25392. setDirty: true
  25393. });
  25394. render(this, ecModel, this._api, payload, {});
  25395. lifecycle.trigger('afterupdate', ecModel, this._api);
  25396. },
  25397. updateVisual: function (payload) {
  25398. // updateMethods.update.call(this, payload);
  25399. var _this = this;
  25400. var ecModel = this._model; // update before setOption
  25401. if (!ecModel) {
  25402. return;
  25403. }
  25404. ecModel.setUpdatePayload(payload); // clear all visual
  25405. ecModel.eachSeries(function (seriesModel) {
  25406. seriesModel.getData().clearAllVisual();
  25407. }); // Perform visual
  25408. ChartView.markUpdateMethod(payload, 'updateVisual');
  25409. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25410. this._scheduler.performVisualTasks(ecModel, payload, {
  25411. visualType: 'visual',
  25412. setDirty: true
  25413. });
  25414. ecModel.eachComponent(function (componentType, componentModel) {
  25415. if (componentType !== 'series') {
  25416. var componentView = _this.getViewOfComponentModel(componentModel);
  25417. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  25418. }
  25419. });
  25420. ecModel.eachSeries(function (seriesModel) {
  25421. var chartView = _this._chartsMap[seriesModel.__viewId];
  25422. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  25423. });
  25424. lifecycle.trigger('afterupdate', ecModel, this._api);
  25425. },
  25426. updateLayout: function (payload) {
  25427. updateMethods.update.call(this, payload);
  25428. }
  25429. };
  25430. doConvertPixel = function (ecIns, methodName, finder, value) {
  25431. if (ecIns._disposed) {
  25432. disposedWarning(ecIns.id);
  25433. return;
  25434. }
  25435. var ecModel = ecIns._model;
  25436. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  25437. var result;
  25438. var parsedFinder = parseFinder(ecModel, finder);
  25439. for (var i = 0; i < coordSysList.length; i++) {
  25440. var coordSys = coordSysList[i];
  25441. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  25442. return result;
  25443. }
  25444. }
  25445. if ("development" !== 'production') {
  25446. console.warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  25447. }
  25448. };
  25449. updateStreamModes = function (ecIns, ecModel) {
  25450. var chartsMap = ecIns._chartsMap;
  25451. var scheduler = ecIns._scheduler;
  25452. ecModel.eachSeries(function (seriesModel) {
  25453. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25454. });
  25455. };
  25456. doDispatchAction = function (payload, silent) {
  25457. var _this = this;
  25458. var ecModel = this.getModel();
  25459. var payloadType = payload.type;
  25460. var escapeConnect = payload.escapeConnect;
  25461. var actionWrap = actions[payloadType];
  25462. var actionInfo = actionWrap.actionInfo;
  25463. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  25464. var updateMethod = cptTypeTmp.pop();
  25465. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  25466. this[IN_MAIN_PROCESS_KEY] = true;
  25467. var payloads = [payload];
  25468. var batched = false; // Batch action
  25469. if (payload.batch) {
  25470. batched = true;
  25471. payloads = map(payload.batch, function (item) {
  25472. item = defaults(extend({}, item), payload);
  25473. item.batch = null;
  25474. return item;
  25475. });
  25476. }
  25477. var eventObjBatch = [];
  25478. var eventObj;
  25479. var isSelectChange = isSelectChangePayload(payload);
  25480. var isHighDown = isHighDownPayload(payload); // Only leave blur once if there are multiple batches.
  25481. if (isHighDown) {
  25482. allLeaveBlur(this._api);
  25483. }
  25484. each(payloads, function (batchItem) {
  25485. // Action can specify the event by return it.
  25486. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  25487. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  25488. eventObj.type = actionInfo.event || eventObj.type;
  25489. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  25490. if (isHighDown) {
  25491. var _a = preParseFinder(payload),
  25492. queryOptionMap = _a.queryOptionMap,
  25493. mainTypeSpecified = _a.mainTypeSpecified;
  25494. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  25495. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  25496. markStatusToUpdate(_this);
  25497. } else if (isSelectChange) {
  25498. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  25499. // geo still use 'geoselect'.
  25500. updateDirectly(_this, updateMethod, batchItem, 'series');
  25501. markStatusToUpdate(_this);
  25502. } else if (cptType) {
  25503. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  25504. }
  25505. });
  25506. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  25507. try {
  25508. // Still dirty
  25509. if (this[PENDING_UPDATE]) {
  25510. prepare(this);
  25511. updateMethods.update.call(this, payload);
  25512. this[PENDING_UPDATE] = null;
  25513. } else {
  25514. updateMethods[updateMethod].call(this, payload);
  25515. }
  25516. } catch (e) {
  25517. this[IN_MAIN_PROCESS_KEY] = false;
  25518. throw e;
  25519. }
  25520. } // Follow the rule of action batch
  25521. if (batched) {
  25522. eventObj = {
  25523. type: actionInfo.event || payloadType,
  25524. escapeConnect: escapeConnect,
  25525. batch: eventObjBatch
  25526. };
  25527. } else {
  25528. eventObj = eventObjBatch[0];
  25529. }
  25530. this[IN_MAIN_PROCESS_KEY] = false;
  25531. if (!silent) {
  25532. var messageCenter = this._messageCenter;
  25533. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  25534. if (isSelectChange) {
  25535. var newObj = {
  25536. type: 'selectchanged',
  25537. escapeConnect: escapeConnect,
  25538. selected: getAllSelectedIndices(ecModel),
  25539. isFromClick: payload.isFromClick || false,
  25540. fromAction: payload.type,
  25541. fromActionPayload: payload
  25542. };
  25543. messageCenter.trigger(newObj.type, newObj);
  25544. }
  25545. }
  25546. };
  25547. flushPendingActions = function (silent) {
  25548. var pendingActions = this._pendingActions;
  25549. while (pendingActions.length) {
  25550. var payload = pendingActions.shift();
  25551. doDispatchAction.call(this, payload, silent);
  25552. }
  25553. };
  25554. triggerUpdatedEvent = function (silent) {
  25555. !silent && this.trigger('updated');
  25556. };
  25557. /**
  25558. * Event `rendered` is triggered when zr
  25559. * rendered. It is useful for realtime
  25560. * snapshot (reflect animation).
  25561. *
  25562. * Event `finished` is triggered when:
  25563. * (1) zrender rendering finished.
  25564. * (2) initial animation finished.
  25565. * (3) progressive rendering finished.
  25566. * (4) no pending action.
  25567. * (5) no delayed setOption needs to be processed.
  25568. */
  25569. bindRenderedEvent = function (zr, ecIns) {
  25570. zr.on('rendered', function (params) {
  25571. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatly,
  25572. // so it should only be triggered when rendering indeed happend
  25573. // in zrender. (Consider the case that dipatchAction is keep
  25574. // triggering when mouse move).
  25575. if ( // Although zr is dirty if initial animation is not finished
  25576. // and this checking is called on frame, we also check
  25577. // animation finished for robustness.
  25578. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  25579. ecIns.trigger('finished');
  25580. }
  25581. });
  25582. };
  25583. bindMouseEvent = function (zr, ecIns) {
  25584. zr.on('mouseover', function (e) {
  25585. var el = e.target;
  25586. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  25587. if (dispatcher) {
  25588. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  25589. markStatusToUpdate(ecIns);
  25590. }
  25591. }).on('mouseout', function (e) {
  25592. var el = e.target;
  25593. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  25594. if (dispatcher) {
  25595. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  25596. markStatusToUpdate(ecIns);
  25597. }
  25598. }).on('click', function (e) {
  25599. var el = e.target;
  25600. var dispatcher = findEventDispatcher(el, function (target) {
  25601. return getECData(target).dataIndex != null;
  25602. }, true);
  25603. if (dispatcher) {
  25604. var actionType = dispatcher.selected ? 'unselect' : 'select';
  25605. var ecData = getECData(dispatcher);
  25606. ecIns._api.dispatchAction({
  25607. type: actionType,
  25608. dataType: ecData.dataType,
  25609. dataIndexInside: ecData.dataIndex,
  25610. seriesIndex: ecData.seriesIndex,
  25611. isFromClick: true
  25612. });
  25613. }
  25614. });
  25615. };
  25616. function clearColorPalette(ecModel) {
  25617. ecModel.clearColorPalette();
  25618. ecModel.eachSeries(function (seriesModel) {
  25619. seriesModel.clearColorPalette();
  25620. });
  25621. }
  25622. function allocateZlevels(ecModel) {
  25623. var componentZLevels = [];
  25624. var seriesZLevels = [];
  25625. var hasSeperateZLevel = false;
  25626. ecModel.eachComponent(function (componentType, componentModel) {
  25627. var zlevel = componentModel.get('zlevel') || 0;
  25628. var z = componentModel.get('z') || 0;
  25629. var zlevelKey = componentModel.getZLevelKey();
  25630. hasSeperateZLevel = hasSeperateZLevel || !!zlevelKey;
  25631. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  25632. zlevel: zlevel,
  25633. z: z,
  25634. idx: componentModel.componentIndex,
  25635. type: componentType,
  25636. key: zlevelKey
  25637. });
  25638. });
  25639. if (hasSeperateZLevel) {
  25640. // Series after component
  25641. var zLevels = componentZLevels.concat(seriesZLevels);
  25642. var lastSeriesZLevel_1;
  25643. var lastSeriesKey_1;
  25644. sort(zLevels, function (a, b) {
  25645. if (a.zlevel === b.zlevel) {
  25646. return a.z - b.z;
  25647. }
  25648. return a.zlevel - b.zlevel;
  25649. });
  25650. each(zLevels, function (item) {
  25651. var componentModel = ecModel.getComponent(item.type, item.idx);
  25652. var zlevel = item.zlevel;
  25653. var key = item.key;
  25654. if (lastSeriesZLevel_1 != null) {
  25655. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  25656. }
  25657. if (key) {
  25658. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  25659. zlevel++;
  25660. }
  25661. lastSeriesKey_1 = key;
  25662. } else if (lastSeriesKey_1) {
  25663. if (zlevel === lastSeriesZLevel_1) {
  25664. zlevel++;
  25665. }
  25666. lastSeriesKey_1 = '';
  25667. }
  25668. lastSeriesZLevel_1 = zlevel;
  25669. componentModel.setZLevel(zlevel);
  25670. });
  25671. }
  25672. }
  25673. render = function (ecIns, ecModel, api, payload, updateParams) {
  25674. allocateZlevels(ecModel);
  25675. renderComponents(ecIns, ecModel, api, payload, updateParams);
  25676. each(ecIns._chartsViews, function (chart) {
  25677. chart.__alive = false;
  25678. });
  25679. renderSeries(ecIns, ecModel, api, payload, updateParams); // Remove groups of unrendered charts
  25680. each(ecIns._chartsViews, function (chart) {
  25681. if (!chart.__alive) {
  25682. chart.remove(ecModel, api);
  25683. }
  25684. });
  25685. };
  25686. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  25687. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25688. var componentModel = componentView.__model;
  25689. clearStates(componentModel, componentView);
  25690. componentView.render(componentModel, ecModel, api, payload);
  25691. updateZ(componentModel, componentView);
  25692. updateStates(componentModel, componentView);
  25693. });
  25694. };
  25695. /**
  25696. * Render each chart and component
  25697. */
  25698. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  25699. // Render all charts
  25700. var scheduler = ecIns._scheduler;
  25701. updateParams = extend(updateParams || {}, {
  25702. updatedSeries: ecModel.getSeries()
  25703. }); // TODO progressive?
  25704. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  25705. var unfinished = false;
  25706. ecModel.eachSeries(function (seriesModel) {
  25707. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25708. chartView.__alive = true;
  25709. var renderTask = chartView.renderTask;
  25710. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  25711. clearStates(seriesModel, chartView);
  25712. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25713. renderTask.dirty();
  25714. }
  25715. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  25716. unfinished = true;
  25717. }
  25718. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  25719. // increamental render (alway render from the __startIndex each frame)
  25720. // chartView.group.markRedraw();
  25721. updateBlend(seriesModel, chartView);
  25722. updateSeriesElementSelection(seriesModel);
  25723. });
  25724. scheduler.unfinished = unfinished || scheduler.unfinished;
  25725. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams); // transition after label is layouted.
  25726. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  25727. ecModel.eachSeries(function (seriesModel) {
  25728. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  25729. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  25730. // label should be in normal status when layouting.
  25731. updateStates(seriesModel, chartView);
  25732. }); // If use hover layer
  25733. updateHoverLayerStatus(ecIns, ecModel);
  25734. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  25735. };
  25736. markStatusToUpdate = function (ecIns) {
  25737. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  25738. ecIns.getZr().wakeUp();
  25739. };
  25740. applyChangedStates = function (ecIns) {
  25741. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  25742. return;
  25743. }
  25744. ecIns.getZr().storage.traverse(function (el) {
  25745. // Not applied on removed elements, it may still in fading.
  25746. if (isElementRemoved(el)) {
  25747. return;
  25748. }
  25749. applyElementStates(el);
  25750. });
  25751. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  25752. };
  25753. function applyElementStates(el) {
  25754. var newStates = [];
  25755. var oldStates = el.currentStates; // Keep other states.
  25756. for (var i = 0; i < oldStates.length; i++) {
  25757. var stateName = oldStates[i];
  25758. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  25759. newStates.push(stateName);
  25760. }
  25761. } // Only use states when it's exists.
  25762. if (el.selected && el.states.select) {
  25763. newStates.push('select');
  25764. }
  25765. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  25766. newStates.push('emphasis');
  25767. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  25768. newStates.push('blur');
  25769. }
  25770. el.useStates(newStates);
  25771. }
  25772. function updateHoverLayerStatus(ecIns, ecModel) {
  25773. var zr = ecIns._zr;
  25774. var storage = zr.storage;
  25775. var elCount = 0;
  25776. storage.traverse(function (el) {
  25777. if (!el.isGroup) {
  25778. elCount++;
  25779. }
  25780. });
  25781. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  25782. ecModel.eachSeries(function (seriesModel) {
  25783. if (seriesModel.preventUsingHoverLayer) {
  25784. return;
  25785. }
  25786. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25787. if (chartView.__alive) {
  25788. chartView.eachRendered(function (el) {
  25789. if (el.states.emphasis) {
  25790. el.states.emphasis.hoverLayer = true;
  25791. }
  25792. });
  25793. }
  25794. });
  25795. }
  25796. }
  25797. /**
  25798. * Update chart and blend.
  25799. */
  25800. function updateBlend(seriesModel, chartView) {
  25801. var blendMode = seriesModel.get('blendMode') || null;
  25802. chartView.eachRendered(function (el) {
  25803. // FIXME marker and other components
  25804. if (!el.isGroup) {
  25805. // DONT mark the element dirty. In case element is incremental and don't wan't to rerender.
  25806. el.style.blend = blendMode;
  25807. }
  25808. });
  25809. }
  25810. function updateZ(model, view) {
  25811. if (model.preventAutoZ) {
  25812. return;
  25813. }
  25814. var z = model.get('z') || 0;
  25815. var zlevel = model.get('zlevel') || 0; // Set z and zlevel
  25816. view.eachRendered(function (el) {
  25817. doUpdateZ(el, z, zlevel, -Infinity); // Don't traverse the children because it has been traversed in _updateZ.
  25818. return true;
  25819. });
  25820. }
  25821. function doUpdateZ(el, z, zlevel, maxZ2) {
  25822. // Group may also have textContent
  25823. var label = el.getTextContent();
  25824. var labelLine = el.getTextGuideLine();
  25825. var isGroup = el.isGroup;
  25826. if (isGroup) {
  25827. // set z & zlevel of children elements of Group
  25828. var children = el.childrenRef();
  25829. for (var i = 0; i < children.length; i++) {
  25830. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  25831. }
  25832. } else {
  25833. // not Group
  25834. el.z = z;
  25835. el.zlevel = zlevel;
  25836. maxZ2 = Math.max(el.z2, maxZ2);
  25837. } // always set z and zlevel if label/labelLine exists
  25838. if (label) {
  25839. label.z = z;
  25840. label.zlevel = zlevel; // lift z2 of text content
  25841. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  25842. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  25843. }
  25844. if (labelLine) {
  25845. var textGuideLineConfig = el.textGuideLineConfig;
  25846. labelLine.z = z;
  25847. labelLine.zlevel = zlevel;
  25848. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  25849. }
  25850. return maxZ2;
  25851. } // Clear states without animation.
  25852. // TODO States on component.
  25853. function clearStates(model, view) {
  25854. view.eachRendered(function (el) {
  25855. // Not applied on removed elements, it may still in fading.
  25856. if (isElementRemoved(el)) {
  25857. return;
  25858. }
  25859. var textContent = el.getTextContent();
  25860. var textGuide = el.getTextGuideLine();
  25861. if (el.stateTransition) {
  25862. el.stateTransition = null;
  25863. }
  25864. if (textContent && textContent.stateTransition) {
  25865. textContent.stateTransition = null;
  25866. }
  25867. if (textGuide && textGuide.stateTransition) {
  25868. textGuide.stateTransition = null;
  25869. } // TODO If el is incremental.
  25870. if (el.hasState()) {
  25871. el.prevStates = el.currentStates;
  25872. el.clearStates();
  25873. } else if (el.prevStates) {
  25874. el.prevStates = null;
  25875. }
  25876. });
  25877. }
  25878. function updateStates(model, view) {
  25879. var stateAnimationModel = model.getModel('stateAnimation');
  25880. var enableAnimation = model.isAnimationEnabled();
  25881. var duration = stateAnimationModel.get('duration');
  25882. var stateTransition = duration > 0 ? {
  25883. duration: duration,
  25884. delay: stateAnimationModel.get('delay'),
  25885. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  25886. } : null;
  25887. view.eachRendered(function (el) {
  25888. if (el.states && el.states.emphasis) {
  25889. // Not applied on removed elements, it may still in fading.
  25890. if (isElementRemoved(el)) {
  25891. return;
  25892. }
  25893. if (el instanceof Path) {
  25894. savePathStates(el);
  25895. } // Only updated on changed element. In case element is incremental and don't wan't to rerender.
  25896. // TODO, a more proper way?
  25897. if (el.__dirty) {
  25898. var prevStates = el.prevStates; // Restore states without animation
  25899. if (prevStates) {
  25900. el.useStates(prevStates);
  25901. }
  25902. } // Update state transition and enable animation again.
  25903. if (enableAnimation) {
  25904. el.stateTransition = stateTransition;
  25905. var textContent = el.getTextContent();
  25906. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  25907. if (textContent) {
  25908. textContent.stateTransition = stateTransition;
  25909. }
  25910. if (textGuide) {
  25911. textGuide.stateTransition = stateTransition;
  25912. }
  25913. } // The use higlighted and selected flag to toggle states.
  25914. if (el.__dirty) {
  25915. applyElementStates(el);
  25916. }
  25917. }
  25918. });
  25919. }
  25920. createExtensionAPI = function (ecIns) {
  25921. return new (
  25922. /** @class */
  25923. function (_super) {
  25924. __extends(class_1, _super);
  25925. function class_1() {
  25926. return _super !== null && _super.apply(this, arguments) || this;
  25927. }
  25928. class_1.prototype.getCoordinateSystems = function () {
  25929. return ecIns._coordSysMgr.getCoordinateSystems();
  25930. };
  25931. class_1.prototype.getComponentByElement = function (el) {
  25932. while (el) {
  25933. var modelInfo = el.__ecComponentInfo;
  25934. if (modelInfo != null) {
  25935. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  25936. }
  25937. el = el.parent;
  25938. }
  25939. };
  25940. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  25941. enterEmphasis(el, highlightDigit);
  25942. markStatusToUpdate(ecIns);
  25943. };
  25944. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  25945. leaveEmphasis(el, highlightDigit);
  25946. markStatusToUpdate(ecIns);
  25947. };
  25948. class_1.prototype.enterBlur = function (el) {
  25949. enterBlur(el);
  25950. markStatusToUpdate(ecIns);
  25951. };
  25952. class_1.prototype.leaveBlur = function (el) {
  25953. leaveBlur(el);
  25954. markStatusToUpdate(ecIns);
  25955. };
  25956. class_1.prototype.enterSelect = function (el) {
  25957. enterSelect(el);
  25958. markStatusToUpdate(ecIns);
  25959. };
  25960. class_1.prototype.leaveSelect = function (el) {
  25961. leaveSelect(el);
  25962. markStatusToUpdate(ecIns);
  25963. };
  25964. class_1.prototype.getModel = function () {
  25965. return ecIns.getModel();
  25966. };
  25967. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  25968. return ecIns.getViewOfComponentModel(componentModel);
  25969. };
  25970. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  25971. return ecIns.getViewOfSeriesModel(seriesModel);
  25972. };
  25973. return class_1;
  25974. }(ExtensionAPI))(ecIns);
  25975. };
  25976. enableConnect = function (chart) {
  25977. function updateConnectedChartsStatus(charts, status) {
  25978. for (var i = 0; i < charts.length; i++) {
  25979. var otherChart = charts[i];
  25980. otherChart[CONNECT_STATUS_KEY] = status;
  25981. }
  25982. }
  25983. each(eventActionMap, function (actionType, eventType) {
  25984. chart._messageCenter.on(eventType, function (event) {
  25985. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  25986. if (event && event.escapeConnect) {
  25987. return;
  25988. }
  25989. var action_1 = chart.makeActionFromEvent(event);
  25990. var otherCharts_1 = [];
  25991. each(instances$1, function (otherChart) {
  25992. if (otherChart !== chart && otherChart.group === chart.group) {
  25993. otherCharts_1.push(otherChart);
  25994. }
  25995. });
  25996. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  25997. each(otherCharts_1, function (otherChart) {
  25998. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  25999. otherChart.dispatchAction(action_1);
  26000. }
  26001. });
  26002. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  26003. }
  26004. });
  26005. });
  26006. };
  26007. }();
  26008. return ECharts;
  26009. }(Eventful);
  26010. var echartsProto = ECharts.prototype;
  26011. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  26012. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  26013. /**
  26014. * @deprecated
  26015. */
  26016. // @ts-ignore
  26017. echartsProto.one = function (eventName, cb, ctx) {
  26018. var self = this;
  26019. deprecateLog('ECharts#one is deprecated.');
  26020. function wrapped() {
  26021. var args2 = [];
  26022. for (var _i = 0; _i < arguments.length; _i++) {
  26023. args2[_i] = arguments[_i];
  26024. }
  26025. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  26026. self.off(eventName, wrapped);
  26027. }
  26028. this.on.call(this, eventName, wrapped, ctx);
  26029. };
  26030. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  26031. function disposedWarning(id) {
  26032. if ("development" !== 'production') {
  26033. console.warn('Instance ' + id + ' has been disposed');
  26034. }
  26035. }
  26036. var actions = {};
  26037. /**
  26038. * Map eventType to actionType
  26039. */
  26040. var eventActionMap = {};
  26041. var dataProcessorFuncs = [];
  26042. var optionPreprocessorFuncs = [];
  26043. var visualFuncs = [];
  26044. var themeStorage = {};
  26045. var loadingEffects = {};
  26046. var instances$1 = {};
  26047. var connectedGroups = {};
  26048. var idBase = +new Date() - 0;
  26049. var groupIdBase = +new Date() - 0;
  26050. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  26051. /**
  26052. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  26053. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  26054. * @param opts.width Use clientWidth of the input `dom` by default.
  26055. * Can be 'auto' (the same as null/undefined)
  26056. * @param opts.height Use clientHeight of the input `dom` by default.
  26057. * Can be 'auto' (the same as null/undefined)
  26058. * @param opts.locale Specify the locale.
  26059. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  26060. */
  26061. function init$1(dom, theme, opts) {
  26062. var isClient = !(opts && opts.ssr);
  26063. if (isClient) {
  26064. if ("development" !== 'production') {
  26065. if (!dom) {
  26066. throw new Error('Initialize failed: invalid dom.');
  26067. }
  26068. }
  26069. var existInstance = getInstanceByDom(dom);
  26070. if (existInstance) {
  26071. if ("development" !== 'production') {
  26072. console.warn('There is a chart instance already initialized on the dom.');
  26073. }
  26074. return existInstance;
  26075. }
  26076. if ("development" !== 'production') {
  26077. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  26078. console.warn('Can\'t get DOM width or height. Please check ' + 'dom.clientWidth and dom.clientHeight. They should not be 0.' + 'For example, you may need to call this in the callback ' + 'of window.onload.');
  26079. }
  26080. }
  26081. }
  26082. var chart = new ECharts(dom, theme, opts);
  26083. chart.id = 'ec_' + idBase++;
  26084. instances$1[chart.id] = chart;
  26085. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  26086. enableConnect(chart);
  26087. lifecycle.trigger('afterinit', chart);
  26088. return chart;
  26089. }
  26090. /**
  26091. * @usage
  26092. * (A)
  26093. * ```js
  26094. * let chart1 = echarts.init(dom1);
  26095. * let chart2 = echarts.init(dom2);
  26096. * chart1.group = 'xxx';
  26097. * chart2.group = 'xxx';
  26098. * echarts.connect('xxx');
  26099. * ```
  26100. * (B)
  26101. * ```js
  26102. * let chart1 = echarts.init(dom1);
  26103. * let chart2 = echarts.init(dom2);
  26104. * echarts.connect('xxx', [chart1, chart2]);
  26105. * ```
  26106. */
  26107. function connect(groupId) {
  26108. // Is array of charts
  26109. if (isArray(groupId)) {
  26110. var charts = groupId;
  26111. groupId = null; // If any chart has group
  26112. each(charts, function (chart) {
  26113. if (chart.group != null) {
  26114. groupId = chart.group;
  26115. }
  26116. });
  26117. groupId = groupId || 'g_' + groupIdBase++;
  26118. each(charts, function (chart) {
  26119. chart.group = groupId;
  26120. });
  26121. }
  26122. connectedGroups[groupId] = true;
  26123. return groupId;
  26124. }
  26125. /**
  26126. * @deprecated
  26127. */
  26128. function disConnect(groupId) {
  26129. connectedGroups[groupId] = false;
  26130. }
  26131. /**
  26132. * Alias and backword compat
  26133. */
  26134. var disconnect = disConnect;
  26135. /**
  26136. * Dispose a chart instance
  26137. */
  26138. function dispose$1(chart) {
  26139. if (isString(chart)) {
  26140. chart = instances$1[chart];
  26141. } else if (!(chart instanceof ECharts)) {
  26142. // Try to treat as dom
  26143. chart = getInstanceByDom(chart);
  26144. }
  26145. if (chart instanceof ECharts && !chart.isDisposed()) {
  26146. chart.dispose();
  26147. }
  26148. }
  26149. function getInstanceByDom(dom) {
  26150. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  26151. }
  26152. function getInstanceById(key) {
  26153. return instances$1[key];
  26154. }
  26155. /**
  26156. * Register theme
  26157. */
  26158. function registerTheme(name, theme) {
  26159. themeStorage[name] = theme;
  26160. }
  26161. /**
  26162. * Register option preprocessor
  26163. */
  26164. function registerPreprocessor(preprocessorFunc) {
  26165. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  26166. optionPreprocessorFuncs.push(preprocessorFunc);
  26167. }
  26168. }
  26169. function registerProcessor(priority, processor) {
  26170. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  26171. }
  26172. /**
  26173. * Register postIniter
  26174. * @param {Function} postInitFunc
  26175. */
  26176. function registerPostInit(postInitFunc) {
  26177. registerUpdateLifecycle('afterinit', postInitFunc);
  26178. }
  26179. /**
  26180. * Register postUpdater
  26181. * @param {Function} postUpdateFunc
  26182. */
  26183. function registerPostUpdate(postUpdateFunc) {
  26184. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  26185. }
  26186. function registerUpdateLifecycle(name, cb) {
  26187. lifecycle.on(name, cb);
  26188. }
  26189. function registerAction(actionInfo, eventName, action) {
  26190. if (isFunction(eventName)) {
  26191. action = eventName;
  26192. eventName = '';
  26193. }
  26194. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  26195. event: eventName
  26196. }][0]; // Event name is all lowercase
  26197. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  26198. eventName = actionInfo.event;
  26199. if (eventActionMap[eventName]) {
  26200. // Already registered.
  26201. return;
  26202. } // Validate action type and event name.
  26203. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  26204. if (!actions[actionType]) {
  26205. actions[actionType] = {
  26206. action: action,
  26207. actionInfo: actionInfo
  26208. };
  26209. }
  26210. eventActionMap[eventName] = actionType;
  26211. }
  26212. function registerCoordinateSystem(type, coordSysCreator) {
  26213. CoordinateSystemManager.register(type, coordSysCreator);
  26214. }
  26215. /**
  26216. * Get dimensions of specified coordinate system.
  26217. * @param {string} type
  26218. * @return {Array.<string|Object>}
  26219. */
  26220. function getCoordinateSystemDimensions(type) {
  26221. var coordSysCreator = CoordinateSystemManager.get(type);
  26222. if (coordSysCreator) {
  26223. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  26224. }
  26225. }
  26226. function registerLayout(priority, layoutTask) {
  26227. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26228. }
  26229. function registerVisual(priority, visualTask) {
  26230. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26231. }
  26232. var registeredTasks = [];
  26233. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26234. if (isFunction(priority) || isObject(priority)) {
  26235. fn = priority;
  26236. priority = defaultPriority;
  26237. }
  26238. if ("development" !== 'production') {
  26239. if (isNaN(priority) || priority == null) {
  26240. throw new Error('Illegal priority');
  26241. } // Check duplicate
  26242. each(targetList, function (wrap) {
  26243. assert(wrap.__raw !== fn);
  26244. });
  26245. } // Already registered
  26246. if (indexOf(registeredTasks, fn) >= 0) {
  26247. return;
  26248. }
  26249. registeredTasks.push(fn);
  26250. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26251. stageHandler.__prio = priority;
  26252. stageHandler.__raw = fn;
  26253. targetList.push(stageHandler);
  26254. }
  26255. function registerLoading(name, loadingFx) {
  26256. loadingEffects[name] = loadingFx;
  26257. }
  26258. /**
  26259. * ZRender need a canvas context to do measureText.
  26260. * But in node environment canvas may be created by node-canvas.
  26261. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26262. *
  26263. *
  26264. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  26265. *
  26266. * @example
  26267. * let Canvas = require('canvas');
  26268. * let echarts = require('echarts');
  26269. * echarts.setCanvasCreator(function () {
  26270. * // Small size is enough.
  26271. * return new Canvas(32, 32);
  26272. * });
  26273. */
  26274. function setCanvasCreator(creator) {
  26275. if ("development" !== 'production') {
  26276. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  26277. }
  26278. setPlatformAPI({
  26279. createCanvas: creator
  26280. });
  26281. }
  26282. /**
  26283. * The parameters and usage: see `geoSourceManager.registerMap`.
  26284. * Compatible with previous `echarts.registerMap`.
  26285. */
  26286. function registerMap(mapName, geoJson, specialAreas) {
  26287. var registerMap = getImpl('registerMap');
  26288. registerMap && registerMap(mapName, geoJson, specialAreas);
  26289. }
  26290. function getMap(mapName) {
  26291. var getMap = getImpl('getMap');
  26292. return getMap && getMap(mapName);
  26293. }
  26294. var registerTransform = registerExternalTransform;
  26295. /**
  26296. * Globa dispatchAction to a specified chart instance.
  26297. */
  26298. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  26299. // if (!payload || !payload.chartId) {
  26300. // // Must have chartId to find chart
  26301. // return;
  26302. // }
  26303. // const chart = instances[payload.chartId];
  26304. // if (chart) {
  26305. // chart.dispatchAction(payload, opt);
  26306. // }
  26307. // }
  26308. // Buitlin global visual
  26309. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  26310. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  26311. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  26312. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  26313. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  26314. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  26315. registerPreprocessor(globalBackwardCompat);
  26316. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26317. registerLoading('default', defaultLoading); // Default actions
  26318. registerAction({
  26319. type: HIGHLIGHT_ACTION_TYPE,
  26320. event: HIGHLIGHT_ACTION_TYPE,
  26321. update: HIGHLIGHT_ACTION_TYPE
  26322. }, noop);
  26323. registerAction({
  26324. type: DOWNPLAY_ACTION_TYPE,
  26325. event: DOWNPLAY_ACTION_TYPE,
  26326. update: DOWNPLAY_ACTION_TYPE
  26327. }, noop);
  26328. registerAction({
  26329. type: SELECT_ACTION_TYPE,
  26330. event: SELECT_ACTION_TYPE,
  26331. update: SELECT_ACTION_TYPE
  26332. }, noop);
  26333. registerAction({
  26334. type: UNSELECT_ACTION_TYPE,
  26335. event: UNSELECT_ACTION_TYPE,
  26336. update: UNSELECT_ACTION_TYPE
  26337. }, noop);
  26338. registerAction({
  26339. type: TOGGLE_SELECT_ACTION_TYPE,
  26340. event: TOGGLE_SELECT_ACTION_TYPE,
  26341. update: TOGGLE_SELECT_ACTION_TYPE
  26342. }, noop); // Default theme
  26343. registerTheme('light', lightTheme);
  26344. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  26345. // be mounted on `echarts` is the extension `dataTool` is imported.
  26346. var dataTool = {};
  26347. var extensions = [];
  26348. var extensionRegisters = {
  26349. registerPreprocessor: registerPreprocessor,
  26350. registerProcessor: registerProcessor,
  26351. registerPostInit: registerPostInit,
  26352. registerPostUpdate: registerPostUpdate,
  26353. registerUpdateLifecycle: registerUpdateLifecycle,
  26354. registerAction: registerAction,
  26355. registerCoordinateSystem: registerCoordinateSystem,
  26356. registerLayout: registerLayout,
  26357. registerVisual: registerVisual,
  26358. registerTransform: registerTransform,
  26359. registerLoading: registerLoading,
  26360. registerMap: registerMap,
  26361. registerImpl: registerImpl,
  26362. PRIORITY: PRIORITY,
  26363. ComponentModel: ComponentModel,
  26364. ComponentView: ComponentView,
  26365. SeriesModel: SeriesModel,
  26366. ChartView: ChartView,
  26367. // TODO Use ComponentModel and SeriesModel instead of Constructor
  26368. registerComponentModel: function (ComponentModelClass) {
  26369. ComponentModel.registerClass(ComponentModelClass);
  26370. },
  26371. registerComponentView: function (ComponentViewClass) {
  26372. ComponentView.registerClass(ComponentViewClass);
  26373. },
  26374. registerSeriesModel: function (SeriesModelClass) {
  26375. SeriesModel.registerClass(SeriesModelClass);
  26376. },
  26377. registerChartView: function (ChartViewClass) {
  26378. ChartView.registerClass(ChartViewClass);
  26379. },
  26380. registerSubTypeDefaulter: function (componentType, defaulter) {
  26381. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  26382. },
  26383. registerPainter: function (painterType, PainterCtor) {
  26384. registerPainter(painterType, PainterCtor);
  26385. }
  26386. };
  26387. function use(ext) {
  26388. if (isArray(ext)) {
  26389. // use([ChartLine, ChartBar]);
  26390. each(ext, function (singleExt) {
  26391. use(singleExt);
  26392. });
  26393. return;
  26394. }
  26395. if (indexOf(extensions, ext) >= 0) {
  26396. return;
  26397. }
  26398. extensions.push(ext);
  26399. if (isFunction(ext)) {
  26400. ext = {
  26401. install: ext
  26402. };
  26403. }
  26404. ext.install(extensionRegisters);
  26405. }
  26406. /*
  26407. * Licensed to the Apache Software Foundation (ASF) under one
  26408. * or more contributor license agreements. See the NOTICE file
  26409. * distributed with this work for additional information
  26410. * regarding copyright ownership. The ASF licenses this file
  26411. * to you under the Apache License, Version 2.0 (the
  26412. * "License"); you may not use this file except in compliance
  26413. * with the License. You may obtain a copy of the License at
  26414. *
  26415. * http://www.apache.org/licenses/LICENSE-2.0
  26416. *
  26417. * Unless required by applicable law or agreed to in writing,
  26418. * software distributed under the License is distributed on an
  26419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26420. * KIND, either express or implied. See the License for the
  26421. * specific language governing permissions and limitations
  26422. * under the License.
  26423. */
  26424. /**
  26425. * AUTO-GENERATED FILE. DO NOT MODIFY.
  26426. */
  26427. /*
  26428. * Licensed to the Apache Software Foundation (ASF) under one
  26429. * or more contributor license agreements. See the NOTICE file
  26430. * distributed with this work for additional information
  26431. * regarding copyright ownership. The ASF licenses this file
  26432. * to you under the Apache License, Version 2.0 (the
  26433. * "License"); you may not use this file except in compliance
  26434. * with the License. You may obtain a copy of the License at
  26435. *
  26436. * http://www.apache.org/licenses/LICENSE-2.0
  26437. *
  26438. * Unless required by applicable law or agreed to in writing,
  26439. * software distributed under the License is distributed on an
  26440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26441. * KIND, either express or implied. See the License for the
  26442. * specific language governing permissions and limitations
  26443. * under the License.
  26444. */
  26445. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  26446. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  26447. }
  26448. function defaultKeyGetter(item) {
  26449. return item;
  26450. }
  26451. var DataDiffer =
  26452. /** @class */
  26453. function () {
  26454. /**
  26455. * @param context Can be visited by this.context in callback.
  26456. */
  26457. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  26458. diffMode) {
  26459. this._old = oldArr;
  26460. this._new = newArr;
  26461. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26462. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  26463. this.context = context;
  26464. this._diffModeMultiple = diffMode === 'multiple';
  26465. }
  26466. /**
  26467. * Callback function when add a data
  26468. */
  26469. DataDiffer.prototype.add = function (func) {
  26470. this._add = func;
  26471. return this;
  26472. };
  26473. /**
  26474. * Callback function when update a data
  26475. */
  26476. DataDiffer.prototype.update = function (func) {
  26477. this._update = func;
  26478. return this;
  26479. };
  26480. /**
  26481. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  26482. */
  26483. DataDiffer.prototype.updateManyToOne = function (func) {
  26484. this._updateManyToOne = func;
  26485. return this;
  26486. };
  26487. /**
  26488. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  26489. */
  26490. DataDiffer.prototype.updateOneToMany = function (func) {
  26491. this._updateOneToMany = func;
  26492. return this;
  26493. };
  26494. /**
  26495. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  26496. */
  26497. DataDiffer.prototype.updateManyToMany = function (func) {
  26498. this._updateManyToMany = func;
  26499. return this;
  26500. };
  26501. /**
  26502. * Callback function when remove a data
  26503. */
  26504. DataDiffer.prototype.remove = function (func) {
  26505. this._remove = func;
  26506. return this;
  26507. };
  26508. DataDiffer.prototype.execute = function () {
  26509. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  26510. };
  26511. DataDiffer.prototype._executeOneToOne = function () {
  26512. var oldArr = this._old;
  26513. var newArr = this._new;
  26514. var newDataIndexMap = {};
  26515. var oldDataKeyArr = new Array(oldArr.length);
  26516. var newDataKeyArr = new Array(newArr.length);
  26517. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  26518. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  26519. for (var i = 0; i < oldArr.length; i++) {
  26520. var oldKey = oldDataKeyArr[i];
  26521. var newIdxMapVal = newDataIndexMap[oldKey];
  26522. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  26523. if (newIdxMapValLen > 1) {
  26524. // Consider there is duplicate key (for example, use dataItem.name as key).
  26525. // We should make sure every item in newArr and oldArr can be visited.
  26526. var newIdx = newIdxMapVal.shift();
  26527. if (newIdxMapVal.length === 1) {
  26528. newDataIndexMap[oldKey] = newIdxMapVal[0];
  26529. }
  26530. this._update && this._update(newIdx, i);
  26531. } else if (newIdxMapValLen === 1) {
  26532. newDataIndexMap[oldKey] = null;
  26533. this._update && this._update(newIdxMapVal, i);
  26534. } else {
  26535. this._remove && this._remove(i);
  26536. }
  26537. }
  26538. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  26539. };
  26540. /**
  26541. * For example, consider the case:
  26542. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  26543. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  26544. * Where:
  26545. * o0, o1, n0 has key 'a' (many to one)
  26546. * o5, n4, n5, n6 has key 'b' (one to many)
  26547. * o2, n1 has key 'c' (one to one)
  26548. * n2, n3 has key 'd' (add)
  26549. * o3, o4 has key 'e' (remove)
  26550. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  26551. * Then:
  26552. * (The order of the following directives are not ensured.)
  26553. * this._updateManyToOne(n0, [o0, o1]);
  26554. * this._updateOneToMany([n4, n5, n6], o5);
  26555. * this._update(n1, o2);
  26556. * this._remove(o3);
  26557. * this._remove(o4);
  26558. * this._remove(o6);
  26559. * this._remove(o7);
  26560. * this._add(n2);
  26561. * this._add(n3);
  26562. * this._add(n7);
  26563. * this._add(n8);
  26564. */
  26565. DataDiffer.prototype._executeMultiple = function () {
  26566. var oldArr = this._old;
  26567. var newArr = this._new;
  26568. var oldDataIndexMap = {};
  26569. var newDataIndexMap = {};
  26570. var oldDataKeyArr = [];
  26571. var newDataKeyArr = [];
  26572. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  26573. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  26574. for (var i = 0; i < oldDataKeyArr.length; i++) {
  26575. var oldKey = oldDataKeyArr[i];
  26576. var oldIdxMapVal = oldDataIndexMap[oldKey];
  26577. var newIdxMapVal = newDataIndexMap[oldKey];
  26578. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  26579. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  26580. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  26581. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  26582. newDataIndexMap[oldKey] = null;
  26583. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  26584. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  26585. newDataIndexMap[oldKey] = null;
  26586. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  26587. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  26588. newDataIndexMap[oldKey] = null;
  26589. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  26590. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  26591. newDataIndexMap[oldKey] = null;
  26592. } else if (oldIdxMapValLen > 1) {
  26593. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  26594. this._remove && this._remove(oldIdxMapVal[i_1]);
  26595. }
  26596. } else {
  26597. this._remove && this._remove(oldIdxMapVal);
  26598. }
  26599. }
  26600. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  26601. };
  26602. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  26603. for (var i = 0; i < newDataKeyArr.length; i++) {
  26604. var newKey = newDataKeyArr[i];
  26605. var newIdxMapVal = newDataIndexMap[newKey];
  26606. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  26607. if (idxMapValLen > 1) {
  26608. for (var j = 0; j < idxMapValLen; j++) {
  26609. this._add && this._add(newIdxMapVal[j]);
  26610. }
  26611. } else if (idxMapValLen === 1) {
  26612. this._add && this._add(newIdxMapVal);
  26613. } // Support both `newDataKeyArr` are duplication removed or not removed.
  26614. newDataIndexMap[newKey] = null;
  26615. }
  26616. };
  26617. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  26618. map, // In 'byKey', the output `keyArr` is duplication removed.
  26619. // In 'byIndex', the output `keyArr` is not duplication removed and
  26620. // its indices are accurately corresponding to `arr`.
  26621. keyArr, keyGetterName) {
  26622. var cbModeMultiple = this._diffModeMultiple;
  26623. for (var i = 0; i < arr.length; i++) {
  26624. // Add prefix to avoid conflict with Object.prototype.
  26625. var key = '_ec_' + this[keyGetterName](arr[i], i);
  26626. if (!cbModeMultiple) {
  26627. keyArr[i] = key;
  26628. }
  26629. if (!map) {
  26630. continue;
  26631. }
  26632. var idxMapVal = map[key];
  26633. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  26634. if (idxMapValLen === 0) {
  26635. // Simple optimize: in most cases, one index has one key,
  26636. // do not need array.
  26637. map[key] = i;
  26638. if (cbModeMultiple) {
  26639. keyArr.push(key);
  26640. }
  26641. } else if (idxMapValLen === 1) {
  26642. map[key] = [idxMapVal, i];
  26643. } else {
  26644. idxMapVal.push(i);
  26645. }
  26646. }
  26647. };
  26648. return DataDiffer;
  26649. }();
  26650. var DimensionUserOuput =
  26651. /** @class */
  26652. function () {
  26653. function DimensionUserOuput(encode, dimRequest) {
  26654. this._encode = encode;
  26655. this._schema = dimRequest;
  26656. }
  26657. DimensionUserOuput.prototype.get = function () {
  26658. return {
  26659. // Do not generate full dimension name until fist used.
  26660. fullDimensions: this._getFullDimensionNames(),
  26661. encode: this._encode
  26662. };
  26663. };
  26664. /**
  26665. * Get all data store dimension names.
  26666. * Theoretically a series data store is defined both by series and used dataset (if any).
  26667. * If some dimensions are omitted for performance reason in `this.dimensions`,
  26668. * the dimension name may not be auto-generated if user does not specify a dimension name.
  26669. * In this case, the dimension name is `null`/`undefined`.
  26670. */
  26671. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  26672. if (!this._cachedDimNames) {
  26673. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  26674. }
  26675. return this._cachedDimNames;
  26676. };
  26677. return DimensionUserOuput;
  26678. }();
  26679. function summarizeDimensions(data, schema) {
  26680. var summary = {};
  26681. var encode = summary.encode = {};
  26682. var notExtraCoordDimMap = createHashMap();
  26683. var defaultedLabel = [];
  26684. var defaultedTooltip = [];
  26685. var userOutputEncode = {};
  26686. each(data.dimensions, function (dimName) {
  26687. var dimItem = data.getDimensionInfo(dimName);
  26688. var coordDim = dimItem.coordDim;
  26689. if (coordDim) {
  26690. if ("development" !== 'production') {
  26691. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  26692. }
  26693. var coordDimIndex = dimItem.coordDimIndex;
  26694. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26695. if (!dimItem.isExtraCoord) {
  26696. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  26697. // because when dataset is used, it is hard to guess which dimension
  26698. // can be value dimension. If both show x, y on label is not look good,
  26699. // and conventionally y axis is focused more.
  26700. if (mayLabelDimType(dimItem.type)) {
  26701. defaultedLabel[0] = dimName;
  26702. } // User output encode do not contain generated coords.
  26703. // And it only has index. User can use index to retrieve value from the raw item array.
  26704. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  26705. }
  26706. if (dimItem.defaultTooltip) {
  26707. defaultedTooltip.push(dimName);
  26708. }
  26709. }
  26710. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  26711. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26712. var dimIndex = dimItem.otherDims[otherDim];
  26713. if (dimIndex != null && dimIndex !== false) {
  26714. encodeArr[dimIndex] = dimItem.name;
  26715. }
  26716. });
  26717. });
  26718. var dataDimsOnCoord = [];
  26719. var encodeFirstDimNotExtra = {};
  26720. notExtraCoordDimMap.each(function (v, coordDim) {
  26721. var dimArr = encode[coordDim];
  26722. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  26723. // dim canot on more than one coordDim.
  26724. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26725. });
  26726. summary.dataDimsOnCoord = dataDimsOnCoord;
  26727. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  26728. return data.getDimensionInfo(dimName).storeDimIndex;
  26729. });
  26730. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26731. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  26732. // in this way. Use label.formatter instead. May be remove this approach someday.
  26733. if (encodeLabel && encodeLabel.length) {
  26734. defaultedLabel = encodeLabel.slice();
  26735. }
  26736. var encodeTooltip = encode.tooltip;
  26737. if (encodeTooltip && encodeTooltip.length) {
  26738. defaultedTooltip = encodeTooltip.slice();
  26739. } else if (!defaultedTooltip.length) {
  26740. defaultedTooltip = defaultedLabel.slice();
  26741. }
  26742. encode.defaultedLabel = defaultedLabel;
  26743. encode.defaultedTooltip = defaultedTooltip;
  26744. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  26745. return summary;
  26746. }
  26747. function getOrCreateEncodeArr(encode, dim) {
  26748. if (!encode.hasOwnProperty(dim)) {
  26749. encode[dim] = [];
  26750. }
  26751. return encode[dim];
  26752. } // FIXME:TS should be type `AxisType`
  26753. function getDimensionTypeByAxis(axisType) {
  26754. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  26755. }
  26756. function mayLabelDimType(dimType) {
  26757. // In most cases, ordinal and time do not suitable for label.
  26758. // Ordinal info can be displayed on axis. Time is too long.
  26759. return !(dimType === 'ordinal' || dimType === 'time');
  26760. } // function findTheLastDimMayLabel(data) {
  26761. // // Get last value dim
  26762. // let dimensions = data.dimensions.slice();
  26763. // let valueType;
  26764. // let valueDim;
  26765. // while (dimensions.length && (
  26766. // valueDim = dimensions.pop(),
  26767. // valueType = data.getDimensionInfo(valueDim).type,
  26768. // valueType === 'ordinal' || valueType === 'time'
  26769. // )) {} // jshint ignore:line
  26770. // return valueDim;
  26771. // }
  26772. var SeriesDimensionDefine =
  26773. /** @class */
  26774. function () {
  26775. /**
  26776. * @param opt All of the fields will be shallow copied.
  26777. */
  26778. function SeriesDimensionDefine(opt) {
  26779. /**
  26780. * The format of `otherDims` is:
  26781. * ```js
  26782. * {
  26783. * tooltip?: number
  26784. * label?: number
  26785. * itemName?: number
  26786. * seriesName?: number
  26787. * }
  26788. * ```
  26789. *
  26790. * A `series.encode` can specified these fields:
  26791. * ```js
  26792. * encode: {
  26793. * // "3, 1, 5" is the index of data dimension.
  26794. * tooltip: [3, 1, 5],
  26795. * label: [0, 3],
  26796. * ...
  26797. * }
  26798. * ```
  26799. * `otherDims` is the parse result of the `series.encode` above, like:
  26800. * ```js
  26801. * // Suppose the index of this data dimension is `3`.
  26802. * this.otherDims = {
  26803. * // `3` is at the index `0` of the `encode.tooltip`
  26804. * tooltip: 0,
  26805. * // `3` is at the index `1` of the `encode.label`
  26806. * label: 1
  26807. * };
  26808. * ```
  26809. *
  26810. * This prop should never be `null`/`undefined` after initialized.
  26811. */
  26812. this.otherDims = {};
  26813. if (opt != null) {
  26814. extend(this, opt);
  26815. }
  26816. }
  26817. return SeriesDimensionDefine;
  26818. }();
  26819. var inner$4 = makeInner();
  26820. var dimTypeShort = {
  26821. float: 'f',
  26822. int: 'i',
  26823. ordinal: 'o',
  26824. number: 'n',
  26825. time: 't'
  26826. };
  26827. /**
  26828. * Represents the dimension requirement of a series.
  26829. *
  26830. * NOTICE:
  26831. * When there are too many dimensions in dataset and many series, only the used dimensions
  26832. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  26833. * But users may query data by other unused dimension names.
  26834. * In this case, users can only query data if and only if they have defined dimension names
  26835. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  26836. * `source` dimensions.
  26837. */
  26838. var SeriesDataSchema =
  26839. /** @class */
  26840. function () {
  26841. function SeriesDataSchema(opt) {
  26842. this.dimensions = opt.dimensions;
  26843. this._dimOmitted = opt.dimensionOmitted;
  26844. this.source = opt.source;
  26845. this._fullDimCount = opt.fullDimensionCount;
  26846. this._updateDimOmitted(opt.dimensionOmitted);
  26847. }
  26848. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  26849. return this._dimOmitted;
  26850. };
  26851. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  26852. this._dimOmitted = dimensionOmitted;
  26853. if (!dimensionOmitted) {
  26854. return;
  26855. }
  26856. if (!this._dimNameMap) {
  26857. this._dimNameMap = ensureSourceDimNameMap(this.source);
  26858. }
  26859. };
  26860. /**
  26861. * @caution Can only be used when `dimensionOmitted: true`.
  26862. *
  26863. * Get index by user defined dimension name (i.e., not internal generate name).
  26864. * That is, get index from `dimensionsDefine`.
  26865. * If no `dimensionsDefine`, or no name get, return -1.
  26866. */
  26867. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  26868. return retrieve2(this._dimNameMap.get(dimName), -1);
  26869. };
  26870. /**
  26871. * @caution Can only be used when `dimensionOmitted: true`.
  26872. *
  26873. * Notice: may return `null`/`undefined` if user not specify dimension names.
  26874. */
  26875. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  26876. var dimensionsDefine = this.source.dimensionsDefine;
  26877. if (dimensionsDefine) {
  26878. return dimensionsDefine[dimIndex];
  26879. }
  26880. };
  26881. SeriesDataSchema.prototype.makeStoreSchema = function () {
  26882. var dimCount = this._fullDimCount;
  26883. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  26884. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount); // If source don't have dimensions or series don't omit unsed dimensions.
  26885. // Generate from seriesDimList directly
  26886. var dimHash = '';
  26887. var dims = [];
  26888. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  26889. var property = void 0;
  26890. var type = void 0;
  26891. var ordinalMeta = void 0;
  26892. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  26893. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  26894. property = willRetrieveDataByName ? seriesDimDef.name : null;
  26895. type = seriesDimDef.type;
  26896. ordinalMeta = seriesDimDef.ordinalMeta;
  26897. seriesDimIdx++;
  26898. } else {
  26899. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  26900. if (sourceDimDef) {
  26901. property = willRetrieveDataByName ? sourceDimDef.name : null;
  26902. type = sourceDimDef.type;
  26903. }
  26904. }
  26905. dims.push({
  26906. property: property,
  26907. type: type,
  26908. ordinalMeta: ordinalMeta
  26909. }); // If retrieving data by index,
  26910. // use <index, type, ordinalMeta> to determine whether data can be shared.
  26911. // (Becuase in this case there might be no dimension name defined in dataset, but indices always exists).
  26912. // (indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  26913. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  26914. // use <property, type, ordinalMeta> in hash.
  26915. if (willRetrieveDataByName && property != null // For data stack, we have make sure each series has its own dim on this store.
  26916. // So we do not add property to hash to make sure they can share this store.
  26917. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  26918. dimHash += makeHashStrict // Use escape character '`' in case that property name contains '$'.
  26919. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2') // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  26920. : property;
  26921. }
  26922. dimHash += '$';
  26923. dimHash += dimTypeShort[type] || 'f';
  26924. if (ordinalMeta) {
  26925. dimHash += ordinalMeta.uid;
  26926. }
  26927. dimHash += '$';
  26928. } // Source from endpoint(usually series) will be read differently
  26929. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  26930. // So we use this three props as key.
  26931. var source = this.source;
  26932. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  26933. return {
  26934. dimensions: dims,
  26935. hash: hash
  26936. };
  26937. };
  26938. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  26939. var result = [];
  26940. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  26941. var name_1 = void 0;
  26942. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  26943. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  26944. if (!seriesDimDef.isCalculationCoord) {
  26945. name_1 = seriesDimDef.name;
  26946. }
  26947. seriesDimIdx++;
  26948. } else {
  26949. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  26950. if (sourceDimDef) {
  26951. name_1 = sourceDimDef.name;
  26952. }
  26953. }
  26954. result.push(name_1);
  26955. }
  26956. return result;
  26957. };
  26958. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  26959. this.dimensions.push(dimDef);
  26960. dimDef.isCalculationCoord = true;
  26961. this._fullDimCount++; // If append dimension on a data store, consider the store
  26962. // might be shared by different series, series dimensions not
  26963. // really map to store dimensions.
  26964. this._updateDimOmitted(true);
  26965. };
  26966. return SeriesDataSchema;
  26967. }();
  26968. function isSeriesDataSchema(schema) {
  26969. return schema instanceof SeriesDataSchema;
  26970. }
  26971. function createDimNameMap(dimsDef) {
  26972. var dataDimNameMap = createHashMap();
  26973. for (var i = 0; i < (dimsDef || []).length; i++) {
  26974. var dimDefItemRaw = dimsDef[i];
  26975. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  26976. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  26977. dataDimNameMap.set(userDimName, i);
  26978. }
  26979. }
  26980. return dataDimNameMap;
  26981. }
  26982. function ensureSourceDimNameMap(source) {
  26983. var innerSource = inner$4(source);
  26984. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  26985. }
  26986. function shouldOmitUnusedDimensions(dimCount) {
  26987. return dimCount > 30;
  26988. }
  26989. var isObject$2 = isObject;
  26990. var map$1 = map;
  26991. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array; // Use prefix to avoid index to be the same as otherIdList[idx],
  26992. // which will cause weird udpate animation.
  26993. var ID_PREFIX = 'e\0\0';
  26994. var INDEX_NOT_FOUND = -1; // type SeriesDimensionIndex = DimensionIndex;
  26995. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  26996. var CLONE_PROPERTIES = ['_approximateExtent']; // -----------------------------
  26997. // Internal method declarations:
  26998. // -----------------------------
  26999. var prepareInvertedIndex;
  27000. var getId;
  27001. var getIdNameFromStore;
  27002. var normalizeDimensions;
  27003. var transferProperties;
  27004. var cloneListForMapAndSample;
  27005. var makeIdFromName;
  27006. var SeriesData =
  27007. /** @class */
  27008. function () {
  27009. /**
  27010. * @param dimensionsInput.dimensions
  27011. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  27012. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  27013. */
  27014. function SeriesData(dimensionsInput, hostModel) {
  27015. this.type = 'list';
  27016. this._dimOmitted = false;
  27017. this._nameList = [];
  27018. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  27019. // Never used yet (not used yet).
  27020. // private _optionModels: Model[] = [];
  27021. // Global visual properties after visual coding
  27022. this._visual = {}; // Globel layout properties.
  27023. this._layout = {}; // Item visual properties after visual coding
  27024. this._itemVisuals = []; // Item layout properties after layout
  27025. this._itemLayouts = []; // Graphic elemnents
  27026. this._graphicEls = []; // key: dim, value: extent
  27027. this._approximateExtent = {};
  27028. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  27029. // (in type `OptionDataItemObject`).
  27030. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  27031. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  27032. this.hasItemOption = false; // Methods that create a new list based on this list should be listed here.
  27033. // Notice that those method should `RETURN` the new list.
  27034. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  27035. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27036. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  27037. var dimensions;
  27038. var assignStoreDimIdx = false;
  27039. if (isSeriesDataSchema(dimensionsInput)) {
  27040. dimensions = dimensionsInput.dimensions;
  27041. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  27042. this._schema = dimensionsInput;
  27043. } else {
  27044. assignStoreDimIdx = true;
  27045. dimensions = dimensionsInput;
  27046. }
  27047. dimensions = dimensions || ['x', 'y'];
  27048. var dimensionInfos = {};
  27049. var dimensionNames = [];
  27050. var invertedIndicesMap = {};
  27051. var needsHasOwn = false;
  27052. var emptyObj = {};
  27053. for (var i = 0; i < dimensions.length; i++) {
  27054. // Use the original dimensions[i], where other flag props may exists.
  27055. var dimInfoInput = dimensions[i];
  27056. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  27057. name: dimInfoInput
  27058. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  27059. var dimensionName = dimensionInfo.name;
  27060. dimensionInfo.type = dimensionInfo.type || 'float';
  27061. if (!dimensionInfo.coordDim) {
  27062. dimensionInfo.coordDim = dimensionName;
  27063. dimensionInfo.coordDimIndex = 0;
  27064. }
  27065. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  27066. dimensionNames.push(dimensionName);
  27067. dimensionInfos[dimensionName] = dimensionInfo;
  27068. if (emptyObj[dimensionName] != null) {
  27069. needsHasOwn = true;
  27070. }
  27071. if (dimensionInfo.createInvertedIndices) {
  27072. invertedIndicesMap[dimensionName] = [];
  27073. }
  27074. if (otherDims.itemName === 0) {
  27075. this._nameDimIdx = i;
  27076. }
  27077. if (otherDims.itemId === 0) {
  27078. this._idDimIdx = i;
  27079. }
  27080. if ("development" !== 'production') {
  27081. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  27082. }
  27083. if (assignStoreDimIdx) {
  27084. dimensionInfo.storeDimIndex = i;
  27085. }
  27086. }
  27087. this.dimensions = dimensionNames;
  27088. this._dimInfos = dimensionInfos;
  27089. this._initGetDimensionInfo(needsHasOwn);
  27090. this.hostModel = hostModel;
  27091. this._invertedIndicesMap = invertedIndicesMap;
  27092. if (this._dimOmitted) {
  27093. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  27094. each(dimensionNames, function (dimName) {
  27095. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  27096. });
  27097. }
  27098. }
  27099. /**
  27100. *
  27101. * Get concrete dimension name by dimension name or dimension index.
  27102. * If input a dimension name, do not validate whether the dimension name exits.
  27103. *
  27104. * @caution
  27105. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  27106. * Because only those dimensions will have auto-generated dimension names if not
  27107. * have a user-specified name, and other dimensions will get a return of null/undefined.
  27108. *
  27109. * @notice Becuause of this reason, should better use `getDimensionIndex` instead, for examples:
  27110. * ```js
  27111. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  27112. * ```
  27113. *
  27114. * @return Concrete dim name.
  27115. */
  27116. SeriesData.prototype.getDimension = function (dim) {
  27117. var dimIdx = this._recognizeDimIndex(dim);
  27118. if (dimIdx == null) {
  27119. return dim;
  27120. }
  27121. dimIdx = dim;
  27122. if (!this._dimOmitted) {
  27123. return this.dimensions[dimIdx];
  27124. } // Retrieve from series dimension definition becuase it probably contains
  27125. // generated dimension name (like 'x', 'y').
  27126. var dimName = this._dimIdxToName.get(dimIdx);
  27127. if (dimName != null) {
  27128. return dimName;
  27129. }
  27130. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  27131. if (sourceDimDef) {
  27132. return sourceDimDef.name;
  27133. }
  27134. };
  27135. /**
  27136. * Get dimension index in data store. Return -1 if not found.
  27137. * Can be used to index value from getRawValue.
  27138. */
  27139. SeriesData.prototype.getDimensionIndex = function (dim) {
  27140. var dimIdx = this._recognizeDimIndex(dim);
  27141. if (dimIdx != null) {
  27142. return dimIdx;
  27143. }
  27144. if (dim == null) {
  27145. return -1;
  27146. }
  27147. var dimInfo = this._getDimInfo(dim);
  27148. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  27149. };
  27150. /**
  27151. * The meanings of the input parameter `dim`:
  27152. *
  27153. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  27154. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  27155. * + If dim is a number-like string (e.g., `"1"`):
  27156. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  27157. * it means that concrete name.
  27158. * + If not, it will be converted to a number, which means the index of the dimension.
  27159. * (why? because of the backward compatbility. We have been tolerating number-like string in
  27160. * dimension setting, although now it seems that it is not a good idea.)
  27161. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  27162. * if no dimension name is defined as `"1"`.
  27163. * + If dim is a not-number-like string, it means the concrete dim name.
  27164. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  27165. * or customized in `dimensions` property of option like `"age"`.
  27166. *
  27167. * @return recogonized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  27168. */
  27169. SeriesData.prototype._recognizeDimIndex = function (dim) {
  27170. if (isNumber(dim) // If being a number-like string but not being defined as a dimension name.
  27171. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  27172. return +dim;
  27173. }
  27174. };
  27175. SeriesData.prototype._getStoreDimIndex = function (dim) {
  27176. var dimIdx = this.getDimensionIndex(dim);
  27177. if ("development" !== 'production') {
  27178. if (dimIdx == null) {
  27179. throw new Error('Unkown dimension ' + dim);
  27180. }
  27181. }
  27182. return dimIdx;
  27183. };
  27184. /**
  27185. * Get type and calculation info of particular dimension
  27186. * @param dim
  27187. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  27188. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  27189. */
  27190. SeriesData.prototype.getDimensionInfo = function (dim) {
  27191. // Do not clone, because there may be categories in dimInfo.
  27192. return this._getDimInfo(this.getDimension(dim));
  27193. };
  27194. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  27195. var dimensionInfos = this._dimInfos;
  27196. this._getDimInfo = needsHasOwn ? function (dimName) {
  27197. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  27198. } : function (dimName) {
  27199. return dimensionInfos[dimName];
  27200. };
  27201. };
  27202. /**
  27203. * concrete dimension name list on coord.
  27204. */
  27205. SeriesData.prototype.getDimensionsOnCoord = function () {
  27206. return this._dimSummary.dataDimsOnCoord.slice();
  27207. };
  27208. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  27209. var dimensionsSummary = this._dimSummary;
  27210. if (idx == null) {
  27211. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  27212. }
  27213. var dims = dimensionsSummary.encode[coordDim];
  27214. return dims ? dims[idx] : null;
  27215. };
  27216. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  27217. var dimensionsSummary = this._dimSummary;
  27218. var dims = dimensionsSummary.encode[coordDim];
  27219. return (dims || []).slice();
  27220. };
  27221. SeriesData.prototype.getStore = function () {
  27222. return this._store;
  27223. };
  27224. /**
  27225. * Initialize from data
  27226. * @param data source or data or data store.
  27227. * @param nameList The name of a datum is used on data diff and
  27228. * default label/tooltip.
  27229. * A name can be specified in encode.itemName,
  27230. * or dataItem.name (only for series option data),
  27231. * or provided in nameList from outside.
  27232. */
  27233. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  27234. var _this = this;
  27235. var store;
  27236. if (data instanceof DataStore) {
  27237. store = data;
  27238. }
  27239. if (!store) {
  27240. var dimensions = this.dimensions;
  27241. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  27242. store = new DataStore();
  27243. var dimensionInfos = map$1(dimensions, function (dimName) {
  27244. return {
  27245. type: _this._dimInfos[dimName].type,
  27246. property: dimName
  27247. };
  27248. });
  27249. store.initData(provider, dimensionInfos, dimValueGetter);
  27250. }
  27251. this._store = store; // Reset
  27252. this._nameList = (nameList || []).slice();
  27253. this._idList = [];
  27254. this._nameRepeatCount = {};
  27255. this._doInit(0, store.count()); // Cache summary info for fast visit. See "dimensionHelper".
  27256. // Needs to be initialized after store is prepared.
  27257. this._dimSummary = summarizeDimensions(this, this._schema);
  27258. this.userOutput = this._dimSummary.userOutput;
  27259. };
  27260. /**
  27261. * Caution: Can be only called on raw data (before `this._indices` created).
  27262. */
  27263. SeriesData.prototype.appendData = function (data) {
  27264. var range = this._store.appendData(data);
  27265. this._doInit(range[0], range[1]);
  27266. };
  27267. /**
  27268. * Caution: Can be only called on raw data (before `this._indices` created).
  27269. * This method does not modify `rawData` (`dataProvider`), but only
  27270. * add values to store.
  27271. *
  27272. * The final count will be increased by `Math.max(values.length, names.length)`.
  27273. *
  27274. * @param values That is the SourceType: 'arrayRows', like
  27275. * [
  27276. * [12, 33, 44],
  27277. * [NaN, 43, 1],
  27278. * ['-', 'asdf', 0]
  27279. * ]
  27280. * Each item is exaclty cooresponding to a dimension.
  27281. */
  27282. SeriesData.prototype.appendValues = function (values, names) {
  27283. var _a = this._store.appendValues(values, names.length),
  27284. start = _a.start,
  27285. end = _a.end;
  27286. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  27287. this._updateOrdinalMeta();
  27288. if (names) {
  27289. for (var idx = start; idx < end; idx++) {
  27290. var sourceIdx = idx - start;
  27291. this._nameList[idx] = names[sourceIdx];
  27292. if (shouldMakeIdFromName) {
  27293. makeIdFromName(this, idx);
  27294. }
  27295. }
  27296. }
  27297. };
  27298. SeriesData.prototype._updateOrdinalMeta = function () {
  27299. var store = this._store;
  27300. var dimensions = this.dimensions;
  27301. for (var i = 0; i < dimensions.length; i++) {
  27302. var dimInfo = this._dimInfos[dimensions[i]];
  27303. if (dimInfo.ordinalMeta) {
  27304. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  27305. }
  27306. }
  27307. };
  27308. SeriesData.prototype._shouldMakeIdFromName = function () {
  27309. var provider = this._store.getProvider();
  27310. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  27311. };
  27312. SeriesData.prototype._doInit = function (start, end) {
  27313. if (start >= end) {
  27314. return;
  27315. }
  27316. var store = this._store;
  27317. var provider = store.getProvider();
  27318. this._updateOrdinalMeta();
  27319. var nameList = this._nameList;
  27320. var idList = this._idList;
  27321. var sourceFormat = provider.getSource().sourceFormat;
  27322. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL; // Each data item is value
  27323. // [1, 2]
  27324. // 2
  27325. // Bar chart, line chart which uses category axis
  27326. // only gives the 'y' value. 'x' value is the indices of category
  27327. // Use a tempValue to normalize the value to be a (x, y) value
  27328. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  27329. // This kind of ids and names are always stored `_nameList` and `_idList`.
  27330. if (isFormatOriginal && !provider.pure) {
  27331. var sharedDataItem = [];
  27332. for (var idx = start; idx < end; idx++) {
  27333. // NOTICE: Try not to write things into dataItem
  27334. var dataItem = provider.getItem(idx, sharedDataItem);
  27335. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  27336. this.hasItemOption = true;
  27337. }
  27338. if (dataItem) {
  27339. var itemName = dataItem.name;
  27340. if (nameList[idx] == null && itemName != null) {
  27341. nameList[idx] = convertOptionIdName(itemName, null);
  27342. }
  27343. var itemId = dataItem.id;
  27344. if (idList[idx] == null && itemId != null) {
  27345. idList[idx] = convertOptionIdName(itemId, null);
  27346. }
  27347. }
  27348. }
  27349. }
  27350. if (this._shouldMakeIdFromName()) {
  27351. for (var idx = start; idx < end; idx++) {
  27352. makeIdFromName(this, idx);
  27353. }
  27354. }
  27355. prepareInvertedIndex(this);
  27356. };
  27357. /**
  27358. * PENDING: In fact currently this function is only used to short-circuit
  27359. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  27360. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  27361. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  27362. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  27363. * But if we add "custom data filter" in future, which is not "axis related", this method may
  27364. * be still needed.
  27365. *
  27366. * Optimize for the scenario that data is filtered by a given extent.
  27367. * Consider that if data amount is more than hundreds of thousand,
  27368. * extent calculation will cost more than 10ms and the cache will
  27369. * be erased because of the filtering.
  27370. */
  27371. SeriesData.prototype.getApproximateExtent = function (dim) {
  27372. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  27373. };
  27374. /**
  27375. * Calculate extent on a filtered data might be time consuming.
  27376. * Approximate extent is only used for: calculte extent of filtered data outside.
  27377. */
  27378. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  27379. dim = this.getDimension(dim);
  27380. this._approximateExtent[dim] = extent.slice();
  27381. };
  27382. SeriesData.prototype.getCalculationInfo = function (key) {
  27383. return this._calculationInfo[key];
  27384. };
  27385. SeriesData.prototype.setCalculationInfo = function (key, value) {
  27386. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  27387. };
  27388. /**
  27389. * @return Never be null/undefined. `number` will be converted to string. Becuase:
  27390. * In most cases, name is used in display, where returning a string is more convenient.
  27391. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  27392. * rule that name `2` equals to name `'2'`.
  27393. */
  27394. SeriesData.prototype.getName = function (idx) {
  27395. var rawIndex = this.getRawIndex(idx);
  27396. var name = this._nameList[rawIndex];
  27397. if (name == null && this._nameDimIdx != null) {
  27398. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  27399. }
  27400. if (name == null) {
  27401. name = '';
  27402. }
  27403. return name;
  27404. };
  27405. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  27406. var ordinal = this._store.get(dimIdx, idx);
  27407. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  27408. if (ordinalMeta) {
  27409. return ordinalMeta.categories[ordinal];
  27410. }
  27411. return ordinal;
  27412. };
  27413. /**
  27414. * @return Never null/undefined. `number` will be converted to string. Becuase:
  27415. * In all cases having encountered at present, id is used in making diff comparison, which
  27416. * are usually based on hash map. We can keep the rule that the internal id are always string
  27417. * (treat `2` is the same as `'2'`) to make the related logic simple.
  27418. */
  27419. SeriesData.prototype.getId = function (idx) {
  27420. return getId(this, this.getRawIndex(idx));
  27421. };
  27422. SeriesData.prototype.count = function () {
  27423. return this._store.count();
  27424. };
  27425. /**
  27426. * Get value. Return NaN if idx is out of range.
  27427. *
  27428. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  27429. */
  27430. SeriesData.prototype.get = function (dim, idx) {
  27431. var store = this._store;
  27432. var dimInfo = this._dimInfos[dim];
  27433. if (dimInfo) {
  27434. return store.get(dimInfo.storeDimIndex, idx);
  27435. }
  27436. };
  27437. /**
  27438. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  27439. */
  27440. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  27441. var store = this._store;
  27442. var dimInfo = this._dimInfos[dim];
  27443. if (dimInfo) {
  27444. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  27445. }
  27446. };
  27447. SeriesData.prototype.getIndices = function () {
  27448. return this._store.getIndices();
  27449. };
  27450. SeriesData.prototype.getDataExtent = function (dim) {
  27451. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  27452. };
  27453. SeriesData.prototype.getSum = function (dim) {
  27454. return this._store.getSum(this._getStoreDimIndex(dim));
  27455. };
  27456. SeriesData.prototype.getMedian = function (dim) {
  27457. return this._store.getMedian(this._getStoreDimIndex(dim));
  27458. };
  27459. SeriesData.prototype.getValues = function (dimensions, idx) {
  27460. var _this = this;
  27461. var store = this._store;
  27462. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  27463. return _this._getStoreDimIndex(dim);
  27464. }), idx) : store.getValues(dimensions);
  27465. };
  27466. /**
  27467. * If value is NaN. Inlcuding '-'
  27468. * Only check the coord dimensions.
  27469. */
  27470. SeriesData.prototype.hasValue = function (idx) {
  27471. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  27472. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  27473. // Ordinal type originally can be string or number.
  27474. // But when an ordinal type is used on coord, it can
  27475. // not be string but only number. So we can also use isNaN.
  27476. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  27477. return false;
  27478. }
  27479. }
  27480. return true;
  27481. };
  27482. /**
  27483. * Retreive the index with given name
  27484. */
  27485. SeriesData.prototype.indexOfName = function (name) {
  27486. for (var i = 0, len = this._store.count(); i < len; i++) {
  27487. if (this.getName(i) === name) {
  27488. return i;
  27489. }
  27490. }
  27491. return -1;
  27492. };
  27493. SeriesData.prototype.getRawIndex = function (idx) {
  27494. return this._store.getRawIndex(idx);
  27495. };
  27496. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  27497. return this._store.indexOfRawIndex(rawIndex);
  27498. };
  27499. /**
  27500. * Only support the dimension which inverted index created.
  27501. * Do not support other cases until required.
  27502. * @param dim concrete dim
  27503. * @param value ordinal index
  27504. * @return rawIndex
  27505. */
  27506. SeriesData.prototype.rawIndexOf = function (dim, value) {
  27507. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27508. if ("development" !== 'production') {
  27509. if (!invertedIndices) {
  27510. throw new Error('Do not supported yet');
  27511. }
  27512. }
  27513. var rawIndex = invertedIndices[value];
  27514. if (rawIndex == null || isNaN(rawIndex)) {
  27515. return INDEX_NOT_FOUND;
  27516. }
  27517. return rawIndex;
  27518. };
  27519. /**
  27520. * Retreive the index of nearest value
  27521. * @param dim
  27522. * @param value
  27523. * @param [maxDistance=Infinity]
  27524. * @return If and only if multiple indices has
  27525. * the same value, they are put to the result.
  27526. */
  27527. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  27528. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  27529. };
  27530. SeriesData.prototype.each = function (dims, cb, ctx) {
  27531. if (isFunction(dims)) {
  27532. ctx = cb;
  27533. cb = dims;
  27534. dims = [];
  27535. } // ctxCompat just for compat echarts3
  27536. var fCtx = ctx || this;
  27537. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  27538. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  27539. };
  27540. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  27541. if (isFunction(dims)) {
  27542. ctx = cb;
  27543. cb = dims;
  27544. dims = [];
  27545. } // ctxCompat just for compat echarts3
  27546. var fCtx = ctx || this;
  27547. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  27548. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  27549. return this;
  27550. };
  27551. /**
  27552. * Select data in range. (For optimization of filter)
  27553. * (Manually inline code, support 5 million data filtering in data zoom.)
  27554. */
  27555. SeriesData.prototype.selectRange = function (range) {
  27556. var _this = this;
  27557. var innerRange = {};
  27558. var dims = keys(range);
  27559. each(dims, function (dim) {
  27560. var dimIdx = _this._getStoreDimIndex(dim);
  27561. innerRange[dimIdx] = range[dim];
  27562. });
  27563. this._store = this._store.selectRange(innerRange);
  27564. return this;
  27565. };
  27566. /* eslint-enable max-len */
  27567. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  27568. if (isFunction(dims)) {
  27569. ctx = cb;
  27570. cb = dims;
  27571. dims = [];
  27572. } // ctxCompat just for compat echarts3
  27573. ctx = ctx || this;
  27574. var result = [];
  27575. this.each(dims, function () {
  27576. result.push(cb && cb.apply(this, arguments));
  27577. }, ctx);
  27578. return result;
  27579. };
  27580. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  27581. var fCtx = ctx || ctxCompat || this;
  27582. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  27583. var list = cloneListForMapAndSample(this);
  27584. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  27585. return list;
  27586. };
  27587. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  27588. var _this = this; // ctxCompat just for compat echarts3
  27589. var fCtx = ctx || ctxCompat || this;
  27590. if ("development" !== 'production') {
  27591. each(normalizeDimensions(dims), function (dim) {
  27592. var dimInfo = _this.getDimensionInfo(dim);
  27593. if (!dimInfo.isCalculationCoord) {
  27594. console.error('Danger: only stack dimension can be modified');
  27595. }
  27596. });
  27597. }
  27598. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this); // If do shallow clone here, if there are too many stacked series,
  27599. // it still cost lots of memory, becuase `_store.dimensions` are not shared.
  27600. // We should consider there probably be shallow clone happen in each sereis
  27601. // in consequent filter/map.
  27602. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  27603. };
  27604. /**
  27605. * Large data down sampling on given dimension
  27606. * @param sampleIndex Sample index for name and id
  27607. */
  27608. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27609. var list = cloneListForMapAndSample(this);
  27610. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  27611. return list;
  27612. };
  27613. /**
  27614. * Large data down sampling using largest-triangle-three-buckets
  27615. * @param {string} valueDimension
  27616. * @param {number} targetCount
  27617. */
  27618. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  27619. var list = cloneListForMapAndSample(this);
  27620. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  27621. return list;
  27622. };
  27623. SeriesData.prototype.getRawDataItem = function (idx) {
  27624. return this._store.getRawDataItem(idx);
  27625. };
  27626. /**
  27627. * Get model of one data item.
  27628. */
  27629. // TODO: Type of data item
  27630. SeriesData.prototype.getItemModel = function (idx) {
  27631. var hostModel = this.hostModel;
  27632. var dataItem = this.getRawDataItem(idx);
  27633. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  27634. };
  27635. /**
  27636. * Create a data differ
  27637. */
  27638. SeriesData.prototype.diff = function (otherList) {
  27639. var thisList = this;
  27640. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  27641. return getId(otherList, idx);
  27642. }, function (idx) {
  27643. return getId(thisList, idx);
  27644. });
  27645. };
  27646. /**
  27647. * Get visual property.
  27648. */
  27649. SeriesData.prototype.getVisual = function (key) {
  27650. var visual = this._visual;
  27651. return visual && visual[key];
  27652. };
  27653. SeriesData.prototype.setVisual = function (kvObj, val) {
  27654. this._visual = this._visual || {};
  27655. if (isObject$2(kvObj)) {
  27656. extend(this._visual, kvObj);
  27657. } else {
  27658. this._visual[kvObj] = val;
  27659. }
  27660. };
  27661. /**
  27662. * Get visual property of single data item
  27663. */
  27664. // eslint-disable-next-line
  27665. SeriesData.prototype.getItemVisual = function (idx, key) {
  27666. var itemVisual = this._itemVisuals[idx];
  27667. var val = itemVisual && itemVisual[key];
  27668. if (val == null) {
  27669. // Use global visual property
  27670. return this.getVisual(key);
  27671. }
  27672. return val;
  27673. };
  27674. /**
  27675. * If exists visual property of single data item
  27676. */
  27677. SeriesData.prototype.hasItemVisual = function () {
  27678. return this._itemVisuals.length > 0;
  27679. };
  27680. /**
  27681. * Make sure itemVisual property is unique
  27682. */
  27683. // TODO: use key to save visual to reduce memory.
  27684. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  27685. var itemVisuals = this._itemVisuals;
  27686. var itemVisual = itemVisuals[idx];
  27687. if (!itemVisual) {
  27688. itemVisual = itemVisuals[idx] = {};
  27689. }
  27690. var val = itemVisual[key];
  27691. if (val == null) {
  27692. val = this.getVisual(key); // TODO Performance?
  27693. if (isArray(val)) {
  27694. val = val.slice();
  27695. } else if (isObject$2(val)) {
  27696. val = extend({}, val);
  27697. }
  27698. itemVisual[key] = val;
  27699. }
  27700. return val;
  27701. }; // eslint-disable-next-line
  27702. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  27703. var itemVisual = this._itemVisuals[idx] || {};
  27704. this._itemVisuals[idx] = itemVisual;
  27705. if (isObject$2(key)) {
  27706. extend(itemVisual, key);
  27707. } else {
  27708. itemVisual[key] = value;
  27709. }
  27710. };
  27711. /**
  27712. * Clear itemVisuals and list visual.
  27713. */
  27714. SeriesData.prototype.clearAllVisual = function () {
  27715. this._visual = {};
  27716. this._itemVisuals = [];
  27717. };
  27718. SeriesData.prototype.setLayout = function (key, val) {
  27719. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  27720. };
  27721. /**
  27722. * Get layout property.
  27723. */
  27724. SeriesData.prototype.getLayout = function (key) {
  27725. return this._layout[key];
  27726. };
  27727. /**
  27728. * Get layout of single data item
  27729. */
  27730. SeriesData.prototype.getItemLayout = function (idx) {
  27731. return this._itemLayouts[idx];
  27732. };
  27733. /**
  27734. * Set layout of single data item
  27735. */
  27736. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  27737. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  27738. };
  27739. /**
  27740. * Clear all layout of single data item
  27741. */
  27742. SeriesData.prototype.clearItemLayouts = function () {
  27743. this._itemLayouts.length = 0;
  27744. };
  27745. /**
  27746. * Set graphic element relative to data. It can be set as null
  27747. */
  27748. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  27749. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  27750. setCommonECData(seriesIndex, this.dataType, idx, el);
  27751. this._graphicEls[idx] = el;
  27752. };
  27753. SeriesData.prototype.getItemGraphicEl = function (idx) {
  27754. return this._graphicEls[idx];
  27755. };
  27756. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  27757. each(this._graphicEls, function (el, idx) {
  27758. if (el) {
  27759. cb && cb.call(context, el, idx);
  27760. }
  27761. });
  27762. };
  27763. /**
  27764. * Shallow clone a new list except visual and layout properties, and graph elements.
  27765. * New list only change the indices.
  27766. */
  27767. SeriesData.prototype.cloneShallow = function (list) {
  27768. if (!list) {
  27769. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  27770. }
  27771. transferProperties(list, this);
  27772. list._store = this._store;
  27773. return list;
  27774. };
  27775. /**
  27776. * Wrap some method to add more feature
  27777. */
  27778. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  27779. var originalMethod = this[methodName];
  27780. if (!isFunction(originalMethod)) {
  27781. return;
  27782. }
  27783. this.__wrappedMethods = this.__wrappedMethods || [];
  27784. this.__wrappedMethods.push(methodName);
  27785. this[methodName] = function () {
  27786. var res = originalMethod.apply(this, arguments);
  27787. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27788. };
  27789. }; // ----------------------------------------------------------
  27790. // A work around for internal method visiting private member.
  27791. // ----------------------------------------------------------
  27792. SeriesData.internalField = function () {
  27793. prepareInvertedIndex = function (data) {
  27794. var invertedIndicesMap = data._invertedIndicesMap;
  27795. each(invertedIndicesMap, function (invertedIndices, dim) {
  27796. var dimInfo = data._dimInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27797. var ordinalMeta = dimInfo.ordinalMeta;
  27798. var store = data._store;
  27799. if (ordinalMeta) {
  27800. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  27801. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27802. for (var i = 0; i < invertedIndices.length; i++) {
  27803. invertedIndices[i] = INDEX_NOT_FOUND;
  27804. }
  27805. for (var i = 0; i < store.count(); i++) {
  27806. // Only support the case that all values are distinct.
  27807. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  27808. }
  27809. }
  27810. });
  27811. };
  27812. getIdNameFromStore = function (data, dimIdx, idx) {
  27813. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  27814. };
  27815. /**
  27816. * @see the comment of `List['getId']`.
  27817. */
  27818. getId = function (data, rawIndex) {
  27819. var id = data._idList[rawIndex];
  27820. if (id == null && data._idDimIdx != null) {
  27821. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  27822. }
  27823. if (id == null) {
  27824. id = ID_PREFIX + rawIndex;
  27825. }
  27826. return id;
  27827. };
  27828. normalizeDimensions = function (dimensions) {
  27829. if (!isArray(dimensions)) {
  27830. dimensions = dimensions != null ? [dimensions] : [];
  27831. }
  27832. return dimensions;
  27833. };
  27834. /**
  27835. * Data in excludeDimensions is copied, otherwise transfered.
  27836. */
  27837. cloneListForMapAndSample = function (original) {
  27838. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  27839. transferProperties(list, original);
  27840. return list;
  27841. };
  27842. transferProperties = function (target, source) {
  27843. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  27844. if (source.hasOwnProperty(propName)) {
  27845. target[propName] = source[propName];
  27846. }
  27847. });
  27848. target.__wrappedMethods = source.__wrappedMethods;
  27849. each(CLONE_PROPERTIES, function (propName) {
  27850. target[propName] = clone(source[propName]);
  27851. });
  27852. target._calculationInfo = extend({}, source._calculationInfo);
  27853. };
  27854. makeIdFromName = function (data, idx) {
  27855. var nameList = data._nameList;
  27856. var idList = data._idList;
  27857. var nameDimIdx = data._nameDimIdx;
  27858. var idDimIdx = data._idDimIdx;
  27859. var name = nameList[idx];
  27860. var id = idList[idx];
  27861. if (name == null && nameDimIdx != null) {
  27862. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  27863. }
  27864. if (id == null && idDimIdx != null) {
  27865. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  27866. }
  27867. if (id == null && name != null) {
  27868. var nameRepeatCount = data._nameRepeatCount;
  27869. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  27870. id = name;
  27871. if (nmCnt > 1) {
  27872. id += '__ec__' + nmCnt;
  27873. }
  27874. idList[idx] = id;
  27875. }
  27876. };
  27877. }();
  27878. return SeriesData;
  27879. }();
  27880. /**
  27881. * For outside usage compat (like echarts-gl are using it).
  27882. */
  27883. function createDimensions(source, opt) {
  27884. return prepareSeriesDataSchema(source, opt).dimensions;
  27885. }
  27886. /**
  27887. * This method builds the relationship between:
  27888. * + "what the coord sys or series requires (see `coordDimensions`)",
  27889. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  27890. * + "what the data source provids (see `source`)".
  27891. *
  27892. * Some guess strategy will be adapted if user does not define something.
  27893. * If no 'value' dimension specified, the first no-named dimension will be
  27894. * named as 'value'.
  27895. *
  27896. * @return The results are always sorted by `storeDimIndex` asc.
  27897. */
  27898. function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type
  27899. source, opt) {
  27900. if (!isSourceInstance(source)) {
  27901. source = createSourceFromSeriesDataOption(source);
  27902. }
  27903. opt = opt || {};
  27904. var sysDims = opt.coordDimensions || [];
  27905. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  27906. var coordDimNameMap = createHashMap();
  27907. var resultList = [];
  27908. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unsed dimensions if sharing a high dimension datastore
  27909. // 30 is an experience value.
  27910. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  27911. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  27912. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  27913. var encodeDef = opt.encodeDefine;
  27914. if (!encodeDef && opt.encodeDefaulter) {
  27915. encodeDef = opt.encodeDefaulter(source, dimCount);
  27916. }
  27917. var encodeDefMap = createHashMap(encodeDef);
  27918. var indicesMap = new CtorInt32Array(dimCount);
  27919. for (var i = 0; i < indicesMap.length; i++) {
  27920. indicesMap[i] = -1;
  27921. }
  27922. function getResultItem(dimIdx) {
  27923. var idx = indicesMap[dimIdx];
  27924. if (idx < 0) {
  27925. var dimDefItemRaw = dimsDef[dimIdx];
  27926. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  27927. name: dimDefItemRaw
  27928. };
  27929. var resultItem = new SeriesDimensionDefine();
  27930. var userDimName = dimDefItem.name;
  27931. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  27932. // Only if `series.dimensions` is defined in option
  27933. // displayName, will be set, and dimension will be diplayed vertically in
  27934. // tooltip by default.
  27935. resultItem.name = resultItem.displayName = userDimName;
  27936. }
  27937. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27938. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27939. var newIdx = resultList.length;
  27940. indicesMap[dimIdx] = newIdx;
  27941. resultItem.storeDimIndex = dimIdx;
  27942. resultList.push(resultItem);
  27943. return resultItem;
  27944. }
  27945. return resultList[idx];
  27946. }
  27947. if (!omitUnusedDimensions) {
  27948. for (var i = 0; i < dimCount; i++) {
  27949. getResultItem(i);
  27950. }
  27951. } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  27952. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  27953. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27954. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27955. // this case.
  27956. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  27957. encodeDefMap.set(coordDim, false);
  27958. return;
  27959. }
  27960. var validDataDims = encodeDefMap.set(coordDim, []);
  27961. each(dataDims, function (resultDimIdxOrName, idx) {
  27962. // The input resultDimIdx can be dim name or index.
  27963. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  27964. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27965. validDataDims[idx] = resultDimIdx;
  27966. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  27967. }
  27968. });
  27969. }); // Apply templetes and default order from `sysDims`.
  27970. var availDimIdx = 0;
  27971. each(sysDims, function (sysDimItemRaw) {
  27972. var coordDim;
  27973. var sysDimItemDimsDef;
  27974. var sysDimItemOtherDims;
  27975. var sysDimItem;
  27976. if (isString(sysDimItemRaw)) {
  27977. coordDim = sysDimItemRaw;
  27978. sysDimItem = {};
  27979. } else {
  27980. sysDimItem = sysDimItemRaw;
  27981. coordDim = sysDimItem.name;
  27982. var ordinalMeta = sysDimItem.ordinalMeta;
  27983. sysDimItem.ordinalMeta = null;
  27984. sysDimItem = extend({}, sysDimItem);
  27985. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  27986. sysDimItemDimsDef = sysDimItem.dimsDef;
  27987. sysDimItemOtherDims = sysDimItem.otherDims;
  27988. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27989. }
  27990. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  27991. if (dataDims === false) {
  27992. return;
  27993. }
  27994. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  27995. if (!dataDims.length) {
  27996. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27997. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  27998. availDimIdx++;
  27999. }
  28000. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  28001. }
  28002. } // Apply templates.
  28003. each(dataDims, function (resultDimIdx, coordDimIndex) {
  28004. var resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source.
  28005. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  28006. resultItem.type = sysDimItem.type;
  28007. }
  28008. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28009. if (resultItem.name == null && sysDimItemDimsDef) {
  28010. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28011. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  28012. name: sysDimItemDimsDefItem
  28013. });
  28014. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28015. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28016. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28017. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28018. });
  28019. });
  28020. function applyDim(resultItem, coordDim, coordDimIndex) {
  28021. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  28022. resultItem.otherDims[coordDim] = coordDimIndex;
  28023. } else {
  28024. resultItem.coordDim = coordDim;
  28025. resultItem.coordDimIndex = coordDimIndex;
  28026. coordDimNameMap.set(coordDim, true);
  28027. }
  28028. } // Make sure the first extra dim is 'value'.
  28029. var generateCoord = opt.generateCoord;
  28030. var generateCoordCount = opt.generateCoordCount;
  28031. var fromZero = generateCoordCount != null;
  28032. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  28033. var extra = generateCoord || 'value';
  28034. function ifNoNameFillWithCoordName(resultItem) {
  28035. if (resultItem.name == null) {
  28036. // Duplication will be removed in the next step.
  28037. resultItem.name = resultItem.coordDim;
  28038. }
  28039. } // Set dim `name` and other `coordDim` and other props.
  28040. if (!omitUnusedDimensions) {
  28041. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28042. var resultItem = getResultItem(resultDimIdx);
  28043. var coordDim = resultItem.coordDim;
  28044. if (coordDim == null) {
  28045. // TODO no need to generate coordDim for isExtraCoord?
  28046. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  28047. resultItem.coordDimIndex = 0; // Series specified generateCoord is using out.
  28048. if (!generateCoord || generateCoordCount <= 0) {
  28049. resultItem.isExtraCoord = true;
  28050. }
  28051. generateCoordCount--;
  28052. }
  28053. ifNoNameFillWithCoordName(resultItem);
  28054. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  28055. // {
  28056. // dataset: {source: [
  28057. // ['2001', 123],
  28058. // ['2002', 456],
  28059. // ...
  28060. // ['The others', 987],
  28061. // ]},
  28062. // series: {type: 'pie'}
  28063. // }
  28064. // The first colum should better be treated as a "ordinal" although it
  28065. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28066. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  28067. resultItem.type = 'ordinal';
  28068. }
  28069. }
  28070. } else {
  28071. each(resultList, function (resultItem) {
  28072. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  28073. ifNoNameFillWithCoordName(resultItem);
  28074. }); // Sort dimensions: there are some rule that use the last dim as label,
  28075. // and for some latter travel process easier.
  28076. resultList.sort(function (item0, item1) {
  28077. return item0.storeDimIndex - item1.storeDimIndex;
  28078. });
  28079. }
  28080. removeDuplication(resultList);
  28081. return new SeriesDataSchema({
  28082. source: source,
  28083. dimensions: resultList,
  28084. fullDimensionCount: dimCount,
  28085. dimensionOmitted: omitUnusedDimensions
  28086. });
  28087. }
  28088. function removeDuplication(result) {
  28089. var duplicationMap = createHashMap();
  28090. for (var i = 0; i < result.length; i++) {
  28091. var dim = result[i];
  28092. var dimOriginalName = dim.name;
  28093. var count = duplicationMap.get(dimOriginalName) || 0;
  28094. if (count > 0) {
  28095. // Starts from 0.
  28096. dim.name = dimOriginalName + (count - 1);
  28097. }
  28098. count++;
  28099. duplicationMap.set(dimOriginalName, count);
  28100. }
  28101. } // ??? TODO
  28102. // Originally detect dimCount by data[0]. Should we
  28103. // optimize it to only by sysDims and dimensions and encode.
  28104. // So only necessary dims will be initialized.
  28105. // But
  28106. // (1) custom series should be considered. where other dims
  28107. // may be visited.
  28108. // (2) sometimes user need to calcualte bubble size or use visualMap
  28109. // on other dimensions besides coordSys needed.
  28110. // So, dims that is not used by system, should be shared in data store?
  28111. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28112. // Note that the result dimCount should not small than columns count
  28113. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28114. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  28115. each(sysDims, function (sysDimItem) {
  28116. var sysDimItemDimsDef;
  28117. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  28118. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  28119. }
  28120. });
  28121. return dimCount;
  28122. }
  28123. function genCoordDimName(name, map, fromZero) {
  28124. var mapData = map.data;
  28125. if (fromZero || mapData.hasOwnProperty(name)) {
  28126. var i = 0;
  28127. while (mapData.hasOwnProperty(name + i)) {
  28128. i++;
  28129. }
  28130. name += i;
  28131. }
  28132. map.set(name, true);
  28133. return name;
  28134. }
  28135. /**
  28136. * @class
  28137. * For example:
  28138. * {
  28139. * coordSysName: 'cartesian2d',
  28140. * coordSysDims: ['x', 'y', ...],
  28141. * axisMap: HashMap({
  28142. * x: xAxisModel,
  28143. * y: yAxisModel
  28144. * }),
  28145. * categoryAxisMap: HashMap({
  28146. * x: xAxisModel,
  28147. * y: undefined
  28148. * }),
  28149. * // The index of the first category axis in `coordSysDims`.
  28150. * // `null/undefined` means no category axis exists.
  28151. * firstCategoryDimIndex: 1,
  28152. * // To replace user specified encode.
  28153. * }
  28154. */
  28155. var CoordSysInfo =
  28156. /** @class */
  28157. function () {
  28158. function CoordSysInfo(coordSysName) {
  28159. this.coordSysDims = [];
  28160. this.axisMap = createHashMap();
  28161. this.categoryAxisMap = createHashMap();
  28162. this.coordSysName = coordSysName;
  28163. }
  28164. return CoordSysInfo;
  28165. }();
  28166. function getCoordSysInfoBySeries(seriesModel) {
  28167. var coordSysName = seriesModel.get('coordinateSystem');
  28168. var result = new CoordSysInfo(coordSysName);
  28169. var fetch = fetchers[coordSysName];
  28170. if (fetch) {
  28171. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28172. return result;
  28173. }
  28174. }
  28175. var fetchers = {
  28176. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28177. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  28178. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  28179. if ("development" !== 'production') {
  28180. if (!xAxisModel) {
  28181. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  28182. }
  28183. if (!yAxisModel) {
  28184. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  28185. }
  28186. }
  28187. result.coordSysDims = ['x', 'y'];
  28188. axisMap.set('x', xAxisModel);
  28189. axisMap.set('y', yAxisModel);
  28190. if (isCategory(xAxisModel)) {
  28191. categoryAxisMap.set('x', xAxisModel);
  28192. result.firstCategoryDimIndex = 0;
  28193. }
  28194. if (isCategory(yAxisModel)) {
  28195. categoryAxisMap.set('y', yAxisModel);
  28196. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28197. }
  28198. },
  28199. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28200. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  28201. if ("development" !== 'production') {
  28202. if (!singleAxisModel) {
  28203. throw new Error('singleAxis should be specified.');
  28204. }
  28205. }
  28206. result.coordSysDims = ['single'];
  28207. axisMap.set('single', singleAxisModel);
  28208. if (isCategory(singleAxisModel)) {
  28209. categoryAxisMap.set('single', singleAxisModel);
  28210. result.firstCategoryDimIndex = 0;
  28211. }
  28212. },
  28213. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28214. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  28215. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28216. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28217. if ("development" !== 'production') {
  28218. if (!angleAxisModel) {
  28219. throw new Error('angleAxis option not found');
  28220. }
  28221. if (!radiusAxisModel) {
  28222. throw new Error('radiusAxis option not found');
  28223. }
  28224. }
  28225. result.coordSysDims = ['radius', 'angle'];
  28226. axisMap.set('radius', radiusAxisModel);
  28227. axisMap.set('angle', angleAxisModel);
  28228. if (isCategory(radiusAxisModel)) {
  28229. categoryAxisMap.set('radius', radiusAxisModel);
  28230. result.firstCategoryDimIndex = 0;
  28231. }
  28232. if (isCategory(angleAxisModel)) {
  28233. categoryAxisMap.set('angle', angleAxisModel);
  28234. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28235. }
  28236. },
  28237. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28238. result.coordSysDims = ['lng', 'lat'];
  28239. },
  28240. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28241. var ecModel = seriesModel.ecModel;
  28242. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  28243. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28244. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28245. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28246. var axisDim = coordSysDims[index];
  28247. axisMap.set(axisDim, axisModel);
  28248. if (isCategory(axisModel)) {
  28249. categoryAxisMap.set(axisDim, axisModel);
  28250. if (result.firstCategoryDimIndex == null) {
  28251. result.firstCategoryDimIndex = index;
  28252. }
  28253. }
  28254. });
  28255. }
  28256. };
  28257. function isCategory(axisModel) {
  28258. return axisModel.get('type') === 'category';
  28259. }
  28260. /**
  28261. * Note that it is too complicated to support 3d stack by value
  28262. * (have to create two-dimension inverted index), so in 3d case
  28263. * we just support that stacked by index.
  28264. *
  28265. * @param seriesModel
  28266. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  28267. * The input will be modified.
  28268. * @param opt
  28269. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  28270. * @param opt.byIndex=false
  28271. * @return calculationInfo
  28272. * {
  28273. * stackedDimension: string
  28274. * stackedByDimension: string
  28275. * isStackedByIndex: boolean
  28276. * stackedOverDimension: string
  28277. * stackResultDimension: string
  28278. * }
  28279. */
  28280. function enableDataStack(seriesModel, dimensionsInput, opt) {
  28281. opt = opt || {};
  28282. var byIndex = opt.byIndex;
  28283. var stackedCoordDimension = opt.stackedCoordDimension;
  28284. var dimensionDefineList;
  28285. var schema;
  28286. var store;
  28287. if (isLegacyDimensionsInput(dimensionsInput)) {
  28288. dimensionDefineList = dimensionsInput;
  28289. } else {
  28290. schema = dimensionsInput.schema;
  28291. dimensionDefineList = schema.dimensions;
  28292. store = dimensionsInput.store;
  28293. } // Compatibal: when `stack` is set as '', do not stack.
  28294. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28295. var stackedByDimInfo;
  28296. var stackedDimInfo;
  28297. var stackResultDimension;
  28298. var stackedOverDimension;
  28299. each(dimensionDefineList, function (dimensionInfo, index) {
  28300. if (isString(dimensionInfo)) {
  28301. dimensionDefineList[index] = dimensionInfo = {
  28302. name: dimensionInfo
  28303. };
  28304. }
  28305. if (mayStack && !dimensionInfo.isExtraCoord) {
  28306. // Find the first ordinal dimension as the stackedByDimInfo.
  28307. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28308. stackedByDimInfo = dimensionInfo;
  28309. } // Find the first stackable dimension as the stackedDimInfo.
  28310. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  28311. stackedDimInfo = dimensionInfo;
  28312. }
  28313. }
  28314. });
  28315. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28316. // Compatible with previous design, value axis (time axis) only stack by index.
  28317. // It may make sense if the user provides elaborately constructed data.
  28318. byIndex = true;
  28319. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28320. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28321. // might not be a good way.
  28322. if (stackedDimInfo) {
  28323. // Use a weird name that not duplicated with other names.
  28324. // Also need to use seriesModel.id as postfix because different
  28325. // series may share same data store. The stack dimension needs to be distinguished.
  28326. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  28327. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id; // Create inverted index to fast query index by value.
  28328. if (stackedByDimInfo) {
  28329. stackedByDimInfo.createInvertedIndices = true;
  28330. }
  28331. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  28332. var stackedDimType = stackedDimInfo.type;
  28333. var stackedDimCoordIndex_1 = 0;
  28334. each(dimensionDefineList, function (dimensionInfo) {
  28335. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  28336. stackedDimCoordIndex_1++;
  28337. }
  28338. });
  28339. var stackedOverDimensionDefine = {
  28340. name: stackResultDimension,
  28341. coordDim: stackedDimCoordDim_1,
  28342. coordDimIndex: stackedDimCoordIndex_1,
  28343. type: stackedDimType,
  28344. isExtraCoord: true,
  28345. isCalculationCoord: true,
  28346. storeDimIndex: dimensionDefineList.length
  28347. };
  28348. var stackResultDimensionDefine = {
  28349. name: stackedOverDimension,
  28350. // This dimension contains stack base (generally, 0), so do not set it as
  28351. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28352. coordDim: stackedOverDimension,
  28353. coordDimIndex: stackedDimCoordIndex_1 + 1,
  28354. type: stackedDimType,
  28355. isExtraCoord: true,
  28356. isCalculationCoord: true,
  28357. storeDimIndex: dimensionDefineList.length + 1
  28358. };
  28359. if (schema) {
  28360. if (store) {
  28361. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  28362. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  28363. }
  28364. schema.appendCalculationDimension(stackedOverDimensionDefine);
  28365. schema.appendCalculationDimension(stackResultDimensionDefine);
  28366. } else {
  28367. dimensionDefineList.push(stackedOverDimensionDefine);
  28368. dimensionDefineList.push(stackResultDimensionDefine);
  28369. }
  28370. }
  28371. return {
  28372. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28373. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28374. isStackedByIndex: byIndex,
  28375. stackedOverDimension: stackedOverDimension,
  28376. stackResultDimension: stackResultDimension
  28377. };
  28378. }
  28379. function isLegacyDimensionsInput(dimensionsInput) {
  28380. return !isSeriesDataSchema(dimensionsInput.schema);
  28381. }
  28382. function isDimensionStacked(data, stackedDim) {
  28383. // Each single series only maps to one pair of axis. So we do not need to
  28384. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28385. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28386. }
  28387. function getStackedDimension(data, targetDim) {
  28388. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  28389. }
  28390. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  28391. var coordSysName = seriesModel.get('coordinateSystem');
  28392. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28393. var coordSysDimDefs;
  28394. if (coordSysInfo && coordSysInfo.coordSysDims) {
  28395. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28396. var dimInfo = {
  28397. name: dim
  28398. };
  28399. var axisModel = coordSysInfo.axisMap.get(dim);
  28400. if (axisModel) {
  28401. var axisType = axisModel.get('type');
  28402. dimInfo.type = getDimensionTypeByAxis(axisType);
  28403. }
  28404. return dimInfo;
  28405. });
  28406. }
  28407. if (!coordSysDimDefs) {
  28408. // Get dimensions from registered coordinate system
  28409. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  28410. }
  28411. return coordSysDimDefs;
  28412. }
  28413. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  28414. var firstCategoryDimIndex;
  28415. var hasNameEncode;
  28416. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  28417. var coordDim = dimInfo.coordDim;
  28418. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  28419. if (categoryAxisModel) {
  28420. if (firstCategoryDimIndex == null) {
  28421. firstCategoryDimIndex = dimIndex;
  28422. }
  28423. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  28424. if (createInvertedIndices) {
  28425. dimInfo.createInvertedIndices = true;
  28426. }
  28427. }
  28428. if (dimInfo.otherDims.itemName != null) {
  28429. hasNameEncode = true;
  28430. }
  28431. });
  28432. if (!hasNameEncode && firstCategoryDimIndex != null) {
  28433. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  28434. }
  28435. return firstCategoryDimIndex;
  28436. }
  28437. /**
  28438. * Caution: there are side effects to `sourceManager` in this method.
  28439. * Should better only be called in `Series['getInitialData']`.
  28440. */
  28441. function createSeriesData(sourceRaw, seriesModel, opt) {
  28442. opt = opt || {};
  28443. var sourceManager = seriesModel.getSourceManager();
  28444. var source;
  28445. var isOriginalSource = false;
  28446. if (sourceRaw) {
  28447. isOriginalSource = true;
  28448. source = createSourceFromSeriesDataOption(sourceRaw);
  28449. } else {
  28450. source = sourceManager.getSource(); // Is series.data. not dataset.
  28451. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  28452. }
  28453. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28454. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  28455. var useEncodeDefaulter = opt.useEncodeDefaulter;
  28456. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  28457. var createDimensionOptions = {
  28458. coordDimensions: coordSysDimDefs,
  28459. generateCoord: opt.generateCoord,
  28460. encodeDefine: seriesModel.getEncode(),
  28461. encodeDefaulter: encodeDefaulter,
  28462. canOmitUnusedDimensions: !isOriginalSource
  28463. };
  28464. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  28465. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  28466. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  28467. var stackCalculationInfo = enableDataStack(seriesModel, {
  28468. schema: schema,
  28469. store: store
  28470. });
  28471. var data = new SeriesData(schema, seriesModel);
  28472. data.setCalculationInfo(stackCalculationInfo);
  28473. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  28474. // Use dataIndex as ordinal value in categoryAxis
  28475. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  28476. } : null;
  28477. data.hasItemOption = false;
  28478. data.initData( // Try to reuse the data store in sourceManager if using dataset.
  28479. isOriginalSource ? source : store, null, dimValueGetter);
  28480. return data;
  28481. }
  28482. function isNeedCompleteOrdinalData(source) {
  28483. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  28484. var sampleItem = firstDataNotNull(source.data || []);
  28485. return !isArray(getDataItemValue(sampleItem));
  28486. }
  28487. }
  28488. function firstDataNotNull(arr) {
  28489. var i = 0;
  28490. while (i < arr.length && arr[i] == null) {
  28491. i++;
  28492. }
  28493. return arr[i];
  28494. }
  28495. var Scale =
  28496. /** @class */
  28497. function () {
  28498. function Scale(setting) {
  28499. this._setting = setting || {};
  28500. this._extent = [Infinity, -Infinity];
  28501. }
  28502. Scale.prototype.getSetting = function (name) {
  28503. return this._setting[name];
  28504. };
  28505. /**
  28506. * Set extent from data
  28507. */
  28508. Scale.prototype.unionExtent = function (other) {
  28509. var extent = this._extent;
  28510. other[0] < extent[0] && (extent[0] = other[0]);
  28511. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  28512. // this.setExtent(extent[0], extent[1]);
  28513. };
  28514. /**
  28515. * Set extent from data
  28516. */
  28517. Scale.prototype.unionExtentFromData = function (data, dim) {
  28518. this.unionExtent(data.getApproximateExtent(dim));
  28519. };
  28520. /**
  28521. * Get extent
  28522. *
  28523. * Extent is always in increase order.
  28524. */
  28525. Scale.prototype.getExtent = function () {
  28526. return this._extent.slice();
  28527. };
  28528. /**
  28529. * Set extent
  28530. */
  28531. Scale.prototype.setExtent = function (start, end) {
  28532. var thisExtent = this._extent;
  28533. if (!isNaN(start)) {
  28534. thisExtent[0] = start;
  28535. }
  28536. if (!isNaN(end)) {
  28537. thisExtent[1] = end;
  28538. }
  28539. };
  28540. /**
  28541. * If value is in extent range
  28542. */
  28543. Scale.prototype.isInExtentRange = function (value) {
  28544. return this._extent[0] <= value && this._extent[1] >= value;
  28545. };
  28546. /**
  28547. * When axis extent depends on data and no data exists,
  28548. * axis ticks should not be drawn, which is named 'blank'.
  28549. */
  28550. Scale.prototype.isBlank = function () {
  28551. return this._isBlank;
  28552. };
  28553. /**
  28554. * When axis extent depends on data and no data exists,
  28555. * axis ticks should not be drawn, which is named 'blank'.
  28556. */
  28557. Scale.prototype.setBlank = function (isBlank) {
  28558. this._isBlank = isBlank;
  28559. };
  28560. return Scale;
  28561. }();
  28562. enableClassManagement(Scale);
  28563. var uidBase = 0;
  28564. var OrdinalMeta =
  28565. /** @class */
  28566. function () {
  28567. function OrdinalMeta(opt) {
  28568. this.categories = opt.categories || [];
  28569. this._needCollect = opt.needCollect;
  28570. this._deduplication = opt.deduplication;
  28571. this.uid = ++uidBase;
  28572. }
  28573. OrdinalMeta.createByAxisModel = function (axisModel) {
  28574. var option = axisModel.option;
  28575. var data = option.data;
  28576. var categories = data && map(data, getName);
  28577. return new OrdinalMeta({
  28578. categories: categories,
  28579. needCollect: !categories,
  28580. // deduplication is default in axis.
  28581. deduplication: option.dedplication !== false
  28582. });
  28583. };
  28584. OrdinalMeta.prototype.getOrdinal = function (category) {
  28585. // @ts-ignore
  28586. return this._getOrCreateMap().get(category);
  28587. };
  28588. /**
  28589. * @return The ordinal. If not found, return NaN.
  28590. */
  28591. OrdinalMeta.prototype.parseAndCollect = function (category) {
  28592. var index;
  28593. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  28594. // This feature is only supported when !needCollect, because we should
  28595. // consider a common case: a value is 2017, which is a number but is
  28596. // expected to be tread as a category. This case usually happen in dataset,
  28597. // where it happent to be no need of the index feature.
  28598. if (!isString(category) && !needCollect) {
  28599. return category;
  28600. } // Optimize for the scenario:
  28601. // category is ['2012-01-01', '2012-01-02', ...], where the input
  28602. // data has been ensured not duplicate and is large data.
  28603. // Notice, if a dataset dimension provide categroies, usually echarts
  28604. // should remove duplication except user tell echarts dont do that
  28605. // (set axis.deduplication = false), because echarts do not know whether
  28606. // the values in the category dimension has duplication (consider the
  28607. // parallel-aqi example)
  28608. if (needCollect && !this._deduplication) {
  28609. index = this.categories.length;
  28610. this.categories[index] = category;
  28611. return index;
  28612. }
  28613. var map = this._getOrCreateMap(); // @ts-ignore
  28614. index = map.get(category);
  28615. if (index == null) {
  28616. if (needCollect) {
  28617. index = this.categories.length;
  28618. this.categories[index] = category; // @ts-ignore
  28619. map.set(category, index);
  28620. } else {
  28621. index = NaN;
  28622. }
  28623. }
  28624. return index;
  28625. }; // Consider big data, do not create map until needed.
  28626. OrdinalMeta.prototype._getOrCreateMap = function () {
  28627. return this._map || (this._map = createHashMap(this.categories));
  28628. };
  28629. return OrdinalMeta;
  28630. }();
  28631. function getName(obj) {
  28632. if (isObject(obj) && obj.value != null) {
  28633. return obj.value;
  28634. } else {
  28635. return obj + '';
  28636. }
  28637. }
  28638. function isValueNice(val) {
  28639. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  28640. var f = Math.abs(val / exp10);
  28641. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  28642. }
  28643. function isIntervalOrLogScale(scale) {
  28644. return scale.type === 'interval' || scale.type === 'log';
  28645. }
  28646. /**
  28647. * @param extent Both extent[0] and extent[1] should be valid number.
  28648. * Should be extent[0] < extent[1].
  28649. * @param splitNumber splitNumber should be >= 1.
  28650. */
  28651. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  28652. var result = {};
  28653. var span = extent[1] - extent[0];
  28654. var interval = result.interval = nice(span / splitNumber, true);
  28655. if (minInterval != null && interval < minInterval) {
  28656. interval = result.interval = minInterval;
  28657. }
  28658. if (maxInterval != null && interval > maxInterval) {
  28659. interval = result.interval = maxInterval;
  28660. } // Tow more digital for tick.
  28661. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  28662. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  28663. fixExtent(niceTickExtent, extent);
  28664. return result;
  28665. }
  28666. function increaseInterval(interval) {
  28667. var exp10 = Math.pow(10, quantityExponent(interval)); // Increase interval
  28668. var f = interval / exp10;
  28669. if (!f) {
  28670. f = 1;
  28671. } else if (f === 2) {
  28672. f = 3;
  28673. } else if (f === 3) {
  28674. f = 5;
  28675. } else {
  28676. // f is 1 or 5
  28677. f *= 2;
  28678. }
  28679. return round(f * exp10);
  28680. }
  28681. /**
  28682. * @return interval precision
  28683. */
  28684. function getIntervalPrecision(interval) {
  28685. // Tow more digital for tick.
  28686. return getPrecision(interval) + 2;
  28687. }
  28688. function clamp(niceTickExtent, idx, extent) {
  28689. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  28690. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  28691. function fixExtent(niceTickExtent, extent) {
  28692. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  28693. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  28694. clamp(niceTickExtent, 0, extent);
  28695. clamp(niceTickExtent, 1, extent);
  28696. if (niceTickExtent[0] > niceTickExtent[1]) {
  28697. niceTickExtent[0] = niceTickExtent[1];
  28698. }
  28699. }
  28700. function contain$1(val, extent) {
  28701. return val >= extent[0] && val <= extent[1];
  28702. }
  28703. function normalize$1(val, extent) {
  28704. if (extent[1] === extent[0]) {
  28705. return 0.5;
  28706. }
  28707. return (val - extent[0]) / (extent[1] - extent[0]);
  28708. }
  28709. function scale$2(val, extent) {
  28710. return val * (extent[1] - extent[0]) + extent[0];
  28711. }
  28712. var OrdinalScale =
  28713. /** @class */
  28714. function (_super) {
  28715. __extends(OrdinalScale, _super);
  28716. function OrdinalScale(setting) {
  28717. var _this = _super.call(this, setting) || this;
  28718. _this.type = 'ordinal';
  28719. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  28720. // import approach to get OrdinalMeta class.
  28721. if (!ordinalMeta) {
  28722. ordinalMeta = new OrdinalMeta({});
  28723. }
  28724. if (isArray(ordinalMeta)) {
  28725. ordinalMeta = new OrdinalMeta({
  28726. categories: map(ordinalMeta, function (item) {
  28727. return isObject(item) ? item.value : item;
  28728. })
  28729. });
  28730. }
  28731. _this._ordinalMeta = ordinalMeta;
  28732. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  28733. return _this;
  28734. }
  28735. OrdinalScale.prototype.parse = function (val) {
  28736. // Caution: Math.round(null) will return `0` rather than `NaN`
  28737. if (val == null) {
  28738. return NaN;
  28739. }
  28740. return isString(val) ? this._ordinalMeta.getOrdinal(val) // val might be float.
  28741. : Math.round(val);
  28742. };
  28743. OrdinalScale.prototype.contain = function (rank) {
  28744. rank = this.parse(rank);
  28745. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  28746. };
  28747. /**
  28748. * Normalize given rank or name to linear [0, 1]
  28749. * @param val raw ordinal number.
  28750. * @return normalized value in [0, 1].
  28751. */
  28752. OrdinalScale.prototype.normalize = function (val) {
  28753. val = this._getTickNumber(this.parse(val));
  28754. return normalize$1(val, this._extent);
  28755. };
  28756. /**
  28757. * @param val normalized value in [0, 1].
  28758. * @return raw ordinal number.
  28759. */
  28760. OrdinalScale.prototype.scale = function (val) {
  28761. val = Math.round(scale$2(val, this._extent));
  28762. return this.getRawOrdinalNumber(val);
  28763. };
  28764. OrdinalScale.prototype.getTicks = function () {
  28765. var ticks = [];
  28766. var extent = this._extent;
  28767. var rank = extent[0];
  28768. while (rank <= extent[1]) {
  28769. ticks.push({
  28770. value: rank
  28771. });
  28772. rank++;
  28773. }
  28774. return ticks;
  28775. };
  28776. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  28777. // Not support.
  28778. return;
  28779. };
  28780. /**
  28781. * @see `Ordinal['_ordinalNumbersByTick']`
  28782. */
  28783. OrdinalScale.prototype.setSortInfo = function (info) {
  28784. if (info == null) {
  28785. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  28786. return;
  28787. }
  28788. var infoOrdinalNumbers = info.ordinalNumbers;
  28789. var ordinalsByTick = this._ordinalNumbersByTick = [];
  28790. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  28791. var tickNum = 0;
  28792. var allCategoryLen = this._ordinalMeta.categories.length;
  28793. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  28794. var ordinalNumber = infoOrdinalNumbers[tickNum];
  28795. ordinalsByTick[tickNum] = ordinalNumber;
  28796. ticksByOrdinal[ordinalNumber] = tickNum;
  28797. } // Handle that `series.data` only covers part of the `axis.category.data`.
  28798. var unusedOrdinal = 0;
  28799. for (; tickNum < allCategoryLen; ++tickNum) {
  28800. while (ticksByOrdinal[unusedOrdinal] != null) {
  28801. unusedOrdinal++;
  28802. }
  28803. ordinalsByTick.push(unusedOrdinal);
  28804. ticksByOrdinal[unusedOrdinal] = tickNum;
  28805. }
  28806. };
  28807. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  28808. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  28809. // where ordinal numbers are used as tick value directly.
  28810. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  28811. };
  28812. /**
  28813. * @usage
  28814. * ```js
  28815. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  28816. *
  28817. * // case0
  28818. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  28819. * // case1
  28820. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  28821. * // case2
  28822. * const coord = axis.dataToCoord(ordinalNumber);
  28823. * ```
  28824. *
  28825. * @param {OrdinalNumber} tickNumber index of display
  28826. */
  28827. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  28828. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  28829. // where ordinal numbers are used as tick value directly.
  28830. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  28831. };
  28832. /**
  28833. * Get item on tick
  28834. */
  28835. OrdinalScale.prototype.getLabel = function (tick) {
  28836. if (!this.isBlank()) {
  28837. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  28838. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  28839. // Return empty if it's not exist.
  28840. return cateogry == null ? '' : cateogry + '';
  28841. }
  28842. };
  28843. OrdinalScale.prototype.count = function () {
  28844. return this._extent[1] - this._extent[0] + 1;
  28845. };
  28846. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  28847. this.unionExtent(data.getApproximateExtent(dim));
  28848. };
  28849. /**
  28850. * @override
  28851. * If value is in extent range
  28852. */
  28853. OrdinalScale.prototype.isInExtentRange = function (value) {
  28854. value = this._getTickNumber(value);
  28855. return this._extent[0] <= value && this._extent[1] >= value;
  28856. };
  28857. OrdinalScale.prototype.getOrdinalMeta = function () {
  28858. return this._ordinalMeta;
  28859. };
  28860. OrdinalScale.prototype.calcNiceTicks = function () {};
  28861. OrdinalScale.prototype.calcNiceExtent = function () {};
  28862. OrdinalScale.type = 'ordinal';
  28863. return OrdinalScale;
  28864. }(Scale);
  28865. Scale.registerClass(OrdinalScale);
  28866. var roundNumber = round;
  28867. var IntervalScale =
  28868. /** @class */
  28869. function (_super) {
  28870. __extends(IntervalScale, _super);
  28871. function IntervalScale() {
  28872. var _this = _super !== null && _super.apply(this, arguments) || this;
  28873. _this.type = 'interval'; // Step is calculated in adjustExtent.
  28874. _this._interval = 0;
  28875. _this._intervalPrecision = 2;
  28876. return _this;
  28877. }
  28878. IntervalScale.prototype.parse = function (val) {
  28879. return val;
  28880. };
  28881. IntervalScale.prototype.contain = function (val) {
  28882. return contain$1(val, this._extent);
  28883. };
  28884. IntervalScale.prototype.normalize = function (val) {
  28885. return normalize$1(val, this._extent);
  28886. };
  28887. IntervalScale.prototype.scale = function (val) {
  28888. return scale$2(val, this._extent);
  28889. };
  28890. IntervalScale.prototype.setExtent = function (start, end) {
  28891. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  28892. if (!isNaN(start)) {
  28893. thisExtent[0] = parseFloat(start);
  28894. }
  28895. if (!isNaN(end)) {
  28896. thisExtent[1] = parseFloat(end);
  28897. }
  28898. };
  28899. IntervalScale.prototype.unionExtent = function (other) {
  28900. var extent = this._extent;
  28901. other[0] < extent[0] && (extent[0] = other[0]);
  28902. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  28903. this.setExtent(extent[0], extent[1]);
  28904. };
  28905. IntervalScale.prototype.getInterval = function () {
  28906. return this._interval;
  28907. };
  28908. IntervalScale.prototype.setInterval = function (interval) {
  28909. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  28910. // We assume user wan't to set both interval, min, max to get a better result
  28911. this._niceExtent = this._extent.slice();
  28912. this._intervalPrecision = getIntervalPrecision(interval);
  28913. };
  28914. /**
  28915. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  28916. */
  28917. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  28918. var interval = this._interval;
  28919. var extent = this._extent;
  28920. var niceTickExtent = this._niceExtent;
  28921. var intervalPrecision = this._intervalPrecision;
  28922. var ticks = []; // If interval is 0, return [];
  28923. if (!interval) {
  28924. return ticks;
  28925. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  28926. var safeLimit = 10000;
  28927. if (extent[0] < niceTickExtent[0]) {
  28928. if (expandToNicedExtent) {
  28929. ticks.push({
  28930. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  28931. });
  28932. } else {
  28933. ticks.push({
  28934. value: extent[0]
  28935. });
  28936. }
  28937. }
  28938. var tick = niceTickExtent[0];
  28939. while (tick <= niceTickExtent[1]) {
  28940. ticks.push({
  28941. value: tick
  28942. }); // Avoid rounding error
  28943. tick = roundNumber(tick + interval, intervalPrecision);
  28944. if (tick === ticks[ticks.length - 1].value) {
  28945. // Consider out of safe float point, e.g.,
  28946. // -3711126.9907707 + 2e-10 === -3711126.9907707
  28947. break;
  28948. }
  28949. if (ticks.length > safeLimit) {
  28950. return [];
  28951. }
  28952. } // Consider this case: the last item of ticks is smaller
  28953. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  28954. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  28955. if (extent[1] > lastNiceTick) {
  28956. if (expandToNicedExtent) {
  28957. ticks.push({
  28958. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  28959. });
  28960. } else {
  28961. ticks.push({
  28962. value: extent[1]
  28963. });
  28964. }
  28965. }
  28966. return ticks;
  28967. };
  28968. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  28969. var ticks = this.getTicks(true);
  28970. var minorTicks = [];
  28971. var extent = this.getExtent();
  28972. for (var i = 1; i < ticks.length; i++) {
  28973. var nextTick = ticks[i];
  28974. var prevTick = ticks[i - 1];
  28975. var count = 0;
  28976. var minorTicksGroup = [];
  28977. var interval = nextTick.value - prevTick.value;
  28978. var minorInterval = interval / splitNumber;
  28979. while (count < splitNumber - 1) {
  28980. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  28981. if (minorTick > extent[0] && minorTick < extent[1]) {
  28982. minorTicksGroup.push(minorTick);
  28983. }
  28984. count++;
  28985. }
  28986. minorTicks.push(minorTicksGroup);
  28987. }
  28988. return minorTicks;
  28989. };
  28990. /**
  28991. * @param opt.precision If 'auto', use nice presision.
  28992. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  28993. */
  28994. IntervalScale.prototype.getLabel = function (data, opt) {
  28995. if (data == null) {
  28996. return '';
  28997. }
  28998. var precision = opt && opt.precision;
  28999. if (precision == null) {
  29000. precision = getPrecision(data.value) || 0;
  29001. } else if (precision === 'auto') {
  29002. // Should be more precise then tick.
  29003. precision = this._intervalPrecision;
  29004. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29005. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29006. var dataNum = roundNumber(data.value, precision, true);
  29007. return addCommas(dataNum);
  29008. };
  29009. /**
  29010. * @param splitNumber By default `5`.
  29011. */
  29012. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  29013. splitNumber = splitNumber || 5;
  29014. var extent = this._extent;
  29015. var span = extent[1] - extent[0];
  29016. if (!isFinite(span)) {
  29017. return;
  29018. } // User may set axis min 0 and data are all negative
  29019. // FIXME If it needs to reverse ?
  29020. if (span < 0) {
  29021. span = -span;
  29022. extent.reverse();
  29023. }
  29024. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  29025. this._intervalPrecision = result.intervalPrecision;
  29026. this._interval = result.interval;
  29027. this._niceExtent = result.niceTickExtent;
  29028. };
  29029. IntervalScale.prototype.calcNiceExtent = function (opt) {
  29030. var extent = this._extent; // If extent start and end are same, expand them
  29031. if (extent[0] === extent[1]) {
  29032. if (extent[0] !== 0) {
  29033. // Expand extent
  29034. var expandSize = extent[0]; // In the fowllowing case
  29035. // Axis has been fixed max 100
  29036. // Plus data are all 100 and axis extent are [100, 100].
  29037. // Extend to the both side will cause expanded max is larger than fixed max.
  29038. // So only expand to the smaller side.
  29039. if (!opt.fixMax) {
  29040. extent[1] += expandSize / 2;
  29041. extent[0] -= expandSize / 2;
  29042. } else {
  29043. extent[0] -= expandSize / 2;
  29044. }
  29045. } else {
  29046. extent[1] = 1;
  29047. }
  29048. }
  29049. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  29050. if (!isFinite(span)) {
  29051. extent[0] = 0;
  29052. extent[1] = 1;
  29053. }
  29054. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  29055. var interval = this._interval;
  29056. if (!opt.fixMin) {
  29057. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29058. }
  29059. if (!opt.fixMax) {
  29060. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29061. }
  29062. };
  29063. IntervalScale.prototype.setNiceExtent = function (min, max) {
  29064. this._niceExtent = [min, max];
  29065. };
  29066. IntervalScale.type = 'interval';
  29067. return IntervalScale;
  29068. }(Scale);
  29069. Scale.registerClass(IntervalScale);
  29070. /* global Float32Array */
  29071. var supportFloat32Array = typeof Float32Array !== 'undefined';
  29072. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  29073. function createFloat32Array(arg) {
  29074. if (isArray(arg)) {
  29075. // Return self directly if don't support TypedArray.
  29076. return supportFloat32Array ? new Float32Array(arg) : arg;
  29077. } // Else is number
  29078. return new Float32ArrayCtor(arg);
  29079. }
  29080. var STACK_PREFIX = '__ec_stack_';
  29081. function getSeriesStackId(seriesModel) {
  29082. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29083. }
  29084. function getAxisKey(axis) {
  29085. return axis.dim + axis.index;
  29086. }
  29087. function prepareLayoutBarSeries(seriesType, ecModel) {
  29088. var seriesModels = [];
  29089. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29090. // Check series coordinate, do layout for cartesian2d only
  29091. if (isOnCartesian(seriesModel)) {
  29092. seriesModels.push(seriesModel);
  29093. }
  29094. });
  29095. return seriesModels;
  29096. }
  29097. /**
  29098. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29099. * values.
  29100. * This works for time axes, value axes, and log axes.
  29101. * For a single time axis, return value is in the form like
  29102. * {'x_0': [1000000]}.
  29103. * The value of 1000000 is in milliseconds.
  29104. */
  29105. function getValueAxesMinGaps(barSeries) {
  29106. /**
  29107. * Map from axis.index to values.
  29108. * For a single time axis, axisValues is in the form like
  29109. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29110. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29111. * series.
  29112. */
  29113. var axisValues = {};
  29114. each(barSeries, function (seriesModel) {
  29115. var cartesian = seriesModel.coordinateSystem;
  29116. var baseAxis = cartesian.getBaseAxis();
  29117. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29118. return;
  29119. }
  29120. var data = seriesModel.getData();
  29121. var key = baseAxis.dim + '_' + baseAxis.index;
  29122. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  29123. var store = data.getStore();
  29124. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  29125. var value = store.get(dimIdx, i);
  29126. if (!axisValues[key]) {
  29127. // No previous data for the axis
  29128. axisValues[key] = [value];
  29129. } else {
  29130. // No value in previous series
  29131. axisValues[key].push(value);
  29132. } // Ignore duplicated time values in the same axis
  29133. }
  29134. });
  29135. var axisMinGaps = {};
  29136. for (var key in axisValues) {
  29137. if (axisValues.hasOwnProperty(key)) {
  29138. var valuesInAxis = axisValues[key];
  29139. if (valuesInAxis) {
  29140. // Sort axis values into ascending order to calculate gaps
  29141. valuesInAxis.sort(function (a, b) {
  29142. return a - b;
  29143. });
  29144. var min = null;
  29145. for (var j = 1; j < valuesInAxis.length; ++j) {
  29146. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29147. if (delta > 0) {
  29148. // Ignore 0 delta because they are of the same axis value
  29149. min = min === null ? delta : Math.min(min, delta);
  29150. }
  29151. } // Set to null if only have one data
  29152. axisMinGaps[key] = min;
  29153. }
  29154. }
  29155. }
  29156. return axisMinGaps;
  29157. }
  29158. function makeColumnLayout(barSeries) {
  29159. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29160. var seriesInfoList = [];
  29161. each(barSeries, function (seriesModel) {
  29162. var cartesian = seriesModel.coordinateSystem;
  29163. var baseAxis = cartesian.getBaseAxis();
  29164. var axisExtent = baseAxis.getExtent();
  29165. var bandWidth;
  29166. if (baseAxis.type === 'category') {
  29167. bandWidth = baseAxis.getBandWidth();
  29168. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29169. var key = baseAxis.dim + '_' + baseAxis.index;
  29170. var minGap = axisMinGaps[key];
  29171. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29172. var scale = baseAxis.scale.getExtent();
  29173. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29174. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  29175. } else {
  29176. var data = seriesModel.getData();
  29177. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29178. }
  29179. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  29180. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  29181. var barMinWidth = parsePercent$1( // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  29182. // the auto-calculated bar width might be less than 0.5 / 1.
  29183. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  29184. var barGap = seriesModel.get('barGap');
  29185. var barCategoryGap = seriesModel.get('barCategoryGap');
  29186. seriesInfoList.push({
  29187. bandWidth: bandWidth,
  29188. barWidth: barWidth,
  29189. barMaxWidth: barMaxWidth,
  29190. barMinWidth: barMinWidth,
  29191. barGap: barGap,
  29192. barCategoryGap: barCategoryGap,
  29193. axisKey: getAxisKey(baseAxis),
  29194. stackId: getSeriesStackId(seriesModel)
  29195. });
  29196. });
  29197. return doCalBarWidthAndOffset(seriesInfoList);
  29198. }
  29199. function doCalBarWidthAndOffset(seriesInfoList) {
  29200. // Columns info on each category axis. Key is cartesian name
  29201. var columnsMap = {};
  29202. each(seriesInfoList, function (seriesInfo, idx) {
  29203. var axisKey = seriesInfo.axisKey;
  29204. var bandWidth = seriesInfo.bandWidth;
  29205. var columnsOnAxis = columnsMap[axisKey] || {
  29206. bandWidth: bandWidth,
  29207. remainedWidth: bandWidth,
  29208. autoWidthCount: 0,
  29209. categoryGap: null,
  29210. gap: '20%',
  29211. stacks: {}
  29212. };
  29213. var stacks = columnsOnAxis.stacks;
  29214. columnsMap[axisKey] = columnsOnAxis;
  29215. var stackId = seriesInfo.stackId;
  29216. if (!stacks[stackId]) {
  29217. columnsOnAxis.autoWidthCount++;
  29218. }
  29219. stacks[stackId] = stacks[stackId] || {
  29220. width: 0,
  29221. maxWidth: 0
  29222. }; // Caution: In a single coordinate system, these barGrid attributes
  29223. // will be shared by series. Consider that they have default values,
  29224. // only the attributes set on the last series will work.
  29225. // Do not change this fact unless there will be a break change.
  29226. var barWidth = seriesInfo.barWidth;
  29227. if (barWidth && !stacks[stackId].width) {
  29228. // See #6312, do not restrict width.
  29229. stacks[stackId].width = barWidth;
  29230. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29231. columnsOnAxis.remainedWidth -= barWidth;
  29232. }
  29233. var barMaxWidth = seriesInfo.barMaxWidth;
  29234. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  29235. var barMinWidth = seriesInfo.barMinWidth;
  29236. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  29237. var barGap = seriesInfo.barGap;
  29238. barGap != null && (columnsOnAxis.gap = barGap);
  29239. var barCategoryGap = seriesInfo.barCategoryGap;
  29240. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  29241. });
  29242. var result = {};
  29243. each(columnsMap, function (columnsOnAxis, coordSysName) {
  29244. result[coordSysName] = {};
  29245. var stacks = columnsOnAxis.stacks;
  29246. var bandWidth = columnsOnAxis.bandWidth;
  29247. var categoryGapPercent = columnsOnAxis.categoryGap;
  29248. if (categoryGapPercent == null) {
  29249. var columnCount = keys(stacks).length; // More columns in one group
  29250. // the spaces between group is smaller. Or the column will be too thin.
  29251. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  29252. }
  29253. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  29254. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  29255. var remainedWidth = columnsOnAxis.remainedWidth;
  29256. var autoWidthCount = columnsOnAxis.autoWidthCount;
  29257. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29258. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  29259. each(stacks, function (column) {
  29260. var maxWidth = column.maxWidth;
  29261. var minWidth = column.minWidth;
  29262. if (!column.width) {
  29263. var finalWidth = autoWidth;
  29264. if (maxWidth && maxWidth < finalWidth) {
  29265. finalWidth = Math.min(maxWidth, remainedWidth);
  29266. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  29267. // bar is able to be visible. So `minWidth` should not be restricted
  29268. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  29269. // the extreme cases for `value` axis, bars are allowed to overlap
  29270. // with each other if `minWidth` specified.
  29271. if (minWidth && minWidth > finalWidth) {
  29272. finalWidth = minWidth;
  29273. }
  29274. if (finalWidth !== autoWidth) {
  29275. column.width = finalWidth;
  29276. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29277. autoWidthCount--;
  29278. }
  29279. } else {
  29280. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  29281. // CSS does. Becuase barWidth can be a percent value, where
  29282. // `barMaxWidth` can be used to restrict the final width.
  29283. var finalWidth = column.width;
  29284. if (maxWidth) {
  29285. finalWidth = Math.min(finalWidth, maxWidth);
  29286. } // `minWidth` has higher priority, as described above
  29287. if (minWidth) {
  29288. finalWidth = Math.max(finalWidth, minWidth);
  29289. }
  29290. column.width = finalWidth;
  29291. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29292. autoWidthCount--;
  29293. }
  29294. }); // Recalculate width again
  29295. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29296. autoWidth = Math.max(autoWidth, 0);
  29297. var widthSum = 0;
  29298. var lastColumn;
  29299. each(stacks, function (column, idx) {
  29300. if (!column.width) {
  29301. column.width = autoWidth;
  29302. }
  29303. lastColumn = column;
  29304. widthSum += column.width * (1 + barGapPercent);
  29305. });
  29306. if (lastColumn) {
  29307. widthSum -= lastColumn.width * barGapPercent;
  29308. }
  29309. var offset = -widthSum / 2;
  29310. each(stacks, function (column, stackId) {
  29311. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  29312. bandWidth: bandWidth,
  29313. offset: offset,
  29314. width: column.width
  29315. };
  29316. offset += column.width * (1 + barGapPercent);
  29317. });
  29318. });
  29319. return result;
  29320. }
  29321. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  29322. if (barWidthAndOffset && axis) {
  29323. var result = barWidthAndOffset[getAxisKey(axis)];
  29324. if (result != null && seriesModel != null) {
  29325. return result[getSeriesStackId(seriesModel)];
  29326. }
  29327. return result;
  29328. }
  29329. }
  29330. function layout(seriesType, ecModel) {
  29331. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  29332. var barWidthAndOffset = makeColumnLayout(seriesModels);
  29333. each(seriesModels, function (seriesModel) {
  29334. var data = seriesModel.getData();
  29335. var cartesian = seriesModel.coordinateSystem;
  29336. var baseAxis = cartesian.getBaseAxis();
  29337. var stackId = getSeriesStackId(seriesModel);
  29338. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  29339. var columnOffset = columnLayoutInfo.offset;
  29340. var columnWidth = columnLayoutInfo.width;
  29341. data.setLayout({
  29342. bandWidth: columnLayoutInfo.bandWidth,
  29343. offset: columnOffset,
  29344. size: columnWidth
  29345. });
  29346. });
  29347. } // TODO: Do not support stack in large mode yet.
  29348. function createProgressiveLayout(seriesType) {
  29349. return {
  29350. seriesType: seriesType,
  29351. plan: createRenderPlanner(),
  29352. reset: function (seriesModel) {
  29353. if (!isOnCartesian(seriesModel)) {
  29354. return;
  29355. }
  29356. var data = seriesModel.getData();
  29357. var cartesian = seriesModel.coordinateSystem;
  29358. var baseAxis = cartesian.getBaseAxis();
  29359. var valueAxis = cartesian.getOtherAxis(baseAxis);
  29360. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  29361. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  29362. var drawBackground = seriesModel.get('showBackground', true);
  29363. var valueDim = data.mapDimension(valueAxis.dim);
  29364. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29365. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  29366. var isValueAxisH = valueAxis.isHorizontal();
  29367. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  29368. var isLarge = isInLargeMode(seriesModel);
  29369. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  29370. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim); // Layout info.
  29371. var columnWidth = data.getLayout('size');
  29372. var columnOffset = data.getLayout('offset');
  29373. return {
  29374. progress: function (params, data) {
  29375. var count = params.count;
  29376. var largePoints = isLarge && createFloat32Array(count * 3);
  29377. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  29378. var largeDataIndices = isLarge && createFloat32Array(count);
  29379. var coordLayout = cartesian.master.getRect();
  29380. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  29381. var dataIndex;
  29382. var store = data.getStore();
  29383. var idxOffset = 0;
  29384. while ((dataIndex = params.next()) != null) {
  29385. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  29386. var baseValue = store.get(baseDimIdx, dataIndex);
  29387. var baseCoord = valueAxisStart;
  29388. var startValue = void 0; // Because of the barMinHeight, we can not use the value in
  29389. // stackResultDimension directly.
  29390. if (stacked) {
  29391. startValue = +value - store.get(valueDimIdx, dataIndex);
  29392. }
  29393. var x = void 0;
  29394. var y = void 0;
  29395. var width = void 0;
  29396. var height = void 0;
  29397. if (isValueAxisH) {
  29398. var coord = cartesian.dataToPoint([value, baseValue]);
  29399. if (stacked) {
  29400. var startCoord = cartesian.dataToPoint([startValue, baseValue]);
  29401. baseCoord = startCoord[0];
  29402. }
  29403. x = baseCoord;
  29404. y = coord[1] + columnOffset;
  29405. width = coord[0] - baseCoord;
  29406. height = columnWidth;
  29407. if (Math.abs(width) < barMinHeight) {
  29408. width = (width < 0 ? -1 : 1) * barMinHeight;
  29409. }
  29410. } else {
  29411. var coord = cartesian.dataToPoint([baseValue, value]);
  29412. if (stacked) {
  29413. var startCoord = cartesian.dataToPoint([baseValue, startValue]);
  29414. baseCoord = startCoord[1];
  29415. }
  29416. x = coord[0] + columnOffset;
  29417. y = baseCoord;
  29418. width = columnWidth;
  29419. height = coord[1] - baseCoord;
  29420. if (Math.abs(height) < barMinHeight) {
  29421. // Include zero to has a positive bar
  29422. height = (height <= 0 ? -1 : 1) * barMinHeight;
  29423. }
  29424. }
  29425. if (!isLarge) {
  29426. data.setItemLayout(dataIndex, {
  29427. x: x,
  29428. y: y,
  29429. width: width,
  29430. height: height
  29431. });
  29432. } else {
  29433. largePoints[idxOffset] = x;
  29434. largePoints[idxOffset + 1] = y;
  29435. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  29436. if (largeBackgroundPoints) {
  29437. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  29438. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  29439. largeBackgroundPoints[idxOffset + 2] = bgSize;
  29440. }
  29441. largeDataIndices[dataIndex] = dataIndex;
  29442. }
  29443. idxOffset += 3;
  29444. }
  29445. if (isLarge) {
  29446. data.setLayout({
  29447. largePoints: largePoints,
  29448. largeDataIndices: largeDataIndices,
  29449. largeBackgroundPoints: largeBackgroundPoints,
  29450. valueAxisHorizontal: isValueAxisH
  29451. });
  29452. }
  29453. }
  29454. };
  29455. }
  29456. };
  29457. }
  29458. function isOnCartesian(seriesModel) {
  29459. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  29460. }
  29461. function isInLargeMode(seriesModel) {
  29462. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  29463. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  29464. function getValueAxisStart(baseAxis, valueAxis) {
  29465. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  29466. }
  29467. var bisect = function (a, x, lo, hi) {
  29468. while (lo < hi) {
  29469. var mid = lo + hi >>> 1;
  29470. if (a[mid][1] < x) {
  29471. lo = mid + 1;
  29472. } else {
  29473. hi = mid;
  29474. }
  29475. }
  29476. return lo;
  29477. };
  29478. var TimeScale =
  29479. /** @class */
  29480. function (_super) {
  29481. __extends(TimeScale, _super);
  29482. function TimeScale(settings) {
  29483. var _this = _super.call(this, settings) || this;
  29484. _this.type = 'time';
  29485. return _this;
  29486. }
  29487. /**
  29488. * Get label is mainly for other components like dataZoom, tooltip.
  29489. */
  29490. TimeScale.prototype.getLabel = function (tick) {
  29491. var useUTC = this.getSetting('useUTC');
  29492. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  29493. };
  29494. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  29495. var isUTC = this.getSetting('useUTC');
  29496. var lang = this.getSetting('locale');
  29497. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  29498. };
  29499. /**
  29500. * @override
  29501. */
  29502. TimeScale.prototype.getTicks = function () {
  29503. var interval = this._interval;
  29504. var extent = this._extent;
  29505. var ticks = []; // If interval is 0, return [];
  29506. if (!interval) {
  29507. return ticks;
  29508. }
  29509. ticks.push({
  29510. value: extent[0],
  29511. level: 0
  29512. });
  29513. var useUTC = this.getSetting('useUTC');
  29514. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  29515. ticks = ticks.concat(innerTicks);
  29516. ticks.push({
  29517. value: extent[1],
  29518. level: 0
  29519. });
  29520. return ticks;
  29521. };
  29522. TimeScale.prototype.calcNiceExtent = function (opt) {
  29523. var extent = this._extent; // If extent start and end are same, expand them
  29524. if (extent[0] === extent[1]) {
  29525. // Expand extent
  29526. extent[0] -= ONE_DAY;
  29527. extent[1] += ONE_DAY;
  29528. } // If there are no data and extent are [Infinity, -Infinity]
  29529. if (extent[1] === -Infinity && extent[0] === Infinity) {
  29530. var d = new Date();
  29531. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  29532. extent[0] = extent[1] - ONE_DAY;
  29533. }
  29534. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29535. };
  29536. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  29537. approxTickNum = approxTickNum || 10;
  29538. var extent = this._extent;
  29539. var span = extent[1] - extent[0];
  29540. this._approxInterval = span / approxTickNum;
  29541. if (minInterval != null && this._approxInterval < minInterval) {
  29542. this._approxInterval = minInterval;
  29543. }
  29544. if (maxInterval != null && this._approxInterval > maxInterval) {
  29545. this._approxInterval = maxInterval;
  29546. }
  29547. var scaleIntervalsLen = scaleIntervals.length;
  29548. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  29549. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  29550. // We check one more level to avoid the ticks are to sparse in some case.
  29551. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  29552. };
  29553. TimeScale.prototype.parse = function (val) {
  29554. // val might be float.
  29555. return isNumber(val) ? val : +parseDate(val);
  29556. };
  29557. TimeScale.prototype.contain = function (val) {
  29558. return contain$1(this.parse(val), this._extent);
  29559. };
  29560. TimeScale.prototype.normalize = function (val) {
  29561. return normalize$1(this.parse(val), this._extent);
  29562. };
  29563. TimeScale.prototype.scale = function (val) {
  29564. return scale$2(val, this._extent);
  29565. };
  29566. TimeScale.type = 'time';
  29567. return TimeScale;
  29568. }(IntervalScale);
  29569. /**
  29570. * This implementation was originally copied from "d3.js"
  29571. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  29572. * with some modifications made for this program.
  29573. * See the license statement at the head of this file.
  29574. */
  29575. var scaleIntervals = [// Format interval
  29576. ['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
  29577. ];
  29578. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  29579. var dateA = parseDate(valueA);
  29580. var dateB = parseDate(valueB);
  29581. var isSame = function (unit) {
  29582. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  29583. };
  29584. var isSameYear = function () {
  29585. return isSame('year');
  29586. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  29587. // const isSameQuater = () => isSameYear() && isSame('quarter');
  29588. var isSameMonth = function () {
  29589. return isSameYear() && isSame('month');
  29590. };
  29591. var isSameDay = function () {
  29592. return isSameMonth() && isSame('day');
  29593. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  29594. var isSameHour = function () {
  29595. return isSameDay() && isSame('hour');
  29596. };
  29597. var isSameMinute = function () {
  29598. return isSameHour() && isSame('minute');
  29599. };
  29600. var isSameSecond = function () {
  29601. return isSameMinute() && isSame('second');
  29602. };
  29603. var isSameMilliSecond = function () {
  29604. return isSameSecond() && isSame('millisecond');
  29605. };
  29606. switch (unit) {
  29607. case 'year':
  29608. return isSameYear();
  29609. case 'month':
  29610. return isSameMonth();
  29611. case 'day':
  29612. return isSameDay();
  29613. case 'hour':
  29614. return isSameHour();
  29615. case 'minute':
  29616. return isSameMinute();
  29617. case 'second':
  29618. return isSameSecond();
  29619. case 'millisecond':
  29620. return isSameMilliSecond();
  29621. }
  29622. } // const primaryUnitGetters = {
  29623. // year: fullYearGetterName(),
  29624. // month: monthGetterName(),
  29625. // day: dateGetterName(),
  29626. // hour: hoursGetterName(),
  29627. // minute: minutesGetterName(),
  29628. // second: secondsGetterName(),
  29629. // millisecond: millisecondsGetterName()
  29630. // };
  29631. // const primaryUnitUTCGetters = {
  29632. // year: fullYearGetterName(true),
  29633. // month: monthGetterName(true),
  29634. // day: dateGetterName(true),
  29635. // hour: hoursGetterName(true),
  29636. // minute: minutesGetterName(true),
  29637. // second: secondsGetterName(true),
  29638. // millisecond: millisecondsGetterName(true)
  29639. // };
  29640. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  29641. // step = step || 1;
  29642. // switch (getPrimaryTimeUnit(unitName)) {
  29643. // case 'year':
  29644. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  29645. // break;
  29646. // case 'month':
  29647. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  29648. // break;
  29649. // case 'day':
  29650. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  29651. // break;
  29652. // case 'hour':
  29653. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  29654. // break;
  29655. // case 'minute':
  29656. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  29657. // break;
  29658. // case 'second':
  29659. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  29660. // break;
  29661. // case 'millisecond':
  29662. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  29663. // break;
  29664. // }
  29665. // return date.getTime();
  29666. // }
  29667. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  29668. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  29669. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  29670. function getDateInterval(approxInterval, daysInMonth) {
  29671. approxInterval /= ONE_DAY;
  29672. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick betwen two month.
  29673. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  29674. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  29675. }
  29676. function getMonthInterval(approxInterval) {
  29677. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  29678. approxInterval /= APPROX_ONE_MONTH;
  29679. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  29680. }
  29681. function getHourInterval(approxInterval) {
  29682. approxInterval /= ONE_HOUR;
  29683. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  29684. }
  29685. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  29686. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  29687. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  29688. }
  29689. function getMillisecondsInterval(approxInterval) {
  29690. return nice(approxInterval, true);
  29691. }
  29692. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  29693. var outDate = new Date(date);
  29694. switch (getPrimaryTimeUnit(unitName)) {
  29695. case 'year':
  29696. case 'month':
  29697. outDate[monthSetterName(isUTC)](0);
  29698. case 'day':
  29699. outDate[dateSetterName(isUTC)](1);
  29700. case 'hour':
  29701. outDate[hoursSetterName(isUTC)](0);
  29702. case 'minute':
  29703. outDate[minutesSetterName(isUTC)](0);
  29704. case 'second':
  29705. outDate[secondsSetterName(isUTC)](0);
  29706. outDate[millisecondsSetterName(isUTC)](0);
  29707. }
  29708. return outDate.getTime();
  29709. }
  29710. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  29711. var safeLimit = 10000;
  29712. var unitNames = timeUnits;
  29713. var iter = 0;
  29714. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  29715. var date = new Date(minTimestamp);
  29716. var dateTime = minTimestamp;
  29717. var d = date[getMethodName](); // if (isDate) {
  29718. // d -= 1; // Starts with 0; PENDING
  29719. // }
  29720. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  29721. out.push({
  29722. value: dateTime
  29723. });
  29724. d += interval;
  29725. date[setMethodName](d);
  29726. dateTime = date.getTime();
  29727. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  29728. out.push({
  29729. value: dateTime,
  29730. notAdd: true
  29731. });
  29732. }
  29733. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  29734. var newAddedTicks = [];
  29735. var isFirstLevel = !lastLevelTicks.length;
  29736. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  29737. return;
  29738. }
  29739. if (isFirstLevel) {
  29740. lastLevelTicks = [{
  29741. // TODO Optimize. Not include so may ticks.
  29742. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  29743. }, {
  29744. value: extent[1]
  29745. }];
  29746. }
  29747. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  29748. var startTick = lastLevelTicks[i].value;
  29749. var endTick = lastLevelTicks[i + 1].value;
  29750. if (startTick === endTick) {
  29751. continue;
  29752. }
  29753. var interval = void 0;
  29754. var getterName = void 0;
  29755. var setterName = void 0;
  29756. var isDate = false;
  29757. switch (unitName) {
  29758. case 'year':
  29759. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  29760. getterName = fullYearGetterName(isUTC);
  29761. setterName = fullYearSetterName(isUTC);
  29762. break;
  29763. case 'half-year':
  29764. case 'quarter':
  29765. case 'month':
  29766. interval = getMonthInterval(approxInterval);
  29767. getterName = monthGetterName(isUTC);
  29768. setterName = monthSetterName(isUTC);
  29769. break;
  29770. case 'week': // PENDING If week is added. Ignore day.
  29771. case 'half-week':
  29772. case 'day':
  29773. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  29774. getterName = dateGetterName(isUTC);
  29775. setterName = dateSetterName(isUTC);
  29776. isDate = true;
  29777. break;
  29778. case 'half-day':
  29779. case 'quarter-day':
  29780. case 'hour':
  29781. interval = getHourInterval(approxInterval);
  29782. getterName = hoursGetterName(isUTC);
  29783. setterName = hoursSetterName(isUTC);
  29784. break;
  29785. case 'minute':
  29786. interval = getMinutesAndSecondsInterval(approxInterval, true);
  29787. getterName = minutesGetterName(isUTC);
  29788. setterName = minutesSetterName(isUTC);
  29789. break;
  29790. case 'second':
  29791. interval = getMinutesAndSecondsInterval(approxInterval, false);
  29792. getterName = secondsGetterName(isUTC);
  29793. setterName = secondsSetterName(isUTC);
  29794. break;
  29795. case 'millisecond':
  29796. interval = getMillisecondsInterval(approxInterval);
  29797. getterName = millisecondsGetterName(isUTC);
  29798. setterName = millisecondsSetterName(isUTC);
  29799. break;
  29800. }
  29801. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  29802. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  29803. // Add nearest years to the left extent.
  29804. levelTicks.unshift({
  29805. value: levelTicks[0].value - interval
  29806. });
  29807. }
  29808. }
  29809. for (var i = 0; i < newAddedTicks.length; i++) {
  29810. levelTicks.push(newAddedTicks[i]);
  29811. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  29812. return newAddedTicks;
  29813. }
  29814. var levelsTicks = [];
  29815. var currentLevelTicks = [];
  29816. var tickCount = 0;
  29817. var lastLevelTickCount = 0;
  29818. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  29819. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  29820. if (!isPrimaryTimeUnit(unitNames[i])) {
  29821. // TODO
  29822. continue;
  29823. }
  29824. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  29825. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  29826. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  29827. if (currentLevelTicks.length) {
  29828. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  29829. currentLevelTicks.sort(function (a, b) {
  29830. return a.value - b.value;
  29831. });
  29832. var levelTicksRemoveDuplicated = [];
  29833. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  29834. var tickValue = currentLevelTicks[i_1].value;
  29835. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  29836. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  29837. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  29838. tickCount++;
  29839. }
  29840. }
  29841. }
  29842. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  29843. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  29844. break;
  29845. } // Only treat primary time unit as one level.
  29846. levelsTicks.push(levelTicksRemoveDuplicated);
  29847. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  29848. break;
  29849. }
  29850. } // Reset if next unitName is primary
  29851. currentLevelTicks = [];
  29852. }
  29853. }
  29854. if ("development" !== 'production') {
  29855. if (iter >= safeLimit) {
  29856. warn('Exceed safe limit.');
  29857. }
  29858. }
  29859. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  29860. return filter(levelTicks, function (tick) {
  29861. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  29862. });
  29863. }), function (levelTicks) {
  29864. return levelTicks.length > 0;
  29865. });
  29866. var ticks = [];
  29867. var maxLevel = levelsTicksInExtent.length - 1;
  29868. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  29869. var levelTicks = levelsTicksInExtent[i];
  29870. for (var k = 0; k < levelTicks.length; ++k) {
  29871. ticks.push({
  29872. value: levelTicks[k].value,
  29873. level: maxLevel - i
  29874. });
  29875. }
  29876. }
  29877. ticks.sort(function (a, b) {
  29878. return a.value - b.value;
  29879. }); // Remove duplicates
  29880. var result = [];
  29881. for (var i = 0; i < ticks.length; ++i) {
  29882. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  29883. result.push(ticks[i]);
  29884. }
  29885. }
  29886. return result;
  29887. }
  29888. Scale.registerClass(TimeScale);
  29889. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  29890. var intervalScaleProto = IntervalScale.prototype;
  29891. var roundingErrorFix = round;
  29892. var mathFloor = Math.floor;
  29893. var mathCeil = Math.ceil;
  29894. var mathPow$1 = Math.pow;
  29895. var mathLog = Math.log;
  29896. var LogScale =
  29897. /** @class */
  29898. function (_super) {
  29899. __extends(LogScale, _super);
  29900. function LogScale() {
  29901. var _this = _super !== null && _super.apply(this, arguments) || this;
  29902. _this.type = 'log';
  29903. _this.base = 10;
  29904. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  29905. _this._interval = 0;
  29906. return _this;
  29907. }
  29908. /**
  29909. * @param Whether expand the ticks to niced extent.
  29910. */
  29911. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  29912. var originalScale = this._originalScale;
  29913. var extent = this._extent;
  29914. var originalExtent = originalScale.getExtent();
  29915. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  29916. return map(ticks, function (tick) {
  29917. var val = tick.value;
  29918. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  29919. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  29920. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  29921. return {
  29922. value: powVal
  29923. };
  29924. }, this);
  29925. };
  29926. LogScale.prototype.setExtent = function (start, end) {
  29927. var base = this.base;
  29928. start = mathLog(start) / mathLog(base);
  29929. end = mathLog(end) / mathLog(base);
  29930. intervalScaleProto.setExtent.call(this, start, end);
  29931. };
  29932. /**
  29933. * @return {number} end
  29934. */
  29935. LogScale.prototype.getExtent = function () {
  29936. var base = this.base;
  29937. var extent = scaleProto.getExtent.call(this);
  29938. extent[0] = mathPow$1(base, extent[0]);
  29939. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  29940. var originalScale = this._originalScale;
  29941. var originalExtent = originalScale.getExtent();
  29942. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  29943. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  29944. return extent;
  29945. };
  29946. LogScale.prototype.unionExtent = function (extent) {
  29947. this._originalScale.unionExtent(extent);
  29948. var base = this.base;
  29949. extent[0] = mathLog(extent[0]) / mathLog(base);
  29950. extent[1] = mathLog(extent[1]) / mathLog(base);
  29951. scaleProto.unionExtent.call(this, extent);
  29952. };
  29953. LogScale.prototype.unionExtentFromData = function (data, dim) {
  29954. // TODO
  29955. // filter value that <= 0
  29956. this.unionExtent(data.getApproximateExtent(dim));
  29957. };
  29958. /**
  29959. * Update interval and extent of intervals for nice ticks
  29960. * @param approxTickNum default 10 Given approx tick number
  29961. */
  29962. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  29963. approxTickNum = approxTickNum || 10;
  29964. var extent = this._extent;
  29965. var span = extent[1] - extent[0];
  29966. if (span === Infinity || span <= 0) {
  29967. return;
  29968. }
  29969. var interval = quantity(span);
  29970. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  29971. if (err <= 0.5) {
  29972. interval *= 10;
  29973. } // Interval should be integer
  29974. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  29975. interval *= 10;
  29976. }
  29977. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  29978. this._interval = interval;
  29979. this._niceExtent = niceExtent;
  29980. };
  29981. LogScale.prototype.calcNiceExtent = function (opt) {
  29982. intervalScaleProto.calcNiceExtent.call(this, opt);
  29983. this._fixMin = opt.fixMin;
  29984. this._fixMax = opt.fixMax;
  29985. };
  29986. LogScale.prototype.parse = function (val) {
  29987. return val;
  29988. };
  29989. LogScale.prototype.contain = function (val) {
  29990. val = mathLog(val) / mathLog(this.base);
  29991. return contain$1(val, this._extent);
  29992. };
  29993. LogScale.prototype.normalize = function (val) {
  29994. val = mathLog(val) / mathLog(this.base);
  29995. return normalize$1(val, this._extent);
  29996. };
  29997. LogScale.prototype.scale = function (val) {
  29998. val = scale$2(val, this._extent);
  29999. return mathPow$1(this.base, val);
  30000. };
  30001. LogScale.type = 'log';
  30002. return LogScale;
  30003. }(Scale);
  30004. var proto = LogScale.prototype;
  30005. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  30006. proto.getLabel = intervalScaleProto.getLabel;
  30007. function fixRoundingError(val, originalVal) {
  30008. return roundingErrorFix(val, getPrecision(originalVal));
  30009. }
  30010. Scale.registerClass(LogScale);
  30011. var ScaleRawExtentInfo =
  30012. /** @class */
  30013. function () {
  30014. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  30015. originalExtent) {
  30016. this._prepareParams(scale, model, originalExtent);
  30017. }
  30018. /**
  30019. * Parameters depending on ouside (like model, user callback)
  30020. * are prepared and fixed here.
  30021. */
  30022. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  30023. dataExtent) {
  30024. if (dataExtent[1] < dataExtent[0]) {
  30025. dataExtent = [NaN, NaN];
  30026. }
  30027. this._dataMin = dataExtent[0];
  30028. this._dataMax = dataExtent[1];
  30029. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  30030. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  30031. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  30032. if (isFunction(modelMinRaw)) {
  30033. // This callback alway provide users the full data extent (before data filtered).
  30034. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  30035. min: dataExtent[0],
  30036. max: dataExtent[1]
  30037. }));
  30038. } else if (modelMinRaw !== 'dataMin') {
  30039. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  30040. }
  30041. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  30042. if (isFunction(modelMaxRaw)) {
  30043. // This callback alway provide users the full data extent (before data filtered).
  30044. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  30045. min: dataExtent[0],
  30046. max: dataExtent[1]
  30047. }));
  30048. } else if (modelMaxRaw !== 'dataMax') {
  30049. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  30050. }
  30051. if (isOrdinal) {
  30052. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  30053. // and progressive rendering is using, here the category result might just only contain
  30054. // the processed chunk rather than the entire result.
  30055. this._axisDataLen = model.getCategories().length;
  30056. } else {
  30057. var boundaryGap = model.get('boundaryGap');
  30058. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  30059. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  30060. if ("development" !== 'production') {
  30061. 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.');
  30062. }
  30063. this._boundaryGapInner = [0, 0];
  30064. } else {
  30065. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  30066. }
  30067. }
  30068. };
  30069. /**
  30070. * Calculate extent by prepared parameters.
  30071. * This method has no external dependency and can be called duplicatedly,
  30072. * getting the same result.
  30073. * If parameters changed, should call this method to recalcuate.
  30074. */
  30075. ScaleRawExtentInfo.prototype.calculate = function () {
  30076. // Notice: When min/max is not set (that is, when there are null/undefined,
  30077. // which is the most common case), these cases should be ensured:
  30078. // (1) For 'ordinal', show all axis.data.
  30079. // (2) For others:
  30080. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30081. // disabled).
  30082. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30083. // be the result that originalExtent enlarged by boundaryGap.
  30084. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30085. var isOrdinal = this._isOrdinal;
  30086. var dataMin = this._dataMin;
  30087. var dataMax = this._dataMax;
  30088. var axisDataLen = this._axisDataLen;
  30089. var boundaryGapInner = this._boundaryGapInner;
  30090. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  30091. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  30092. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  30093. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  30094. var minFixed = min != null;
  30095. var maxFixed = max != null;
  30096. if (min == null) {
  30097. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  30098. }
  30099. if (max == null) {
  30100. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  30101. }
  30102. (min == null || !isFinite(min)) && (min = NaN);
  30103. (max == null || !isFinite(max)) && (max = NaN);
  30104. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  30105. if (this._needCrossZero) {
  30106. // Axis is over zero and min is not set
  30107. if (min > 0 && max > 0 && !minFixed) {
  30108. min = 0; // minFixed = true;
  30109. } // Axis is under zero and max is not set
  30110. if (min < 0 && max < 0 && !maxFixed) {
  30111. max = 0; // maxFixed = true;
  30112. } // PENDING:
  30113. // When `needCrossZero` and all data is positive/negative, should it be ensured
  30114. // that the results processed by boundaryGap are positive/negative?
  30115. // If so, here `minFixed`/`maxFixed` need to be set.
  30116. }
  30117. var determinedMin = this._determinedMin;
  30118. var determinedMax = this._determinedMax;
  30119. if (determinedMin != null) {
  30120. min = determinedMin;
  30121. minFixed = true;
  30122. }
  30123. if (determinedMax != null) {
  30124. max = determinedMax;
  30125. maxFixed = true;
  30126. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  30127. // `NaN` means min/max axis is blank.
  30128. return {
  30129. min: min,
  30130. max: max,
  30131. minFixed: minFixed,
  30132. maxFixed: maxFixed,
  30133. isBlank: isBlank
  30134. };
  30135. };
  30136. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  30137. if ("development" !== 'production') {
  30138. assert(!this.frozen);
  30139. }
  30140. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  30141. };
  30142. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  30143. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  30144. if ("development" !== 'production') {
  30145. assert(!this.frozen // Earse them usually means logic flaw.
  30146. && this[attr] == null);
  30147. }
  30148. this[attr] = val;
  30149. };
  30150. ScaleRawExtentInfo.prototype.freeze = function () {
  30151. // @ts-ignore
  30152. this.frozen = true;
  30153. };
  30154. return ScaleRawExtentInfo;
  30155. }();
  30156. var DETERMINED_MIN_MAX_ATTR = {
  30157. min: '_determinedMin',
  30158. max: '_determinedMax'
  30159. };
  30160. var DATA_MIN_MAX_ATTR = {
  30161. min: '_dataMin',
  30162. max: '_dataMax'
  30163. };
  30164. /**
  30165. * Get scale min max and related info only depends on model settings.
  30166. * This method can be called after coordinate system created.
  30167. * For example, in data processing stage.
  30168. *
  30169. * Scale extent info probably be required multiple times during a workflow.
  30170. * For example:
  30171. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  30172. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  30173. * (3) `coordSys.update` use it to finally decide the scale extent.
  30174. * But the callback of `min`/`max` should not be called multiple times.
  30175. * The code below should not be implemented repeatedly either.
  30176. * So we cache the result in the scale instance, which will be recreated at the begining
  30177. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  30178. */
  30179. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  30180. originalExtent) {
  30181. // Do not permit to recreate.
  30182. var rawExtentInfo = scale.rawExtentInfo;
  30183. if (rawExtentInfo) {
  30184. return rawExtentInfo;
  30185. }
  30186. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  30187. scale.rawExtentInfo = rawExtentInfo;
  30188. return rawExtentInfo;
  30189. }
  30190. function parseAxisModelMinMax(scale, minMax) {
  30191. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  30192. }
  30193. /**
  30194. * Get axis scale extent before niced.
  30195. * Item of returned array can only be number (including Infinity and NaN).
  30196. *
  30197. * Caution:
  30198. * Precondition of calling this method:
  30199. * The scale extent has been initialized using series data extent via
  30200. * `scale.setExtent` or `scale.unionExtentFromData`;
  30201. */
  30202. function getScaleExtent(scale, model) {
  30203. var scaleType = scale.type;
  30204. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  30205. scale.setBlank(rawExtentResult.isBlank);
  30206. var min = rawExtentResult.min;
  30207. var max = rawExtentResult.max; // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30208. // is base axis
  30209. // FIXME
  30210. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30211. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30212. // Should not depend on series type `bar`?
  30213. // (3) Fix that might overlap when using dataZoom.
  30214. // (4) Consider other chart types using `barGrid`?
  30215. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30216. var ecModel = model.ecModel;
  30217. if (ecModel && scaleType === 'time'
  30218. /*|| scaleType === 'interval' */
  30219. ) {
  30220. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30221. var isBaseAxisAndHasBarSeries_1 = false;
  30222. each(barSeriesModels, function (seriesModel) {
  30223. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  30224. });
  30225. if (isBaseAxisAndHasBarSeries_1) {
  30226. // Calculate placement of bars on axis. TODO should be decoupled
  30227. // with barLayout
  30228. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  30229. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30230. min = adjustedScale.min;
  30231. max = adjustedScale.max;
  30232. }
  30233. }
  30234. return {
  30235. extent: [min, max],
  30236. // "fix" means "fixed", the value should not be
  30237. // changed in the subsequent steps.
  30238. fixMin: rawExtentResult.minFixed,
  30239. fixMax: rawExtentResult.maxFixed
  30240. };
  30241. }
  30242. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  30243. barWidthAndOffset) {
  30244. // Get Axis Length
  30245. var axisExtent = model.axis.getExtent();
  30246. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  30247. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30248. if (barsOnCurrentAxis === undefined) {
  30249. return {
  30250. min: min,
  30251. max: max
  30252. };
  30253. }
  30254. var minOverflow = Infinity;
  30255. each(barsOnCurrentAxis, function (item) {
  30256. minOverflow = Math.min(item.offset, minOverflow);
  30257. });
  30258. var maxOverflow = -Infinity;
  30259. each(barsOnCurrentAxis, function (item) {
  30260. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30261. });
  30262. minOverflow = Math.abs(minOverflow);
  30263. maxOverflow = Math.abs(maxOverflow);
  30264. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  30265. var oldRange = max - min;
  30266. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  30267. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  30268. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30269. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30270. return {
  30271. min: min,
  30272. max: max
  30273. };
  30274. } // Precondition of calling this method:
  30275. // The scale extent has been initailized using series data extent via
  30276. // `scale.setExtent` or `scale.unionExtentFromData`;
  30277. function niceScaleExtent(scale, inModel) {
  30278. var model = inModel;
  30279. var extentInfo = getScaleExtent(scale, model);
  30280. var extent = extentInfo.extent;
  30281. var splitNumber = model.get('splitNumber');
  30282. if (scale instanceof LogScale) {
  30283. scale.base = model.get('logBase');
  30284. }
  30285. var scaleType = scale.type;
  30286. var interval = model.get('interval');
  30287. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  30288. scale.setExtent(extent[0], extent[1]);
  30289. scale.calcNiceExtent({
  30290. splitNumber: splitNumber,
  30291. fixMin: extentInfo.fixMin,
  30292. fixMax: extentInfo.fixMax,
  30293. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  30294. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  30295. }); // If some one specified the min, max. And the default calculated interval
  30296. // is not good enough. He can specify the interval. It is often appeared
  30297. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30298. // to be 60.
  30299. // FIXME
  30300. if (interval != null) {
  30301. scale.setInterval && scale.setInterval(interval);
  30302. }
  30303. }
  30304. /**
  30305. * @param axisType Default retrieve from model.type
  30306. */
  30307. function createScaleByModel(model, axisType) {
  30308. axisType = axisType || model.get('type');
  30309. if (axisType) {
  30310. switch (axisType) {
  30311. // Buildin scale
  30312. case 'category':
  30313. return new OrdinalScale({
  30314. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  30315. extent: [Infinity, -Infinity]
  30316. });
  30317. case 'time':
  30318. return new TimeScale({
  30319. locale: model.ecModel.getLocaleModel(),
  30320. useUTC: model.ecModel.get('useUTC')
  30321. });
  30322. default:
  30323. // case 'value'/'interval', 'log', or others.
  30324. return new (Scale.getClass(axisType) || IntervalScale)();
  30325. }
  30326. }
  30327. }
  30328. /**
  30329. * Check if the axis cross 0
  30330. */
  30331. function ifAxisCrossZero(axis) {
  30332. var dataExtent = axis.scale.getExtent();
  30333. var min = dataExtent[0];
  30334. var max = dataExtent[1];
  30335. return !(min > 0 && max > 0 || min < 0 && max < 0);
  30336. }
  30337. /**
  30338. * @param axis
  30339. * @return Label formatter function.
  30340. * param: {number} tickValue,
  30341. * param: {number} idx, the index in all ticks.
  30342. * If category axis, this param is not required.
  30343. * return: {string} label string.
  30344. */
  30345. function makeLabelFormatter(axis) {
  30346. var labelFormatter = axis.getLabelModel().get('formatter');
  30347. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30348. if (axis.scale.type === 'time') {
  30349. return function (tpl) {
  30350. return function (tick, idx) {
  30351. return axis.scale.getFormattedLabel(tick, idx, tpl);
  30352. };
  30353. }(labelFormatter);
  30354. } else if (isString(labelFormatter)) {
  30355. return function (tpl) {
  30356. return function (tick) {
  30357. // For category axis, get raw value; for numeric axis,
  30358. // get formatted label like '1,333,444'.
  30359. var label = axis.scale.getLabel(tick);
  30360. var text = tpl.replace('{value}', label != null ? label : '');
  30361. return text;
  30362. };
  30363. }(labelFormatter);
  30364. } else if (isFunction(labelFormatter)) {
  30365. return function (cb) {
  30366. return function (tick, idx) {
  30367. // The original intention of `idx` is "the index of the tick in all ticks".
  30368. // But the previous implementation of category axis do not consider the
  30369. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30370. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30371. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30372. // the definition here for back compatibility.
  30373. if (categoryTickStart != null) {
  30374. idx = tick.value - categoryTickStart;
  30375. }
  30376. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  30377. level: tick.level
  30378. } : null);
  30379. };
  30380. }(labelFormatter);
  30381. } else {
  30382. return function (tick) {
  30383. return axis.scale.getLabel(tick);
  30384. };
  30385. }
  30386. }
  30387. function getAxisRawValue(axis, tick) {
  30388. // In category axis with data zoom, tick is not the original
  30389. // index of axis.data. So tick should not be exposed to user
  30390. // in category axis.
  30391. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  30392. }
  30393. /**
  30394. * @param axis
  30395. * @return Be null/undefined if no labels.
  30396. */
  30397. function estimateLabelUnionRect(axis) {
  30398. var axisModel = axis.model;
  30399. var scale = axis.scale;
  30400. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  30401. return;
  30402. }
  30403. var realNumberScaleTicks;
  30404. var tickCount;
  30405. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  30406. if (scale instanceof OrdinalScale) {
  30407. tickCount = scale.count();
  30408. } else {
  30409. realNumberScaleTicks = scale.getTicks();
  30410. tickCount = realNumberScaleTicks.length;
  30411. }
  30412. var axisLabelModel = axis.getLabelModel();
  30413. var labelFormatter = makeLabelFormatter(axis);
  30414. var rect;
  30415. var step = 1; // Simple optimization for large amount of labels
  30416. if (tickCount > 40) {
  30417. step = Math.ceil(tickCount / 40);
  30418. }
  30419. for (var i = 0; i < tickCount; i += step) {
  30420. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  30421. value: categoryScaleExtent[0] + i
  30422. };
  30423. var label = labelFormatter(tick, i);
  30424. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  30425. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  30426. rect ? rect.union(singleRect) : rect = singleRect;
  30427. }
  30428. return rect;
  30429. }
  30430. function rotateTextRect(textRect, rotate) {
  30431. var rotateRadians = rotate * Math.PI / 180;
  30432. var beforeWidth = textRect.width;
  30433. var beforeHeight = textRect.height;
  30434. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  30435. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  30436. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  30437. return rotatedRect;
  30438. }
  30439. /**
  30440. * @param model axisLabelModel or axisTickModel
  30441. * @return {number|String} Can be null|'auto'|number|function
  30442. */
  30443. function getOptionCategoryInterval(model) {
  30444. var interval = model.get('interval');
  30445. return interval == null ? 'auto' : interval;
  30446. }
  30447. /**
  30448. * Set `categoryInterval` as 0 implicitly indicates that
  30449. * show all labels reguardless of overlap.
  30450. * @param {Object} axis axisModel.axis
  30451. */
  30452. function shouldShowAllLabels(axis) {
  30453. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  30454. }
  30455. function getDataDimensionsOnAxis(data, axisDim) {
  30456. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  30457. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  30458. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  30459. // there has been stacked result dim?
  30460. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  30461. // For example, the extent of the original dimension
  30462. // is [0.1, 0.5], the extent of the `stackResultDimension`
  30463. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  30464. // because there is no graphic corresponding to [0.1, 0.5].
  30465. // See the case in `test/area-stack.html` `main1`, where area line
  30466. // stack needs `yAxis` not start from 0.
  30467. dataDimMap[getStackedDimension(data, dataDim)] = true;
  30468. });
  30469. return keys(dataDimMap);
  30470. }
  30471. /*
  30472. * Licensed to the Apache Software Foundation (ASF) under one
  30473. * or more contributor license agreements. See the NOTICE file
  30474. * distributed with this work for additional information
  30475. * regarding copyright ownership. The ASF licenses this file
  30476. * to you under the Apache License, Version 2.0 (the
  30477. * "License"); you may not use this file except in compliance
  30478. * with the License. You may obtain a copy of the License at
  30479. *
  30480. * http://www.apache.org/licenses/LICENSE-2.0
  30481. *
  30482. * Unless required by applicable law or agreed to in writing,
  30483. * software distributed under the License is distributed on an
  30484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30485. * KIND, either express or implied. See the License for the
  30486. * specific language governing permissions and limitations
  30487. * under the License.
  30488. */
  30489. /**
  30490. * AUTO-GENERATED FILE. DO NOT MODIFY.
  30491. */
  30492. /*
  30493. * Licensed to the Apache Software Foundation (ASF) under one
  30494. * or more contributor license agreements. See the NOTICE file
  30495. * distributed with this work for additional information
  30496. * regarding copyright ownership. The ASF licenses this file
  30497. * to you under the Apache License, Version 2.0 (the
  30498. * "License"); you may not use this file except in compliance
  30499. * with the License. You may obtain a copy of the License at
  30500. *
  30501. * http://www.apache.org/licenses/LICENSE-2.0
  30502. *
  30503. * Unless required by applicable law or agreed to in writing,
  30504. * software distributed under the License is distributed on an
  30505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30506. * KIND, either express or implied. See the License for the
  30507. * specific language governing permissions and limitations
  30508. * under the License.
  30509. */
  30510. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  30511. var AxisModelCommonMixin =
  30512. /** @class */
  30513. function () {
  30514. function AxisModelCommonMixin() {}
  30515. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  30516. var option = this.option;
  30517. return !option.scale;
  30518. };
  30519. /**
  30520. * Should be implemented by each axis model if necessary.
  30521. * @return coordinate system model
  30522. */
  30523. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  30524. return;
  30525. };
  30526. return AxisModelCommonMixin;
  30527. }();
  30528. /**
  30529. * Create a muti dimension List structure from seriesModel.
  30530. */
  30531. function createList(seriesModel) {
  30532. return createSeriesData(null, seriesModel);
  30533. } // export function createGraph(seriesModel) {
  30534. var dataStack$1 = {
  30535. isDimensionStacked: isDimensionStacked,
  30536. enableDataStack: enableDataStack,
  30537. getStackedDimension: getStackedDimension
  30538. };
  30539. /**
  30540. * Create scale
  30541. * @param {Array.<number>} dataExtent
  30542. * @param {Object|module:echarts/Model} option If `optoin.type`
  30543. * is secified, it can only be `'value'` currently.
  30544. */
  30545. function createScale(dataExtent, option) {
  30546. var axisModel = option;
  30547. if (!(option instanceof Model)) {
  30548. axisModel = new Model(option); // FIXME
  30549. // Currently AxisModelCommonMixin has nothing to do with the
  30550. // the requirements of `axisHelper.createScaleByModel`. For
  30551. // example the method `getCategories` and `getOrdinalMeta`
  30552. // are required for `'category'` axis, and ecModel are required
  30553. // for `'time'` axis. But occationally echarts-gl happened
  30554. // to only use `'value'` axis.
  30555. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  30556. }
  30557. var scale = createScaleByModel(axisModel);
  30558. scale.setExtent(dataExtent[0], dataExtent[1]);
  30559. niceScaleExtent(scale, axisModel);
  30560. return scale;
  30561. }
  30562. /**
  30563. * Mixin common methods to axis model,
  30564. *
  30565. * Inlcude methods
  30566. * `getFormattedLabels() => Array.<string>`
  30567. * `getCategories() => Array.<string>`
  30568. * `getMin(origin: boolean) => number`
  30569. * `getMax(origin: boolean) => number`
  30570. * `getNeedCrossZero() => boolean`
  30571. */
  30572. function mixinAxisModelCommonMethods(Model) {
  30573. mixin(Model, AxisModelCommonMixin);
  30574. }
  30575. function createTextStyle$1(textStyleModel, opts) {
  30576. opts = opts || {};
  30577. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  30578. }
  30579. var helper = /*#__PURE__*/Object.freeze({
  30580. __proto__: null,
  30581. createList: createList,
  30582. getLayoutRect: getLayoutRect,
  30583. dataStack: dataStack$1,
  30584. createScale: createScale,
  30585. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  30586. getECData: getECData,
  30587. createTextStyle: createTextStyle$1,
  30588. createDimensions: createDimensions,
  30589. createSymbol: createSymbol,
  30590. enableHoverEmphasis: enableHoverEmphasis
  30591. });
  30592. var EPSILON$3 = 1e-8;
  30593. function isAroundEqual$1(a, b) {
  30594. return Math.abs(a - b) < EPSILON$3;
  30595. }
  30596. function contain$2(points, x, y) {
  30597. var w = 0;
  30598. var p = points[0];
  30599. if (!p) {
  30600. return false;
  30601. }
  30602. for (var i = 1; i < points.length; i++) {
  30603. var p2 = points[i];
  30604. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  30605. p = p2;
  30606. }
  30607. var p0 = points[0];
  30608. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  30609. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  30610. }
  30611. return w !== 0;
  30612. }
  30613. var TMP_TRANSFORM = [];
  30614. function transformPoints(points, transform) {
  30615. for (var p = 0; p < points.length; p++) {
  30616. applyTransform(points[p], points[p], transform);
  30617. }
  30618. }
  30619. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  30620. for (var i = 0; i < points.length; i++) {
  30621. var p = points[i];
  30622. if (projection) {
  30623. // projection may return null point.
  30624. p = projection.project(p);
  30625. }
  30626. if (p && isFinite(p[0]) && isFinite(p[1])) {
  30627. min(min$1, min$1, p);
  30628. max(max$1, max$1, p);
  30629. }
  30630. }
  30631. }
  30632. function centroid(points) {
  30633. var signedArea = 0;
  30634. var cx = 0;
  30635. var cy = 0;
  30636. var len = points.length;
  30637. var x0 = points[len - 1][0];
  30638. var y0 = points[len - 1][1]; // Polygon should been closed.
  30639. for (var i = 0; i < len; i++) {
  30640. var x1 = points[i][0];
  30641. var y1 = points[i][1];
  30642. var a = x0 * y1 - x1 * y0;
  30643. signedArea += a;
  30644. cx += (x0 + x1) * a;
  30645. cy += (y0 + y1) * a;
  30646. x0 = x1;
  30647. y0 = y1;
  30648. }
  30649. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  30650. }
  30651. var Region =
  30652. /** @class */
  30653. function () {
  30654. function Region(name) {
  30655. this.name = name;
  30656. }
  30657. Region.prototype.setCenter = function (center) {
  30658. this._center = center;
  30659. };
  30660. /**
  30661. * Get center point in data unit. That is,
  30662. * for GeoJSONRegion, the unit is lat/lng,
  30663. * for GeoSVGRegion, the unit is SVG local coord.
  30664. */
  30665. Region.prototype.getCenter = function () {
  30666. var center = this._center;
  30667. if (!center) {
  30668. // In most cases there are no need to calculate this center.
  30669. // So calculate only when called.
  30670. center = this._center = this.calcCenter();
  30671. }
  30672. return center;
  30673. };
  30674. return Region;
  30675. }();
  30676. var GeoJSONPolygonGeometry =
  30677. /** @class */
  30678. function () {
  30679. function GeoJSONPolygonGeometry(exterior, interiors) {
  30680. this.type = 'polygon';
  30681. this.exterior = exterior;
  30682. this.interiors = interiors;
  30683. }
  30684. return GeoJSONPolygonGeometry;
  30685. }();
  30686. var GeoJSONLineStringGeometry =
  30687. /** @class */
  30688. function () {
  30689. function GeoJSONLineStringGeometry(points) {
  30690. this.type = 'linestring';
  30691. this.points = points;
  30692. }
  30693. return GeoJSONLineStringGeometry;
  30694. }();
  30695. var GeoJSONRegion =
  30696. /** @class */
  30697. function (_super) {
  30698. __extends(GeoJSONRegion, _super);
  30699. function GeoJSONRegion(name, geometries, cp) {
  30700. var _this = _super.call(this, name) || this;
  30701. _this.type = 'geoJSON';
  30702. _this.geometries = geometries;
  30703. _this._center = cp && [cp[0], cp[1]];
  30704. return _this;
  30705. }
  30706. GeoJSONRegion.prototype.calcCenter = function () {
  30707. var geometries = this.geometries;
  30708. var largestGeo;
  30709. var largestGeoSize = 0;
  30710. for (var i = 0; i < geometries.length; i++) {
  30711. var geo = geometries[i];
  30712. var exterior = geo.exterior; // Simple trick to use points count instead of polygon area as region size.
  30713. // Ignore linestring
  30714. var size = exterior && exterior.length;
  30715. if (size > largestGeoSize) {
  30716. largestGeo = geo;
  30717. largestGeoSize = size;
  30718. }
  30719. }
  30720. if (largestGeo) {
  30721. return centroid(largestGeo.exterior);
  30722. } // from bounding rect by default.
  30723. var rect = this.getBoundingRect();
  30724. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  30725. };
  30726. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  30727. var rect = this._rect; // Always recalculate if using projection.
  30728. if (rect && !projection) {
  30729. return rect;
  30730. }
  30731. var min = [Infinity, Infinity];
  30732. var max = [-Infinity, -Infinity];
  30733. var geometries = this.geometries;
  30734. each(geometries, function (geo) {
  30735. if (geo.type === 'polygon') {
  30736. // Doesn't consider hole
  30737. updateBBoxFromPoints(geo.exterior, min, max, projection);
  30738. } else {
  30739. each(geo.points, function (points) {
  30740. updateBBoxFromPoints(points, min, max, projection);
  30741. });
  30742. }
  30743. }); // Normalie invalid bounding.
  30744. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  30745. min[0] = min[1] = max[0] = max[1] = 0;
  30746. }
  30747. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  30748. if (!projection) {
  30749. this._rect = rect;
  30750. }
  30751. return rect;
  30752. };
  30753. GeoJSONRegion.prototype.contain = function (coord) {
  30754. var rect = this.getBoundingRect();
  30755. var geometries = this.geometries;
  30756. if (!rect.contain(coord[0], coord[1])) {
  30757. return false;
  30758. }
  30759. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  30760. var geo = geometries[i]; // Only support polygon.
  30761. if (geo.type !== 'polygon') {
  30762. continue;
  30763. }
  30764. var exterior = geo.exterior;
  30765. var interiors = geo.interiors;
  30766. if (contain$2(exterior, coord[0], coord[1])) {
  30767. // Not in the region if point is in the hole.
  30768. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  30769. if (contain$2(interiors[k], coord[0], coord[1])) {
  30770. continue loopGeo;
  30771. }
  30772. }
  30773. return true;
  30774. }
  30775. }
  30776. return false;
  30777. };
  30778. /**
  30779. * Transform the raw coords to target bounding.
  30780. * @param x
  30781. * @param y
  30782. * @param width
  30783. * @param height
  30784. */
  30785. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  30786. var rect = this.getBoundingRect();
  30787. var aspect = rect.width / rect.height;
  30788. if (!width) {
  30789. width = aspect * height;
  30790. } else if (!height) {
  30791. height = width / aspect;
  30792. }
  30793. var target = new BoundingRect(x, y, width, height);
  30794. var transform = rect.calculateTransform(target);
  30795. var geometries = this.geometries;
  30796. for (var i = 0; i < geometries.length; i++) {
  30797. var geo = geometries[i];
  30798. if (geo.type === 'polygon') {
  30799. transformPoints(geo.exterior, transform);
  30800. each(geo.interiors, function (interior) {
  30801. transformPoints(interior, transform);
  30802. });
  30803. } else {
  30804. each(geo.points, function (points) {
  30805. transformPoints(points, transform);
  30806. });
  30807. }
  30808. }
  30809. rect = this._rect;
  30810. rect.copy(target); // Update center
  30811. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  30812. };
  30813. GeoJSONRegion.prototype.cloneShallow = function (name) {
  30814. name == null && (name = this.name);
  30815. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  30816. newRegion._rect = this._rect;
  30817. newRegion.transformTo = null; // Simply avoid to be called.
  30818. return newRegion;
  30819. };
  30820. return GeoJSONRegion;
  30821. }(Region);
  30822. var GeoSVGRegion =
  30823. /** @class */
  30824. function (_super) {
  30825. __extends(GeoSVGRegion, _super);
  30826. function GeoSVGRegion(name, elOnlyForCalculate) {
  30827. var _this = _super.call(this, name) || this;
  30828. _this.type = 'geoSVG';
  30829. _this._elOnlyForCalculate = elOnlyForCalculate;
  30830. return _this;
  30831. }
  30832. GeoSVGRegion.prototype.calcCenter = function () {
  30833. var el = this._elOnlyForCalculate;
  30834. var rect = el.getBoundingRect();
  30835. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  30836. var mat = identity(TMP_TRANSFORM);
  30837. var target = el;
  30838. while (target && !target.isGeoSVGGraphicRoot) {
  30839. mul$1(mat, target.getLocalTransform(), mat);
  30840. target = target.parent;
  30841. }
  30842. invert(mat, mat);
  30843. applyTransform(center, center, mat);
  30844. return center;
  30845. };
  30846. return GeoSVGRegion;
  30847. }(Region);
  30848. function decode(json) {
  30849. if (!json.UTF8Encoding) {
  30850. return json;
  30851. }
  30852. var jsonCompressed = json;
  30853. var encodeScale = jsonCompressed.UTF8Scale;
  30854. if (encodeScale == null) {
  30855. encodeScale = 1024;
  30856. }
  30857. var features = jsonCompressed.features;
  30858. each(features, function (feature) {
  30859. var geometry = feature.geometry;
  30860. var encodeOffsets = geometry.encodeOffsets;
  30861. var coordinates = geometry.coordinates; // Geometry may be appeded manually in the script after json loaded.
  30862. // In this case this geometry is usually not encoded.
  30863. if (!encodeOffsets) {
  30864. return;
  30865. }
  30866. switch (geometry.type) {
  30867. case 'LineString':
  30868. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  30869. break;
  30870. case 'Polygon':
  30871. decodeRings(coordinates, encodeOffsets, encodeScale);
  30872. break;
  30873. case 'MultiLineString':
  30874. decodeRings(coordinates, encodeOffsets, encodeScale);
  30875. break;
  30876. case 'MultiPolygon':
  30877. each(coordinates, function (rings, idx) {
  30878. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  30879. });
  30880. }
  30881. }); // Has been decoded
  30882. jsonCompressed.UTF8Encoding = false;
  30883. return jsonCompressed;
  30884. }
  30885. function decodeRings(rings, encodeOffsets, encodeScale) {
  30886. for (var c = 0; c < rings.length; c++) {
  30887. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  30888. }
  30889. }
  30890. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  30891. var result = [];
  30892. var prevX = encodeOffsets[0];
  30893. var prevY = encodeOffsets[1];
  30894. for (var i = 0; i < coordinate.length; i += 2) {
  30895. var x = coordinate.charCodeAt(i) - 64;
  30896. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  30897. x = x >> 1 ^ -(x & 1);
  30898. y = y >> 1 ^ -(y & 1); // Delta deocding
  30899. x += prevX;
  30900. y += prevY;
  30901. prevX = x;
  30902. prevY = y; // Dequantize
  30903. result.push([x / encodeScale, y / encodeScale]);
  30904. }
  30905. return result;
  30906. }
  30907. function parseGeoJSON(geoJson, nameProperty) {
  30908. geoJson = decode(geoJson);
  30909. return map(filter(geoJson.features, function (featureObj) {
  30910. // Output of mapshaper may have geometry null
  30911. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  30912. }), function (featureObj) {
  30913. var properties = featureObj.properties;
  30914. var geo = featureObj.geometry;
  30915. var geometries = [];
  30916. switch (geo.type) {
  30917. case 'Polygon':
  30918. var coordinates = geo.coordinates; // According to the GeoJSON specification.
  30919. // First must be exterior, and the rest are all interior(holes).
  30920. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  30921. break;
  30922. case 'MultiPolygon':
  30923. each(geo.coordinates, function (item) {
  30924. if (item[0]) {
  30925. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  30926. }
  30927. });
  30928. break;
  30929. case 'LineString':
  30930. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  30931. break;
  30932. case 'MultiLineString':
  30933. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  30934. }
  30935. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  30936. region.properties = properties;
  30937. return region;
  30938. });
  30939. }
  30940. var number = /*#__PURE__*/Object.freeze({
  30941. __proto__: null,
  30942. linearMap: linearMap,
  30943. round: round,
  30944. asc: asc,
  30945. getPrecision: getPrecision,
  30946. getPrecisionSafe: getPrecisionSafe,
  30947. getPixelPrecision: getPixelPrecision,
  30948. getPercentWithPrecision: getPercentWithPrecision,
  30949. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  30950. remRadian: remRadian,
  30951. isRadianAroundZero: isRadianAroundZero,
  30952. parseDate: parseDate,
  30953. quantity: quantity,
  30954. quantityExponent: quantityExponent,
  30955. nice: nice,
  30956. quantile: quantile,
  30957. reformIntervals: reformIntervals,
  30958. isNumeric: isNumeric,
  30959. numericToNumber: numericToNumber
  30960. });
  30961. var time = /*#__PURE__*/Object.freeze({
  30962. __proto__: null,
  30963. parse: parseDate,
  30964. format: format
  30965. });
  30966. var graphic = /*#__PURE__*/Object.freeze({
  30967. __proto__: null,
  30968. extendShape: extendShape,
  30969. extendPath: extendPath,
  30970. makePath: makePath,
  30971. makeImage: makeImage,
  30972. mergePath: mergePath$1,
  30973. resizePath: resizePath,
  30974. createIcon: createIcon,
  30975. updateProps: updateProps,
  30976. initProps: initProps,
  30977. getTransform: getTransform,
  30978. clipPointsByRect: clipPointsByRect,
  30979. clipRectByRect: clipRectByRect,
  30980. registerShape: registerShape,
  30981. getShapeClass: getShapeClass,
  30982. Group: Group,
  30983. Image: ZRImage,
  30984. Text: ZRText,
  30985. Circle: Circle,
  30986. Ellipse: Ellipse,
  30987. Sector: Sector,
  30988. Ring: Ring,
  30989. Polygon: Polygon,
  30990. Polyline: Polyline,
  30991. Rect: Rect,
  30992. Line: Line,
  30993. BezierCurve: BezierCurve,
  30994. Arc: Arc,
  30995. IncrementalDisplayable: IncrementalDisplayable,
  30996. CompoundPath: CompoundPath,
  30997. LinearGradient: LinearGradient,
  30998. RadialGradient: RadialGradient,
  30999. BoundingRect: BoundingRect
  31000. });
  31001. var format$1 = /*#__PURE__*/Object.freeze({
  31002. __proto__: null,
  31003. addCommas: addCommas,
  31004. toCamelCase: toCamelCase,
  31005. normalizeCssArray: normalizeCssArray$1,
  31006. encodeHTML: encodeHTML,
  31007. formatTpl: formatTpl,
  31008. getTooltipMarker: getTooltipMarker,
  31009. formatTime: formatTime,
  31010. capitalFirst: capitalFirst,
  31011. truncateText: truncateText,
  31012. getTextRect: getTextRect
  31013. });
  31014. var util$1 = /*#__PURE__*/Object.freeze({
  31015. __proto__: null,
  31016. map: map,
  31017. each: each,
  31018. indexOf: indexOf,
  31019. inherits: inherits,
  31020. reduce: reduce,
  31021. filter: filter,
  31022. bind: bind,
  31023. curry: curry,
  31024. isArray: isArray,
  31025. isString: isString,
  31026. isObject: isObject,
  31027. isFunction: isFunction,
  31028. extend: extend,
  31029. defaults: defaults,
  31030. clone: clone,
  31031. merge: merge
  31032. });
  31033. var inner$5 = makeInner();
  31034. function createAxisLabels(axis) {
  31035. // Only ordinal scale support tick interval
  31036. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  31037. }
  31038. /**
  31039. * @param {module:echats/coord/Axis} axis
  31040. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31041. * @return {Object} {
  31042. * ticks: Array.<number>
  31043. * tickCategoryInterval: number
  31044. * }
  31045. */
  31046. function createAxisTicks(axis, tickModel) {
  31047. // Only ordinal scale support tick interval
  31048. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  31049. ticks: map(axis.scale.getTicks(), function (tick) {
  31050. return tick.value;
  31051. })
  31052. };
  31053. }
  31054. function makeCategoryLabels(axis) {
  31055. var labelModel = axis.getLabelModel();
  31056. var result = makeCategoryLabelsActually(axis, labelModel);
  31057. return !labelModel.get('show') || axis.scale.isBlank() ? {
  31058. labels: [],
  31059. labelCategoryInterval: result.labelCategoryInterval
  31060. } : result;
  31061. }
  31062. function makeCategoryLabelsActually(axis, labelModel) {
  31063. var labelsCache = getListCache(axis, 'labels');
  31064. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31065. var result = listCacheGet(labelsCache, optionLabelInterval);
  31066. if (result) {
  31067. return result;
  31068. }
  31069. var labels;
  31070. var numericLabelInterval;
  31071. if (isFunction(optionLabelInterval)) {
  31072. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31073. } else {
  31074. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31075. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31076. } // Cache to avoid calling interval function repeatly.
  31077. return listCacheSet(labelsCache, optionLabelInterval, {
  31078. labels: labels,
  31079. labelCategoryInterval: numericLabelInterval
  31080. });
  31081. }
  31082. function makeCategoryTicks(axis, tickModel) {
  31083. var ticksCache = getListCache(axis, 'ticks');
  31084. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31085. var result = listCacheGet(ticksCache, optionTickInterval);
  31086. if (result) {
  31087. return result;
  31088. }
  31089. var ticks;
  31090. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  31091. // we should not return all ticks.
  31092. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31093. ticks = [];
  31094. }
  31095. if (isFunction(optionTickInterval)) {
  31096. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31097. } // Always use label interval by default despite label show. Consider this
  31098. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31099. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31100. else if (optionTickInterval === 'auto') {
  31101. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31102. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31103. ticks = map(labelsResult.labels, function (labelItem) {
  31104. return labelItem.tickValue;
  31105. });
  31106. } else {
  31107. tickCategoryInterval = optionTickInterval;
  31108. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31109. } // Cache to avoid calling interval function repeatly.
  31110. return listCacheSet(ticksCache, optionTickInterval, {
  31111. ticks: ticks,
  31112. tickCategoryInterval: tickCategoryInterval
  31113. });
  31114. }
  31115. function makeRealNumberLabels(axis) {
  31116. var ticks = axis.scale.getTicks();
  31117. var labelFormatter = makeLabelFormatter(axis);
  31118. return {
  31119. labels: map(ticks, function (tick, idx) {
  31120. return {
  31121. level: tick.level,
  31122. formattedLabel: labelFormatter(tick, idx),
  31123. rawLabel: axis.scale.getLabel(tick),
  31124. tickValue: tick.value
  31125. };
  31126. })
  31127. };
  31128. }
  31129. function getListCache(axis, prop) {
  31130. // Because key can be funciton, and cache size always be small, we use array cache.
  31131. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  31132. }
  31133. function listCacheGet(cache, key) {
  31134. for (var i = 0; i < cache.length; i++) {
  31135. if (cache[i].key === key) {
  31136. return cache[i].value;
  31137. }
  31138. }
  31139. }
  31140. function listCacheSet(cache, key, value) {
  31141. cache.push({
  31142. key: key,
  31143. value: value
  31144. });
  31145. return value;
  31146. }
  31147. function makeAutoCategoryInterval(axis) {
  31148. var result = inner$5(axis).autoInterval;
  31149. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  31150. }
  31151. /**
  31152. * Calculate interval for category axis ticks and labels.
  31153. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31154. * should be implemented in axis.
  31155. */
  31156. function calculateCategoryInterval(axis) {
  31157. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31158. var labelFormatter = makeLabelFormatter(axis);
  31159. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31160. var ordinalScale = axis.scale;
  31161. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  31162. // avoid generating a long array by `getTicks`
  31163. // in large category data case.
  31164. var tickCount = ordinalScale.count();
  31165. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31166. return 0;
  31167. }
  31168. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  31169. if (tickCount > 40) {
  31170. step = Math.max(1, Math.floor(tickCount / 40));
  31171. }
  31172. var tickValue = ordinalExtent[0];
  31173. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31174. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31175. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31176. var maxW = 0;
  31177. var maxH = 0; // Caution: Performance sensitive for large category data.
  31178. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31179. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31180. var width = 0;
  31181. var height = 0; // Not precise, do not consider align and vertical align
  31182. // and each distance from axis line yet.
  31183. var rect = getBoundingRect(labelFormatter({
  31184. value: tickValue
  31185. }), params.font, 'center', 'top'); // Magic number
  31186. width = rect.width * 1.3;
  31187. height = rect.height * 1.3; // Min size, void long loop.
  31188. maxW = Math.max(maxW, width, 7);
  31189. maxH = Math.max(maxH, height, 7);
  31190. }
  31191. var dw = maxW / unitW;
  31192. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  31193. isNaN(dw) && (dw = Infinity);
  31194. isNaN(dh) && (dh = Infinity);
  31195. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31196. var cache = inner$5(axis.model);
  31197. var axisExtent = axis.getExtent();
  31198. var lastAutoInterval = cache.lastAutoInterval;
  31199. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  31200. // otherwise the calculated interval might jitter when the zoom
  31201. // window size is close to the interval-changing size.
  31202. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  31203. // The jitter will cause that sometimes the displayed labels are
  31204. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  31205. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  31206. // point is not the same when zooming in or zooming out.
  31207. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  31208. // be used. Otherwise some hiden labels might not be shown again.
  31209. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  31210. interval = lastAutoInterval;
  31211. } // Only update cache if cache not used, otherwise the
  31212. // changing of interval is too insensitive.
  31213. else {
  31214. cache.lastTickCount = tickCount;
  31215. cache.lastAutoInterval = interval;
  31216. cache.axisExtent0 = axisExtent[0];
  31217. cache.axisExtent1 = axisExtent[1];
  31218. }
  31219. return interval;
  31220. }
  31221. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31222. var labelModel = axis.getLabelModel();
  31223. return {
  31224. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  31225. labelRotate: labelModel.get('rotate') || 0,
  31226. font: labelModel.getFont()
  31227. };
  31228. }
  31229. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31230. var labelFormatter = makeLabelFormatter(axis);
  31231. var ordinalScale = axis.scale;
  31232. var ordinalExtent = ordinalScale.getExtent();
  31233. var labelModel = axis.getLabelModel();
  31234. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  31235. var step = Math.max((categoryInterval || 0) + 1, 1);
  31236. var startTick = ordinalExtent[0];
  31237. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  31238. // while zooming and moving while interval > 0. Otherwise the selection
  31239. // of displayable ticks and symbols probably keep changing.
  31240. // 3 is empirical value.
  31241. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  31242. startTick = Math.round(Math.ceil(startTick / step) * step);
  31243. } // (1) Only add min max label here but leave overlap checking
  31244. // to render stage, which also ensure the returned list
  31245. // suitable for splitLine and splitArea rendering.
  31246. // (2) Scales except category always contain min max label so
  31247. // do not need to perform this process.
  31248. var showAllLabel = shouldShowAllLabels(axis);
  31249. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  31250. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31251. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31252. addItem(ordinalExtent[0]);
  31253. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  31254. var tickValue = startTick;
  31255. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31256. addItem(tickValue);
  31257. }
  31258. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  31259. addItem(ordinalExtent[1]);
  31260. }
  31261. function addItem(tickValue) {
  31262. var tickObj = {
  31263. value: tickValue
  31264. };
  31265. result.push(onlyTick ? tickValue : {
  31266. formattedLabel: labelFormatter(tickObj),
  31267. rawLabel: ordinalScale.getLabel(tickObj),
  31268. tickValue: tickValue
  31269. });
  31270. }
  31271. return result;
  31272. }
  31273. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  31274. var ordinalScale = axis.scale;
  31275. var labelFormatter = makeLabelFormatter(axis);
  31276. var result = [];
  31277. each(ordinalScale.getTicks(), function (tick) {
  31278. var rawLabel = ordinalScale.getLabel(tick);
  31279. var tickValue = tick.value;
  31280. if (categoryInterval(tick.value, rawLabel)) {
  31281. result.push(onlyTick ? tickValue : {
  31282. formattedLabel: labelFormatter(tick),
  31283. rawLabel: rawLabel,
  31284. tickValue: tickValue
  31285. });
  31286. }
  31287. });
  31288. return result;
  31289. }
  31290. var NORMALIZED_EXTENT = [0, 1];
  31291. /**
  31292. * Base class of Axis.
  31293. */
  31294. var Axis =
  31295. /** @class */
  31296. function () {
  31297. function Axis(dim, scale, extent) {
  31298. this.onBand = false;
  31299. this.inverse = false;
  31300. this.dim = dim;
  31301. this.scale = scale;
  31302. this._extent = extent || [0, 0];
  31303. }
  31304. /**
  31305. * If axis extent contain given coord
  31306. */
  31307. Axis.prototype.contain = function (coord) {
  31308. var extent = this._extent;
  31309. var min = Math.min(extent[0], extent[1]);
  31310. var max = Math.max(extent[0], extent[1]);
  31311. return coord >= min && coord <= max;
  31312. };
  31313. /**
  31314. * If axis extent contain given data
  31315. */
  31316. Axis.prototype.containData = function (data) {
  31317. return this.scale.contain(data);
  31318. };
  31319. /**
  31320. * Get coord extent.
  31321. */
  31322. Axis.prototype.getExtent = function () {
  31323. return this._extent.slice();
  31324. };
  31325. /**
  31326. * Get precision used for formatting
  31327. */
  31328. Axis.prototype.getPixelPrecision = function (dataExtent) {
  31329. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  31330. };
  31331. /**
  31332. * Set coord extent
  31333. */
  31334. Axis.prototype.setExtent = function (start, end) {
  31335. var extent = this._extent;
  31336. extent[0] = start;
  31337. extent[1] = end;
  31338. };
  31339. /**
  31340. * Convert data to coord. Data is the rank if it has an ordinal scale
  31341. */
  31342. Axis.prototype.dataToCoord = function (data, clamp) {
  31343. var extent = this._extent;
  31344. var scale = this.scale;
  31345. data = scale.normalize(data);
  31346. if (this.onBand && scale.type === 'ordinal') {
  31347. extent = extent.slice();
  31348. fixExtentWithBands(extent, scale.count());
  31349. }
  31350. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  31351. };
  31352. /**
  31353. * Convert coord to data. Data is the rank if it has an ordinal scale
  31354. */
  31355. Axis.prototype.coordToData = function (coord, clamp) {
  31356. var extent = this._extent;
  31357. var scale = this.scale;
  31358. if (this.onBand && scale.type === 'ordinal') {
  31359. extent = extent.slice();
  31360. fixExtentWithBands(extent, scale.count());
  31361. }
  31362. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  31363. return this.scale.scale(t);
  31364. };
  31365. /**
  31366. * Convert pixel point to data in axis
  31367. */
  31368. Axis.prototype.pointToData = function (point, clamp) {
  31369. // Should be implemented in derived class if necessary.
  31370. return;
  31371. };
  31372. /**
  31373. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  31374. * `axis.getTicksCoords` considers `onBand`, which is used by
  31375. * `boundaryGap:true` of category axis and splitLine and splitArea.
  31376. * @param opt.tickModel default: axis.model.getModel('axisTick')
  31377. * @param opt.clamp If `true`, the first and the last
  31378. * tick must be at the axis end points. Otherwise, clip ticks
  31379. * that outside the axis extent.
  31380. */
  31381. Axis.prototype.getTicksCoords = function (opt) {
  31382. opt = opt || {};
  31383. var tickModel = opt.tickModel || this.getTickModel();
  31384. var result = createAxisTicks(this, tickModel);
  31385. var ticks = result.ticks;
  31386. var ticksCoords = map(ticks, function (tickVal) {
  31387. return {
  31388. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  31389. tickValue: tickVal
  31390. };
  31391. }, this);
  31392. var alignWithLabel = tickModel.get('alignWithLabel');
  31393. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  31394. return ticksCoords;
  31395. };
  31396. Axis.prototype.getMinorTicksCoords = function () {
  31397. if (this.scale.type === 'ordinal') {
  31398. // Category axis doesn't support minor ticks
  31399. return [];
  31400. }
  31401. var minorTickModel = this.model.getModel('minorTick');
  31402. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  31403. if (!(splitNumber > 0 && splitNumber < 100)) {
  31404. splitNumber = 5;
  31405. }
  31406. var minorTicks = this.scale.getMinorTicks(splitNumber);
  31407. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  31408. return map(minorTicksGroup, function (minorTick) {
  31409. return {
  31410. coord: this.dataToCoord(minorTick),
  31411. tickValue: minorTick
  31412. };
  31413. }, this);
  31414. }, this);
  31415. return minorTicksCoords;
  31416. };
  31417. Axis.prototype.getViewLabels = function () {
  31418. return createAxisLabels(this).labels;
  31419. };
  31420. Axis.prototype.getLabelModel = function () {
  31421. return this.model.getModel('axisLabel');
  31422. };
  31423. /**
  31424. * Notice here we only get the default tick model. For splitLine
  31425. * or splitArea, we should pass the splitLineModel or splitAreaModel
  31426. * manually when calling `getTicksCoords`.
  31427. * In GL, this method may be overrided to:
  31428. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  31429. */
  31430. Axis.prototype.getTickModel = function () {
  31431. return this.model.getModel('axisTick');
  31432. };
  31433. /**
  31434. * Get width of band
  31435. */
  31436. Axis.prototype.getBandWidth = function () {
  31437. var axisExtent = this._extent;
  31438. var dataExtent = this.scale.getExtent();
  31439. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  31440. len === 0 && (len = 1);
  31441. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  31442. return Math.abs(size) / len;
  31443. };
  31444. /**
  31445. * Only be called in category axis.
  31446. * Can be overrided, consider other axes like in 3D.
  31447. * @return Auto interval for cateogry axis tick and label
  31448. */
  31449. Axis.prototype.calculateCategoryInterval = function () {
  31450. return calculateCategoryInterval(this);
  31451. };
  31452. return Axis;
  31453. }();
  31454. function fixExtentWithBands(extent, nTick) {
  31455. var size = extent[1] - extent[0];
  31456. var len = nTick;
  31457. var margin = size / len / 2;
  31458. extent[0] += margin;
  31459. extent[1] -= margin;
  31460. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  31461. // |---1---|---2---|---3---|---4---|.
  31462. // So the displayed ticks and splitLine/splitArea should between
  31463. // each data item, otherwise cause misleading (e.g., split tow bars
  31464. // of a single data item when there are two bar series).
  31465. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  31466. // splitLine/spliteArea should layout appropriately corresponding
  31467. // to displayed labels. (So we should not use `getBandWidth` in this
  31468. // case).
  31469. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  31470. var ticksLen = ticksCoords.length;
  31471. if (!axis.onBand || alignWithLabel || !ticksLen) {
  31472. return;
  31473. }
  31474. var axisExtent = axis.getExtent();
  31475. var last;
  31476. var diffSize;
  31477. if (ticksLen === 1) {
  31478. ticksCoords[0].coord = axisExtent[0];
  31479. last = ticksCoords[1] = {
  31480. coord: axisExtent[0]
  31481. };
  31482. } else {
  31483. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  31484. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  31485. each(ticksCoords, function (ticksItem) {
  31486. ticksItem.coord -= shift_1 / 2;
  31487. });
  31488. var dataExtent = axis.scale.getExtent();
  31489. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  31490. last = {
  31491. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  31492. };
  31493. ticksCoords.push(last);
  31494. }
  31495. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  31496. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  31497. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  31498. }
  31499. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  31500. ticksCoords.unshift({
  31501. coord: axisExtent[0]
  31502. });
  31503. }
  31504. if (littleThan(axisExtent[1], last.coord)) {
  31505. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  31506. }
  31507. if (clamp && littleThan(last.coord, axisExtent[1])) {
  31508. ticksCoords.push({
  31509. coord: axisExtent[1]
  31510. });
  31511. }
  31512. function littleThan(a, b) {
  31513. // Avoid rounding error cause calculated tick coord different with extent.
  31514. // It may cause an extra unecessary tick added.
  31515. a = round(a);
  31516. b = round(b);
  31517. return inverse ? a > b : a < b;
  31518. }
  31519. }
  31520. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  31521. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  31522. // class Bar3DModel extends ComponentModel {}
  31523. // export function install(registers) { regsiters.registerComponentModel(Bar3DModel); }
  31524. // echarts.use(install);
  31525. function extendComponentModel(proto) {
  31526. var Model = ComponentModel.extend(proto);
  31527. ComponentModel.registerClass(Model);
  31528. return Model;
  31529. }
  31530. function extendComponentView(proto) {
  31531. var View = ComponentView.extend(proto);
  31532. ComponentView.registerClass(View);
  31533. return View;
  31534. }
  31535. function extendSeriesModel(proto) {
  31536. var Model = SeriesModel.extend(proto);
  31537. SeriesModel.registerClass(Model);
  31538. return Model;
  31539. }
  31540. function extendChartView(proto) {
  31541. var View = ChartView.extend(proto);
  31542. ChartView.registerClass(View);
  31543. return View;
  31544. }
  31545. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  31546. var dx = x - x1;
  31547. var dy = y - y1;
  31548. var dx1 = x2 - x1;
  31549. var dy1 = y2 - y1;
  31550. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  31551. dx1 /= lineLen;
  31552. dy1 /= lineLen; // dot product
  31553. var projectedLen = dx * dx1 + dy * dy1;
  31554. var t = projectedLen / lineLen;
  31555. if (limitToEnds) {
  31556. t = Math.min(Math.max(t, 0), 1);
  31557. }
  31558. t *= lineLen;
  31559. var ox = out[0] = x1 + t * dx1;
  31560. var oy = out[1] = y1 + t * dy1;
  31561. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  31562. }
  31563. var pt0 = new Point();
  31564. var pt1 = new Point();
  31565. var pt2 = new Point();
  31566. var dir = new Point();
  31567. var dir2 = new Point();
  31568. var tmpArr = [];
  31569. var tmpProjPoint = new Point();
  31570. /**
  31571. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  31572. * @param linePoints
  31573. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  31574. */
  31575. function limitTurnAngle(linePoints, minTurnAngle) {
  31576. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  31577. return;
  31578. }
  31579. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  31580. // /pt1----pt2 (label)
  31581. // /
  31582. // pt0/
  31583. pt0.fromArray(linePoints[0]);
  31584. pt1.fromArray(linePoints[1]);
  31585. pt2.fromArray(linePoints[2]);
  31586. Point.sub(dir, pt0, pt1);
  31587. Point.sub(dir2, pt2, pt1);
  31588. var len1 = dir.len();
  31589. var len2 = dir2.len();
  31590. if (len1 < 1e-3 || len2 < 1e-3) {
  31591. return;
  31592. }
  31593. dir.scale(1 / len1);
  31594. dir2.scale(1 / len2);
  31595. var angleCos = dir.dot(dir2);
  31596. var minTurnAngleCos = Math.cos(minTurnAngle);
  31597. if (minTurnAngleCos < angleCos) {
  31598. // Smaller than minTurnAngle
  31599. // Calculate project point of pt0 on pt1-pt2
  31600. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  31601. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  31602. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  31603. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  31604. if (isNaN(t)) {
  31605. return;
  31606. }
  31607. if (t < 0) {
  31608. Point.copy(tmpProjPoint, pt1);
  31609. } else if (t > 1) {
  31610. Point.copy(tmpProjPoint, pt2);
  31611. }
  31612. tmpProjPoint.toArray(linePoints[1]);
  31613. }
  31614. }
  31615. /**
  31616. * Limit the angle of line and the surface
  31617. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  31618. */
  31619. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  31620. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  31621. return;
  31622. }
  31623. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  31624. pt0.fromArray(linePoints[0]);
  31625. pt1.fromArray(linePoints[1]);
  31626. pt2.fromArray(linePoints[2]);
  31627. Point.sub(dir, pt1, pt0);
  31628. Point.sub(dir2, pt2, pt1);
  31629. var len1 = dir.len();
  31630. var len2 = dir2.len();
  31631. if (len1 < 1e-3 || len2 < 1e-3) {
  31632. return;
  31633. }
  31634. dir.scale(1 / len1);
  31635. dir2.scale(1 / len2);
  31636. var angleCos = dir.dot(surfaceNormal);
  31637. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  31638. if (angleCos < maxSurfaceAngleCos) {
  31639. // Calculate project point of pt0 on pt1-pt2
  31640. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  31641. tmpProjPoint.fromArray(tmpArr);
  31642. var HALF_PI = Math.PI / 2;
  31643. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  31644. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  31645. if (newAngle >= HALF_PI) {
  31646. // parallel
  31647. Point.copy(tmpProjPoint, pt2);
  31648. } else {
  31649. // Calculate new projected length with limited minTurnAngle and get the new connect point
  31650. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  31651. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  31652. if (isNaN(t)) {
  31653. return;
  31654. }
  31655. if (t < 0) {
  31656. Point.copy(tmpProjPoint, pt1);
  31657. } else if (t > 1) {
  31658. Point.copy(tmpProjPoint, pt2);
  31659. }
  31660. }
  31661. tmpProjPoint.toArray(linePoints[1]);
  31662. }
  31663. }
  31664. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  31665. var isNormal = stateName === 'normal';
  31666. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  31667. stateObj.ignore = ignore; // Set smooth
  31668. var smooth = stateModel.get('smooth');
  31669. if (smooth && smooth === true) {
  31670. smooth = 0.3;
  31671. }
  31672. stateObj.shape = stateObj.shape || {};
  31673. if (smooth > 0) {
  31674. stateObj.shape.smooth = smooth;
  31675. }
  31676. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  31677. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  31678. }
  31679. function buildLabelLinePath(path, shape) {
  31680. var smooth = shape.smooth;
  31681. var points = shape.points;
  31682. if (!points) {
  31683. return;
  31684. }
  31685. path.moveTo(points[0][0], points[0][1]);
  31686. if (smooth > 0 && points.length >= 3) {
  31687. var len1 = dist(points[0], points[1]);
  31688. var len2 = dist(points[1], points[2]);
  31689. if (!len1 || !len2) {
  31690. path.lineTo(points[1][0], points[1][1]);
  31691. path.lineTo(points[2][0], points[2][1]);
  31692. return;
  31693. }
  31694. var moveLen = Math.min(len1, len2) * smooth;
  31695. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  31696. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  31697. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  31698. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  31699. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  31700. } else {
  31701. for (var i = 1; i < points.length; i++) {
  31702. path.lineTo(points[i][0], points[i][1]);
  31703. }
  31704. }
  31705. }
  31706. /**
  31707. * Create a label line if necessary and set it's style.
  31708. */
  31709. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  31710. var labelLine = targetEl.getTextGuideLine();
  31711. var label = targetEl.getTextContent();
  31712. if (!label) {
  31713. // Not show label line if there is no label.
  31714. if (labelLine) {
  31715. targetEl.removeTextGuideLine();
  31716. }
  31717. return;
  31718. }
  31719. var normalModel = statesModels.normal;
  31720. var showNormal = normalModel.get('show');
  31721. var labelIgnoreNormal = label.ignore;
  31722. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  31723. var stateName = DISPLAY_STATES[i];
  31724. var stateModel = statesModels[stateName];
  31725. var isNormal = stateName === 'normal';
  31726. if (stateModel) {
  31727. var stateShow = stateModel.get('show');
  31728. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  31729. if (isLabelIgnored // Not show when label is not shown in this state.
  31730. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  31731. ) {
  31732. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  31733. if (stateObj) {
  31734. stateObj.ignore = true;
  31735. }
  31736. continue;
  31737. } // Create labelLine if not exists
  31738. if (!labelLine) {
  31739. labelLine = new Polyline();
  31740. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  31741. // NOTE: NORMAL should always been the first!
  31742. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  31743. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  31744. } // Use same state proxy.
  31745. if (targetEl.stateProxy) {
  31746. labelLine.stateProxy = targetEl.stateProxy;
  31747. }
  31748. }
  31749. setLabelLineState(labelLine, false, stateName, stateModel);
  31750. }
  31751. }
  31752. if (labelLine) {
  31753. defaults(labelLine.style, defaultStyle); // Not fill.
  31754. labelLine.style.fill = null;
  31755. var showAbove = normalModel.get('showAbove');
  31756. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  31757. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  31758. labelLine.buildPath = buildLabelLinePath;
  31759. }
  31760. }
  31761. function getLabelLineStatesModels(itemModel, labelLineName) {
  31762. labelLineName = labelLineName || 'labelLine';
  31763. var statesModels = {
  31764. normal: itemModel.getModel(labelLineName)
  31765. };
  31766. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  31767. var stateName = SPECIAL_STATES[i];
  31768. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  31769. }
  31770. return statesModels;
  31771. }
  31772. function prepareLayoutList(input) {
  31773. var list = [];
  31774. for (var i = 0; i < input.length; i++) {
  31775. var rawItem = input[i];
  31776. if (rawItem.defaultAttr.ignore) {
  31777. continue;
  31778. }
  31779. var label = rawItem.label;
  31780. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  31781. var localRect = label.getBoundingRect();
  31782. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  31783. var minMargin = label.style.margin || 0;
  31784. var globalRect = localRect.clone();
  31785. globalRect.applyTransform(transform);
  31786. globalRect.x -= minMargin / 2;
  31787. globalRect.y -= minMargin / 2;
  31788. globalRect.width += minMargin;
  31789. globalRect.height += minMargin;
  31790. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  31791. list.push({
  31792. label: label,
  31793. labelLine: rawItem.labelLine,
  31794. rect: globalRect,
  31795. localRect: localRect,
  31796. obb: obb,
  31797. priority: rawItem.priority,
  31798. defaultAttr: rawItem.defaultAttr,
  31799. layoutOption: rawItem.computedLayoutOption,
  31800. axisAligned: isAxisAligned,
  31801. transform: transform
  31802. });
  31803. }
  31804. return list;
  31805. }
  31806. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  31807. var len = list.length;
  31808. if (len < 2) {
  31809. return;
  31810. }
  31811. list.sort(function (a, b) {
  31812. return a.rect[xyDim] - b.rect[xyDim];
  31813. });
  31814. var lastPos = 0;
  31815. var delta;
  31816. var adjusted = false;
  31817. var totalShifts = 0;
  31818. for (var i = 0; i < len; i++) {
  31819. var item = list[i];
  31820. var rect = item.rect;
  31821. delta = rect[xyDim] - lastPos;
  31822. if (delta < 0) {
  31823. // shiftForward(i, len, -delta);
  31824. rect[xyDim] -= delta;
  31825. item.label[xyDim] -= delta;
  31826. adjusted = true;
  31827. }
  31828. var shift = Math.max(-delta, 0);
  31829. totalShifts += shift;
  31830. lastPos = rect[xyDim] + rect[sizeDim];
  31831. }
  31832. if (totalShifts > 0 && balanceShift) {
  31833. // Shift back to make the distribution more equally.
  31834. shiftList(-totalShifts / len, 0, len);
  31835. } // TODO bleedMargin?
  31836. var first = list[0];
  31837. var last = list[len - 1];
  31838. var minGap;
  31839. var maxGap;
  31840. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  31841. minGap < 0 && squeezeGaps(-minGap, 0.8);
  31842. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  31843. updateMinMaxGap();
  31844. takeBoundsGap(minGap, maxGap, 1);
  31845. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  31846. updateMinMaxGap();
  31847. if (minGap < 0) {
  31848. squeezeWhenBailout(-minGap);
  31849. }
  31850. if (maxGap < 0) {
  31851. squeezeWhenBailout(maxGap);
  31852. }
  31853. function updateMinMaxGap() {
  31854. minGap = first.rect[xyDim] - minBound;
  31855. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  31856. }
  31857. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  31858. if (gapThisBound < 0) {
  31859. // Move from other gap if can.
  31860. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  31861. if (moveFromMaxGap > 0) {
  31862. shiftList(moveFromMaxGap * moveDir, 0, len);
  31863. var remained = moveFromMaxGap + gapThisBound;
  31864. if (remained < 0) {
  31865. squeezeGaps(-remained * moveDir, 1);
  31866. }
  31867. } else {
  31868. squeezeGaps(-gapThisBound * moveDir, 1);
  31869. }
  31870. }
  31871. }
  31872. function shiftList(delta, start, end) {
  31873. if (delta !== 0) {
  31874. adjusted = true;
  31875. }
  31876. for (var i = start; i < end; i++) {
  31877. var item = list[i];
  31878. var rect = item.rect;
  31879. rect[xyDim] += delta;
  31880. item.label[xyDim] += delta;
  31881. }
  31882. } // Squeeze gaps if the labels exceed margin.
  31883. function squeezeGaps(delta, maxSqeezePercent) {
  31884. var gaps = [];
  31885. var totalGaps = 0;
  31886. for (var i = 1; i < len; i++) {
  31887. var prevItemRect = list[i - 1].rect;
  31888. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  31889. gaps.push(gap);
  31890. totalGaps += gap;
  31891. }
  31892. if (!totalGaps) {
  31893. return;
  31894. }
  31895. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  31896. if (delta > 0) {
  31897. for (var i = 0; i < len - 1; i++) {
  31898. // Distribute the shift delta to all gaps.
  31899. var movement = gaps[i] * squeezePercent; // Forward
  31900. shiftList(movement, 0, i + 1);
  31901. }
  31902. } else {
  31903. // Backward
  31904. for (var i = len - 1; i > 0; i--) {
  31905. // Distribute the shift delta to all gaps.
  31906. var movement = gaps[i - 1] * squeezePercent;
  31907. shiftList(-movement, i, len);
  31908. }
  31909. }
  31910. }
  31911. /**
  31912. * Squeeze to allow overlap if there is no more space available.
  31913. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  31914. */
  31915. function squeezeWhenBailout(delta) {
  31916. var dir = delta < 0 ? -1 : 1;
  31917. delta = Math.abs(delta);
  31918. var moveForEachLabel = Math.ceil(delta / (len - 1));
  31919. for (var i = 0; i < len - 1; i++) {
  31920. if (dir > 0) {
  31921. // Forward
  31922. shiftList(moveForEachLabel, 0, i + 1);
  31923. } else {
  31924. // Backward
  31925. shiftList(-moveForEachLabel, len - i - 1, len);
  31926. }
  31927. delta -= moveForEachLabel;
  31928. if (delta <= 0) {
  31929. return;
  31930. }
  31931. }
  31932. }
  31933. return adjusted;
  31934. }
  31935. /**
  31936. * Adjust labels on y direction to avoid overlap.
  31937. */
  31938. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  31939. balanceShift) {
  31940. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  31941. }
  31942. function hideOverlap(labelList) {
  31943. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  31944. labelList.sort(function (a, b) {
  31945. return b.priority - a.priority;
  31946. });
  31947. var globalRect = new BoundingRect(0, 0, 0, 0);
  31948. function hideEl(el) {
  31949. if (!el.ignore) {
  31950. // Show on emphasis.
  31951. var emphasisState = el.ensureState('emphasis');
  31952. if (emphasisState.ignore == null) {
  31953. emphasisState.ignore = false;
  31954. }
  31955. }
  31956. el.ignore = true;
  31957. }
  31958. for (var i = 0; i < labelList.length; i++) {
  31959. var labelItem = labelList[i];
  31960. var isAxisAligned = labelItem.axisAligned;
  31961. var localRect = labelItem.localRect;
  31962. var transform = labelItem.transform;
  31963. var label = labelItem.label;
  31964. var labelLine = labelItem.labelLine;
  31965. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  31966. globalRect.width -= 0.1;
  31967. globalRect.height -= 0.1;
  31968. globalRect.x += 0.05;
  31969. globalRect.y += 0.05;
  31970. var obb = labelItem.obb;
  31971. var overlapped = false;
  31972. for (var j = 0; j < displayedLabels.length; j++) {
  31973. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  31974. if (!globalRect.intersect(existsTextCfg.rect)) {
  31975. continue;
  31976. }
  31977. if (isAxisAligned && existsTextCfg.axisAligned) {
  31978. // Is overlapped
  31979. overlapped = true;
  31980. break;
  31981. }
  31982. if (!existsTextCfg.obb) {
  31983. // If self is not axis aligned. But other is.
  31984. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  31985. }
  31986. if (!obb) {
  31987. // If self is axis aligned. But other is not.
  31988. obb = new OrientedBoundingRect(localRect, transform);
  31989. }
  31990. if (obb.intersect(existsTextCfg.obb)) {
  31991. overlapped = true;
  31992. break;
  31993. }
  31994. } // TODO Callback to determine if this overlap should be handled?
  31995. if (overlapped) {
  31996. hideEl(label);
  31997. labelLine && hideEl(labelLine);
  31998. } else {
  31999. label.attr('ignore', labelItem.defaultAttr.ignore);
  32000. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  32001. displayedLabels.push(labelItem);
  32002. }
  32003. }
  32004. }
  32005. function createDom(id, painter, dpr) {
  32006. var newDom = platformApi.createCanvas();
  32007. var width = painter.getWidth();
  32008. var height = painter.getHeight();
  32009. var newDomStyle = newDom.style;
  32010. if (newDomStyle) {
  32011. newDomStyle.position = 'absolute';
  32012. newDomStyle.left = '0';
  32013. newDomStyle.top = '0';
  32014. newDomStyle.width = width + 'px';
  32015. newDomStyle.height = height + 'px';
  32016. newDom.setAttribute('data-zr-dom-id', id);
  32017. }
  32018. newDom.width = width * dpr;
  32019. newDom.height = height * dpr;
  32020. return newDom;
  32021. }
  32022. var Layer = (function (_super) {
  32023. __extends(Layer, _super);
  32024. function Layer(id, painter, dpr) {
  32025. var _this = _super.call(this) || this;
  32026. _this.motionBlur = false;
  32027. _this.lastFrameAlpha = 0.7;
  32028. _this.dpr = 1;
  32029. _this.virtual = false;
  32030. _this.config = {};
  32031. _this.incremental = false;
  32032. _this.zlevel = 0;
  32033. _this.maxRepaintRectCount = 5;
  32034. _this.__dirty = true;
  32035. _this.__firstTimePaint = true;
  32036. _this.__used = false;
  32037. _this.__drawIndex = 0;
  32038. _this.__startIndex = 0;
  32039. _this.__endIndex = 0;
  32040. _this.__prevStartIndex = null;
  32041. _this.__prevEndIndex = null;
  32042. var dom;
  32043. dpr = dpr || devicePixelRatio;
  32044. if (typeof id === 'string') {
  32045. dom = createDom(id, painter, dpr);
  32046. }
  32047. else if (isObject(id)) {
  32048. dom = id;
  32049. id = dom.id;
  32050. }
  32051. _this.id = id;
  32052. _this.dom = dom;
  32053. var domStyle = dom.style;
  32054. if (domStyle) {
  32055. disableUserSelect(dom);
  32056. dom.onselectstart = function () { return false; };
  32057. domStyle.padding = '0';
  32058. domStyle.margin = '0';
  32059. domStyle.borderWidth = '0';
  32060. }
  32061. _this.painter = painter;
  32062. _this.dpr = dpr;
  32063. return _this;
  32064. }
  32065. Layer.prototype.getElementCount = function () {
  32066. return this.__endIndex - this.__startIndex;
  32067. };
  32068. Layer.prototype.afterBrush = function () {
  32069. this.__prevStartIndex = this.__startIndex;
  32070. this.__prevEndIndex = this.__endIndex;
  32071. };
  32072. Layer.prototype.initContext = function () {
  32073. this.ctx = this.dom.getContext('2d');
  32074. this.ctx.dpr = this.dpr;
  32075. };
  32076. Layer.prototype.setUnpainted = function () {
  32077. this.__firstTimePaint = true;
  32078. };
  32079. Layer.prototype.createBackBuffer = function () {
  32080. var dpr = this.dpr;
  32081. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  32082. this.ctxBack = this.domBack.getContext('2d');
  32083. if (dpr !== 1) {
  32084. this.ctxBack.scale(dpr, dpr);
  32085. }
  32086. };
  32087. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  32088. if (this.__firstTimePaint) {
  32089. this.__firstTimePaint = false;
  32090. return null;
  32091. }
  32092. var mergedRepaintRects = [];
  32093. var maxRepaintRectCount = this.maxRepaintRectCount;
  32094. var full = false;
  32095. var pendingRect = new BoundingRect(0, 0, 0, 0);
  32096. function addRectToMergePool(rect) {
  32097. if (!rect.isFinite() || rect.isZero()) {
  32098. return;
  32099. }
  32100. if (mergedRepaintRects.length === 0) {
  32101. var boundingRect = new BoundingRect(0, 0, 0, 0);
  32102. boundingRect.copy(rect);
  32103. mergedRepaintRects.push(boundingRect);
  32104. }
  32105. else {
  32106. var isMerged = false;
  32107. var minDeltaArea = Infinity;
  32108. var bestRectToMergeIdx = 0;
  32109. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  32110. var mergedRect = mergedRepaintRects[i];
  32111. if (mergedRect.intersect(rect)) {
  32112. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  32113. pendingRect_1.copy(mergedRect);
  32114. pendingRect_1.union(rect);
  32115. mergedRepaintRects[i] = pendingRect_1;
  32116. isMerged = true;
  32117. break;
  32118. }
  32119. else if (full) {
  32120. pendingRect.copy(rect);
  32121. pendingRect.union(mergedRect);
  32122. var aArea = rect.width * rect.height;
  32123. var bArea = mergedRect.width * mergedRect.height;
  32124. var pendingArea = pendingRect.width * pendingRect.height;
  32125. var deltaArea = pendingArea - aArea - bArea;
  32126. if (deltaArea < minDeltaArea) {
  32127. minDeltaArea = deltaArea;
  32128. bestRectToMergeIdx = i;
  32129. }
  32130. }
  32131. }
  32132. if (full) {
  32133. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  32134. isMerged = true;
  32135. }
  32136. if (!isMerged) {
  32137. var boundingRect = new BoundingRect(0, 0, 0, 0);
  32138. boundingRect.copy(rect);
  32139. mergedRepaintRects.push(boundingRect);
  32140. }
  32141. if (!full) {
  32142. full = mergedRepaintRects.length >= maxRepaintRectCount;
  32143. }
  32144. }
  32145. }
  32146. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  32147. var el = displayList[i];
  32148. if (el) {
  32149. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  32150. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  32151. ? el.getPrevPaintRect()
  32152. : null;
  32153. if (prevRect) {
  32154. addRectToMergePool(prevRect);
  32155. }
  32156. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  32157. ? el.getPaintRect()
  32158. : null;
  32159. if (curRect) {
  32160. addRectToMergePool(curRect);
  32161. }
  32162. }
  32163. }
  32164. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  32165. var el = prevList[i];
  32166. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  32167. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  32168. var prevRect = el.getPrevPaintRect();
  32169. if (prevRect) {
  32170. addRectToMergePool(prevRect);
  32171. }
  32172. }
  32173. }
  32174. var hasIntersections;
  32175. do {
  32176. hasIntersections = false;
  32177. for (var i = 0; i < mergedRepaintRects.length;) {
  32178. if (mergedRepaintRects[i].isZero()) {
  32179. mergedRepaintRects.splice(i, 1);
  32180. continue;
  32181. }
  32182. for (var j = i + 1; j < mergedRepaintRects.length;) {
  32183. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  32184. hasIntersections = true;
  32185. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  32186. mergedRepaintRects.splice(j, 1);
  32187. }
  32188. else {
  32189. j++;
  32190. }
  32191. }
  32192. i++;
  32193. }
  32194. } while (hasIntersections);
  32195. this._paintRects = mergedRepaintRects;
  32196. return mergedRepaintRects;
  32197. };
  32198. Layer.prototype.debugGetPaintRects = function () {
  32199. return (this._paintRects || []).slice();
  32200. };
  32201. Layer.prototype.resize = function (width, height) {
  32202. var dpr = this.dpr;
  32203. var dom = this.dom;
  32204. var domStyle = dom.style;
  32205. var domBack = this.domBack;
  32206. if (domStyle) {
  32207. domStyle.width = width + 'px';
  32208. domStyle.height = height + 'px';
  32209. }
  32210. dom.width = width * dpr;
  32211. dom.height = height * dpr;
  32212. if (domBack) {
  32213. domBack.width = width * dpr;
  32214. domBack.height = height * dpr;
  32215. if (dpr !== 1) {
  32216. this.ctxBack.scale(dpr, dpr);
  32217. }
  32218. }
  32219. };
  32220. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  32221. var dom = this.dom;
  32222. var ctx = this.ctx;
  32223. var width = dom.width;
  32224. var height = dom.height;
  32225. clearColor = clearColor || this.clearColor;
  32226. var haveMotionBLur = this.motionBlur && !clearAll;
  32227. var lastFrameAlpha = this.lastFrameAlpha;
  32228. var dpr = this.dpr;
  32229. var self = this;
  32230. if (haveMotionBLur) {
  32231. if (!this.domBack) {
  32232. this.createBackBuffer();
  32233. }
  32234. this.ctxBack.globalCompositeOperation = 'copy';
  32235. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  32236. }
  32237. var domBack = this.domBack;
  32238. function doClear(x, y, width, height) {
  32239. ctx.clearRect(x, y, width, height);
  32240. if (clearColor && clearColor !== 'transparent') {
  32241. var clearColorGradientOrPattern = void 0;
  32242. if (isGradientObject(clearColor)) {
  32243. clearColorGradientOrPattern = clearColor.__canvasGradient
  32244. || getCanvasGradient(ctx, clearColor, {
  32245. x: 0,
  32246. y: 0,
  32247. width: width,
  32248. height: height
  32249. });
  32250. clearColor.__canvasGradient = clearColorGradientOrPattern;
  32251. }
  32252. else if (isImagePatternObject(clearColor)) {
  32253. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  32254. dirty: function () {
  32255. self.setUnpainted();
  32256. self.__painter.refresh();
  32257. }
  32258. });
  32259. }
  32260. ctx.save();
  32261. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  32262. ctx.fillRect(x, y, width, height);
  32263. ctx.restore();
  32264. }
  32265. if (haveMotionBLur) {
  32266. ctx.save();
  32267. ctx.globalAlpha = lastFrameAlpha;
  32268. ctx.drawImage(domBack, x, y, width, height);
  32269. ctx.restore();
  32270. }
  32271. }
  32272. if (!repaintRects || haveMotionBLur) {
  32273. doClear(0, 0, width, height);
  32274. }
  32275. else if (repaintRects.length) {
  32276. each(repaintRects, function (rect) {
  32277. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  32278. });
  32279. }
  32280. };
  32281. return Layer;
  32282. }(Eventful));
  32283. var HOVER_LAYER_ZLEVEL = 1e5;
  32284. var CANVAS_ZLEVEL = 314159;
  32285. var EL_AFTER_INCREMENTAL_INC = 0.01;
  32286. var INCREMENTAL_INC = 0.001;
  32287. function isLayerValid(layer) {
  32288. if (!layer) {
  32289. return false;
  32290. }
  32291. if (layer.__builtin__) {
  32292. return true;
  32293. }
  32294. if (typeof (layer.resize) !== 'function'
  32295. || typeof (layer.refresh) !== 'function') {
  32296. return false;
  32297. }
  32298. return true;
  32299. }
  32300. function createRoot(width, height) {
  32301. var domRoot = document.createElement('div');
  32302. domRoot.style.cssText = [
  32303. 'position:relative',
  32304. 'width:' + width + 'px',
  32305. 'height:' + height + 'px',
  32306. 'padding:0',
  32307. 'margin:0',
  32308. 'border-width:0'
  32309. ].join(';') + ';';
  32310. return domRoot;
  32311. }
  32312. var CanvasPainter = (function () {
  32313. function CanvasPainter(root, storage, opts, id) {
  32314. this.type = 'canvas';
  32315. this._zlevelList = [];
  32316. this._prevDisplayList = [];
  32317. this._layers = {};
  32318. this._layerConfig = {};
  32319. this._needsManuallyCompositing = false;
  32320. this.type = 'canvas';
  32321. var singleCanvas = !root.nodeName
  32322. || root.nodeName.toUpperCase() === 'CANVAS';
  32323. this._opts = opts = extend({}, opts || {});
  32324. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  32325. this._singleCanvas = singleCanvas;
  32326. this.root = root;
  32327. var rootStyle = root.style;
  32328. if (rootStyle) {
  32329. disableUserSelect(root);
  32330. root.innerHTML = '';
  32331. }
  32332. this.storage = storage;
  32333. var zlevelList = this._zlevelList;
  32334. this._prevDisplayList = [];
  32335. var layers = this._layers;
  32336. if (!singleCanvas) {
  32337. this._width = getSize(root, 0, opts);
  32338. this._height = getSize(root, 1, opts);
  32339. var domRoot = this._domRoot = createRoot(this._width, this._height);
  32340. root.appendChild(domRoot);
  32341. }
  32342. else {
  32343. var rootCanvas = root;
  32344. var width = rootCanvas.width;
  32345. var height = rootCanvas.height;
  32346. if (opts.width != null) {
  32347. width = opts.width;
  32348. }
  32349. if (opts.height != null) {
  32350. height = opts.height;
  32351. }
  32352. this.dpr = opts.devicePixelRatio || 1;
  32353. rootCanvas.width = width * this.dpr;
  32354. rootCanvas.height = height * this.dpr;
  32355. this._width = width;
  32356. this._height = height;
  32357. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  32358. mainLayer.__builtin__ = true;
  32359. mainLayer.initContext();
  32360. layers[CANVAS_ZLEVEL] = mainLayer;
  32361. mainLayer.zlevel = CANVAS_ZLEVEL;
  32362. zlevelList.push(CANVAS_ZLEVEL);
  32363. this._domRoot = root;
  32364. }
  32365. }
  32366. CanvasPainter.prototype.getType = function () {
  32367. return 'canvas';
  32368. };
  32369. CanvasPainter.prototype.isSingleCanvas = function () {
  32370. return this._singleCanvas;
  32371. };
  32372. CanvasPainter.prototype.getViewportRoot = function () {
  32373. return this._domRoot;
  32374. };
  32375. CanvasPainter.prototype.getViewportRootOffset = function () {
  32376. var viewportRoot = this.getViewportRoot();
  32377. if (viewportRoot) {
  32378. return {
  32379. offsetLeft: viewportRoot.offsetLeft || 0,
  32380. offsetTop: viewportRoot.offsetTop || 0
  32381. };
  32382. }
  32383. };
  32384. CanvasPainter.prototype.refresh = function (paintAll) {
  32385. var list = this.storage.getDisplayList(true);
  32386. var prevList = this._prevDisplayList;
  32387. var zlevelList = this._zlevelList;
  32388. this._redrawId = Math.random();
  32389. this._paintList(list, prevList, paintAll, this._redrawId);
  32390. for (var i = 0; i < zlevelList.length; i++) {
  32391. var z = zlevelList[i];
  32392. var layer = this._layers[z];
  32393. if (!layer.__builtin__ && layer.refresh) {
  32394. var clearColor = i === 0 ? this._backgroundColor : null;
  32395. layer.refresh(clearColor);
  32396. }
  32397. }
  32398. if (this._opts.useDirtyRect) {
  32399. this._prevDisplayList = list.slice();
  32400. }
  32401. return this;
  32402. };
  32403. CanvasPainter.prototype.refreshHover = function () {
  32404. this._paintHoverList(this.storage.getDisplayList(false));
  32405. };
  32406. CanvasPainter.prototype._paintHoverList = function (list) {
  32407. var len = list.length;
  32408. var hoverLayer = this._hoverlayer;
  32409. hoverLayer && hoverLayer.clear();
  32410. if (!len) {
  32411. return;
  32412. }
  32413. var scope = {
  32414. inHover: true,
  32415. viewWidth: this._width,
  32416. viewHeight: this._height
  32417. };
  32418. var ctx;
  32419. for (var i = 0; i < len; i++) {
  32420. var el = list[i];
  32421. if (el.__inHover) {
  32422. if (!hoverLayer) {
  32423. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  32424. }
  32425. if (!ctx) {
  32426. ctx = hoverLayer.ctx;
  32427. ctx.save();
  32428. }
  32429. brush(ctx, el, scope, i === len - 1);
  32430. }
  32431. }
  32432. if (ctx) {
  32433. ctx.restore();
  32434. }
  32435. };
  32436. CanvasPainter.prototype.getHoverLayer = function () {
  32437. return this.getLayer(HOVER_LAYER_ZLEVEL);
  32438. };
  32439. CanvasPainter.prototype.paintOne = function (ctx, el) {
  32440. brushSingle(ctx, el);
  32441. };
  32442. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  32443. if (this._redrawId !== redrawId) {
  32444. return;
  32445. }
  32446. paintAll = paintAll || false;
  32447. this._updateLayerStatus(list);
  32448. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  32449. if (this._needsManuallyCompositing) {
  32450. this._compositeManually();
  32451. }
  32452. if (needsRefreshHover) {
  32453. this._paintHoverList(list);
  32454. }
  32455. if (!finished) {
  32456. var self_1 = this;
  32457. requestAnimationFrame$1(function () {
  32458. self_1._paintList(list, prevList, paintAll, redrawId);
  32459. });
  32460. }
  32461. else {
  32462. this.eachLayer(function (layer) {
  32463. layer.afterBrush && layer.afterBrush();
  32464. });
  32465. }
  32466. };
  32467. CanvasPainter.prototype._compositeManually = function () {
  32468. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  32469. var width = this._domRoot.width;
  32470. var height = this._domRoot.height;
  32471. ctx.clearRect(0, 0, width, height);
  32472. this.eachBuiltinLayer(function (layer) {
  32473. if (layer.virtual) {
  32474. ctx.drawImage(layer.dom, 0, 0, width, height);
  32475. }
  32476. });
  32477. };
  32478. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  32479. var _this = this;
  32480. var layerList = [];
  32481. var useDirtyRect = this._opts.useDirtyRect;
  32482. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  32483. var zlevel = this._zlevelList[zi];
  32484. var layer = this._layers[zlevel];
  32485. if (layer.__builtin__
  32486. && layer !== this._hoverlayer
  32487. && (layer.__dirty || paintAll)) {
  32488. layerList.push(layer);
  32489. }
  32490. }
  32491. var finished = true;
  32492. var needsRefreshHover = false;
  32493. var _loop_1 = function (k) {
  32494. var layer = layerList[k];
  32495. var ctx = layer.ctx;
  32496. var repaintRects = useDirtyRect
  32497. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  32498. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  32499. var useTimer = !paintAll && layer.incremental && Date.now;
  32500. var startTime = useTimer && Date.now();
  32501. var clearColor = layer.zlevel === this_1._zlevelList[0]
  32502. ? this_1._backgroundColor : null;
  32503. if (layer.__startIndex === layer.__endIndex) {
  32504. layer.clear(false, clearColor, repaintRects);
  32505. }
  32506. else if (start === layer.__startIndex) {
  32507. var firstEl = list[start];
  32508. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  32509. layer.clear(false, clearColor, repaintRects);
  32510. }
  32511. }
  32512. if (start === -1) {
  32513. console.error('For some unknown reason. drawIndex is -1');
  32514. start = layer.__startIndex;
  32515. }
  32516. var i;
  32517. var repaint = function (repaintRect) {
  32518. var scope = {
  32519. inHover: false,
  32520. allClipped: false,
  32521. prevEl: null,
  32522. viewWidth: _this._width,
  32523. viewHeight: _this._height
  32524. };
  32525. for (i = start; i < layer.__endIndex; i++) {
  32526. var el = list[i];
  32527. if (el.__inHover) {
  32528. needsRefreshHover = true;
  32529. }
  32530. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  32531. if (useTimer) {
  32532. var dTime = Date.now() - startTime;
  32533. if (dTime > 15) {
  32534. break;
  32535. }
  32536. }
  32537. }
  32538. if (scope.prevElClipPaths) {
  32539. ctx.restore();
  32540. }
  32541. };
  32542. if (repaintRects) {
  32543. if (repaintRects.length === 0) {
  32544. i = layer.__endIndex;
  32545. }
  32546. else {
  32547. var dpr = this_1.dpr;
  32548. for (var r = 0; r < repaintRects.length; ++r) {
  32549. var rect = repaintRects[r];
  32550. ctx.save();
  32551. ctx.beginPath();
  32552. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  32553. ctx.clip();
  32554. repaint(rect);
  32555. ctx.restore();
  32556. }
  32557. }
  32558. }
  32559. else {
  32560. ctx.save();
  32561. repaint();
  32562. ctx.restore();
  32563. }
  32564. layer.__drawIndex = i;
  32565. if (layer.__drawIndex < layer.__endIndex) {
  32566. finished = false;
  32567. }
  32568. };
  32569. var this_1 = this;
  32570. for (var k = 0; k < layerList.length; k++) {
  32571. _loop_1(k);
  32572. }
  32573. if (env.wxa) {
  32574. each(this._layers, function (layer) {
  32575. if (layer && layer.ctx && layer.ctx.draw) {
  32576. layer.ctx.draw();
  32577. }
  32578. });
  32579. }
  32580. return {
  32581. finished: finished,
  32582. needsRefreshHover: needsRefreshHover
  32583. };
  32584. };
  32585. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  32586. var ctx = currentLayer.ctx;
  32587. if (useDirtyRect) {
  32588. var paintRect = el.getPaintRect();
  32589. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  32590. brush(ctx, el, scope, isLast);
  32591. el.setPrevPaintRect(paintRect);
  32592. }
  32593. }
  32594. else {
  32595. brush(ctx, el, scope, isLast);
  32596. }
  32597. };
  32598. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  32599. if (this._singleCanvas && !this._needsManuallyCompositing) {
  32600. zlevel = CANVAS_ZLEVEL;
  32601. }
  32602. var layer = this._layers[zlevel];
  32603. if (!layer) {
  32604. layer = new Layer('zr_' + zlevel, this, this.dpr);
  32605. layer.zlevel = zlevel;
  32606. layer.__builtin__ = true;
  32607. if (this._layerConfig[zlevel]) {
  32608. merge(layer, this._layerConfig[zlevel], true);
  32609. }
  32610. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  32611. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  32612. }
  32613. if (virtual) {
  32614. layer.virtual = virtual;
  32615. }
  32616. this.insertLayer(zlevel, layer);
  32617. layer.initContext();
  32618. }
  32619. return layer;
  32620. };
  32621. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  32622. var layersMap = this._layers;
  32623. var zlevelList = this._zlevelList;
  32624. var len = zlevelList.length;
  32625. var domRoot = this._domRoot;
  32626. var prevLayer = null;
  32627. var i = -1;
  32628. if (layersMap[zlevel]) {
  32629. if ("development" !== 'production') {
  32630. logError('ZLevel ' + zlevel + ' has been used already');
  32631. }
  32632. return;
  32633. }
  32634. if (!isLayerValid(layer)) {
  32635. if ("development" !== 'production') {
  32636. logError('Layer of zlevel ' + zlevel + ' is not valid');
  32637. }
  32638. return;
  32639. }
  32640. if (len > 0 && zlevel > zlevelList[0]) {
  32641. for (i = 0; i < len - 1; i++) {
  32642. if (zlevelList[i] < zlevel
  32643. && zlevelList[i + 1] > zlevel) {
  32644. break;
  32645. }
  32646. }
  32647. prevLayer = layersMap[zlevelList[i]];
  32648. }
  32649. zlevelList.splice(i + 1, 0, zlevel);
  32650. layersMap[zlevel] = layer;
  32651. if (!layer.virtual) {
  32652. if (prevLayer) {
  32653. var prevDom = prevLayer.dom;
  32654. if (prevDom.nextSibling) {
  32655. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  32656. }
  32657. else {
  32658. domRoot.appendChild(layer.dom);
  32659. }
  32660. }
  32661. else {
  32662. if (domRoot.firstChild) {
  32663. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  32664. }
  32665. else {
  32666. domRoot.appendChild(layer.dom);
  32667. }
  32668. }
  32669. }
  32670. layer.__painter = this;
  32671. };
  32672. CanvasPainter.prototype.eachLayer = function (cb, context) {
  32673. var zlevelList = this._zlevelList;
  32674. for (var i = 0; i < zlevelList.length; i++) {
  32675. var z = zlevelList[i];
  32676. cb.call(context, this._layers[z], z);
  32677. }
  32678. };
  32679. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  32680. var zlevelList = this._zlevelList;
  32681. for (var i = 0; i < zlevelList.length; i++) {
  32682. var z = zlevelList[i];
  32683. var layer = this._layers[z];
  32684. if (layer.__builtin__) {
  32685. cb.call(context, layer, z);
  32686. }
  32687. }
  32688. };
  32689. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  32690. var zlevelList = this._zlevelList;
  32691. for (var i = 0; i < zlevelList.length; i++) {
  32692. var z = zlevelList[i];
  32693. var layer = this._layers[z];
  32694. if (!layer.__builtin__) {
  32695. cb.call(context, layer, z);
  32696. }
  32697. }
  32698. };
  32699. CanvasPainter.prototype.getLayers = function () {
  32700. return this._layers;
  32701. };
  32702. CanvasPainter.prototype._updateLayerStatus = function (list) {
  32703. this.eachBuiltinLayer(function (layer, z) {
  32704. layer.__dirty = layer.__used = false;
  32705. });
  32706. function updatePrevLayer(idx) {
  32707. if (prevLayer) {
  32708. if (prevLayer.__endIndex !== idx) {
  32709. prevLayer.__dirty = true;
  32710. }
  32711. prevLayer.__endIndex = idx;
  32712. }
  32713. }
  32714. if (this._singleCanvas) {
  32715. for (var i_1 = 1; i_1 < list.length; i_1++) {
  32716. var el = list[i_1];
  32717. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  32718. this._needsManuallyCompositing = true;
  32719. break;
  32720. }
  32721. }
  32722. }
  32723. var prevLayer = null;
  32724. var incrementalLayerCount = 0;
  32725. var prevZlevel;
  32726. var i;
  32727. for (i = 0; i < list.length; i++) {
  32728. var el = list[i];
  32729. var zlevel = el.zlevel;
  32730. var layer = void 0;
  32731. if (prevZlevel !== zlevel) {
  32732. prevZlevel = zlevel;
  32733. incrementalLayerCount = 0;
  32734. }
  32735. if (el.incremental) {
  32736. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  32737. layer.incremental = true;
  32738. incrementalLayerCount = 1;
  32739. }
  32740. else {
  32741. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  32742. }
  32743. if (!layer.__builtin__) {
  32744. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  32745. }
  32746. if (layer !== prevLayer) {
  32747. layer.__used = true;
  32748. if (layer.__startIndex !== i) {
  32749. layer.__dirty = true;
  32750. }
  32751. layer.__startIndex = i;
  32752. if (!layer.incremental) {
  32753. layer.__drawIndex = i;
  32754. }
  32755. else {
  32756. layer.__drawIndex = -1;
  32757. }
  32758. updatePrevLayer(i);
  32759. prevLayer = layer;
  32760. }
  32761. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  32762. layer.__dirty = true;
  32763. if (layer.incremental && layer.__drawIndex < 0) {
  32764. layer.__drawIndex = i;
  32765. }
  32766. }
  32767. }
  32768. updatePrevLayer(i);
  32769. this.eachBuiltinLayer(function (layer, z) {
  32770. if (!layer.__used && layer.getElementCount() > 0) {
  32771. layer.__dirty = true;
  32772. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  32773. }
  32774. if (layer.__dirty && layer.__drawIndex < 0) {
  32775. layer.__drawIndex = layer.__startIndex;
  32776. }
  32777. });
  32778. };
  32779. CanvasPainter.prototype.clear = function () {
  32780. this.eachBuiltinLayer(this._clearLayer);
  32781. return this;
  32782. };
  32783. CanvasPainter.prototype._clearLayer = function (layer) {
  32784. layer.clear();
  32785. };
  32786. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  32787. this._backgroundColor = backgroundColor;
  32788. each(this._layers, function (layer) {
  32789. layer.setUnpainted();
  32790. });
  32791. };
  32792. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  32793. if (config) {
  32794. var layerConfig = this._layerConfig;
  32795. if (!layerConfig[zlevel]) {
  32796. layerConfig[zlevel] = config;
  32797. }
  32798. else {
  32799. merge(layerConfig[zlevel], config, true);
  32800. }
  32801. for (var i = 0; i < this._zlevelList.length; i++) {
  32802. var _zlevel = this._zlevelList[i];
  32803. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  32804. var layer = this._layers[_zlevel];
  32805. merge(layer, layerConfig[zlevel], true);
  32806. }
  32807. }
  32808. }
  32809. };
  32810. CanvasPainter.prototype.delLayer = function (zlevel) {
  32811. var layers = this._layers;
  32812. var zlevelList = this._zlevelList;
  32813. var layer = layers[zlevel];
  32814. if (!layer) {
  32815. return;
  32816. }
  32817. layer.dom.parentNode.removeChild(layer.dom);
  32818. delete layers[zlevel];
  32819. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  32820. };
  32821. CanvasPainter.prototype.resize = function (width, height) {
  32822. if (!this._domRoot.style) {
  32823. if (width == null || height == null) {
  32824. return;
  32825. }
  32826. this._width = width;
  32827. this._height = height;
  32828. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  32829. }
  32830. else {
  32831. var domRoot = this._domRoot;
  32832. domRoot.style.display = 'none';
  32833. var opts = this._opts;
  32834. var root = this.root;
  32835. width != null && (opts.width = width);
  32836. height != null && (opts.height = height);
  32837. width = getSize(root, 0, opts);
  32838. height = getSize(root, 1, opts);
  32839. domRoot.style.display = '';
  32840. if (this._width !== width || height !== this._height) {
  32841. domRoot.style.width = width + 'px';
  32842. domRoot.style.height = height + 'px';
  32843. for (var id in this._layers) {
  32844. if (this._layers.hasOwnProperty(id)) {
  32845. this._layers[id].resize(width, height);
  32846. }
  32847. }
  32848. this.refresh(true);
  32849. }
  32850. this._width = width;
  32851. this._height = height;
  32852. }
  32853. return this;
  32854. };
  32855. CanvasPainter.prototype.clearLayer = function (zlevel) {
  32856. var layer = this._layers[zlevel];
  32857. if (layer) {
  32858. layer.clear();
  32859. }
  32860. };
  32861. CanvasPainter.prototype.dispose = function () {
  32862. this.root.innerHTML = '';
  32863. this.root =
  32864. this.storage =
  32865. this._domRoot =
  32866. this._layers = null;
  32867. };
  32868. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  32869. opts = opts || {};
  32870. if (this._singleCanvas && !this._compositeManually) {
  32871. return this._layers[CANVAS_ZLEVEL].dom;
  32872. }
  32873. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  32874. imageLayer.initContext();
  32875. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  32876. var ctx = imageLayer.ctx;
  32877. if (opts.pixelRatio <= this.dpr) {
  32878. this.refresh();
  32879. var width_1 = imageLayer.dom.width;
  32880. var height_1 = imageLayer.dom.height;
  32881. this.eachLayer(function (layer) {
  32882. if (layer.__builtin__) {
  32883. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  32884. }
  32885. else if (layer.renderToCanvas) {
  32886. ctx.save();
  32887. layer.renderToCanvas(ctx);
  32888. ctx.restore();
  32889. }
  32890. });
  32891. }
  32892. else {
  32893. var scope = {
  32894. inHover: false,
  32895. viewWidth: this._width,
  32896. viewHeight: this._height
  32897. };
  32898. var displayList = this.storage.getDisplayList(true);
  32899. for (var i = 0, len = displayList.length; i < len; i++) {
  32900. var el = displayList[i];
  32901. brush(ctx, el, scope, i === len - 1);
  32902. }
  32903. }
  32904. return imageLayer.dom;
  32905. };
  32906. CanvasPainter.prototype.getWidth = function () {
  32907. return this._width;
  32908. };
  32909. CanvasPainter.prototype.getHeight = function () {
  32910. return this._height;
  32911. };
  32912. return CanvasPainter;
  32913. }());
  32914. function install(registers) {
  32915. registers.registerPainter('canvas', CanvasPainter);
  32916. }
  32917. var LineSeriesModel =
  32918. /** @class */
  32919. function (_super) {
  32920. __extends(LineSeriesModel, _super);
  32921. function LineSeriesModel() {
  32922. var _this = _super !== null && _super.apply(this, arguments) || this;
  32923. _this.type = LineSeriesModel.type;
  32924. _this.hasSymbolVisual = true;
  32925. return _this;
  32926. }
  32927. LineSeriesModel.prototype.getInitialData = function (option) {
  32928. if ("development" !== 'production') {
  32929. var coordSys = option.coordinateSystem;
  32930. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32931. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32932. }
  32933. }
  32934. return createSeriesData(null, this, {
  32935. useEncodeDefaulter: true
  32936. });
  32937. };
  32938. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  32939. var group = new Group();
  32940. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  32941. group.add(line);
  32942. line.setStyle(opt.lineStyle);
  32943. var visualType = this.getData().getVisual('symbol');
  32944. var visualRotate = this.getData().getVisual('symbolRotate');
  32945. var symbolType = visualType === 'none' ? 'circle' : visualType; // Symbol size is 80% when there is a line
  32946. var size = opt.itemHeight * 0.8;
  32947. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  32948. group.add(symbol);
  32949. symbol.setStyle(opt.itemStyle);
  32950. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  32951. symbol.rotation = symbolRotate * Math.PI / 180;
  32952. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  32953. if (symbolType.indexOf('empty') > -1) {
  32954. symbol.style.stroke = symbol.style.fill;
  32955. symbol.style.fill = '#fff';
  32956. symbol.style.lineWidth = 2;
  32957. }
  32958. return group;
  32959. };
  32960. LineSeriesModel.type = 'series.line';
  32961. LineSeriesModel.dependencies = ['grid', 'polar'];
  32962. LineSeriesModel.defaultOption = {
  32963. // zlevel: 0,
  32964. z: 3,
  32965. coordinateSystem: 'cartesian2d',
  32966. legendHoverLink: true,
  32967. clip: true,
  32968. label: {
  32969. position: 'top'
  32970. },
  32971. // itemStyle: {
  32972. // },
  32973. endLabel: {
  32974. show: false,
  32975. valueAnimation: true,
  32976. distance: 8
  32977. },
  32978. lineStyle: {
  32979. width: 2,
  32980. type: 'solid'
  32981. },
  32982. emphasis: {
  32983. scale: true
  32984. },
  32985. // areaStyle: {
  32986. // origin of areaStyle. Valid values:
  32987. // `'auto'/null/undefined`: from axisLine to data
  32988. // `'start'`: from min to data
  32989. // `'end'`: from data to max
  32990. // origin: 'auto'
  32991. // },
  32992. // false, 'start', 'end', 'middle'
  32993. step: false,
  32994. // Disabled if step is true
  32995. smooth: false,
  32996. smoothMonotone: null,
  32997. symbol: 'emptyCircle',
  32998. symbolSize: 4,
  32999. symbolRotate: null,
  33000. showSymbol: true,
  33001. // `false`: follow the label interval strategy.
  33002. // `true`: show all symbols.
  33003. // `'auto'`: If possible, show all symbols, otherwise
  33004. // follow the label interval strategy.
  33005. showAllSymbol: 'auto',
  33006. // Whether to connect break point.
  33007. connectNulls: false,
  33008. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  33009. sampling: 'none',
  33010. animationEasing: 'linear',
  33011. // Disable progressive
  33012. progressive: 0,
  33013. hoverLayerThreshold: Infinity,
  33014. universalTransition: {
  33015. divideShape: 'clone'
  33016. },
  33017. triggerLineEvent: false
  33018. };
  33019. return LineSeriesModel;
  33020. }(SeriesModel);
  33021. /**
  33022. * @return label string. Not null/undefined
  33023. */
  33024. function getDefaultLabel(data, dataIndex) {
  33025. var labelDims = data.mapDimensionsAll('defaultedLabel');
  33026. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  33027. if (len === 1) {
  33028. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  33029. return rawVal != null ? rawVal + '' : null;
  33030. } else if (len) {
  33031. var vals = [];
  33032. for (var i = 0; i < labelDims.length; i++) {
  33033. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  33034. }
  33035. return vals.join(' ');
  33036. }
  33037. }
  33038. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  33039. var labelDims = data.mapDimensionsAll('defaultedLabel');
  33040. if (!isArray(interpolatedValue)) {
  33041. return interpolatedValue + '';
  33042. }
  33043. var vals = [];
  33044. for (var i = 0; i < labelDims.length; i++) {
  33045. var dimIndex = data.getDimensionIndex(labelDims[i]);
  33046. if (dimIndex >= 0) {
  33047. vals.push(interpolatedValue[dimIndex]);
  33048. }
  33049. }
  33050. return vals.join(' ');
  33051. }
  33052. var Symbol =
  33053. /** @class */
  33054. function (_super) {
  33055. __extends(Symbol, _super);
  33056. function Symbol(data, idx, seriesScope, opts) {
  33057. var _this = _super.call(this) || this;
  33058. _this.updateData(data, idx, seriesScope, opts);
  33059. return _this;
  33060. }
  33061. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  33062. // Remove paths created before
  33063. this.removeAll(); // let symbolPath = createSymbol(
  33064. // symbolType, -0.5, -0.5, 1, 1, color
  33065. // );
  33066. // If width/height are set too small (e.g., set to 1) on ios10
  33067. // and macOS Sierra, a circle stroke become a rect, no matter what
  33068. // the scale is set. So we set width/height as 2. See #4150.
  33069. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  33070. symbolPath.attr({
  33071. z2: 100,
  33072. culling: true,
  33073. scaleX: symbolSize[0] / 2,
  33074. scaleY: symbolSize[1] / 2
  33075. }); // Rewrite drift method
  33076. symbolPath.drift = driftSymbol;
  33077. this._symbolType = symbolType;
  33078. this.add(symbolPath);
  33079. };
  33080. /**
  33081. * Stop animation
  33082. * @param {boolean} toLastFrame
  33083. */
  33084. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  33085. this.childAt(0).stopAnimation(null, toLastFrame);
  33086. };
  33087. Symbol.prototype.getSymbolType = function () {
  33088. return this._symbolType;
  33089. };
  33090. /**
  33091. * FIXME:
  33092. * Caution: This method breaks the encapsulation of this module,
  33093. * but it indeed brings convenience. So do not use the method
  33094. * unless you detailedly know all the implements of `Symbol`,
  33095. * especially animation.
  33096. *
  33097. * Get symbol path element.
  33098. */
  33099. Symbol.prototype.getSymbolPath = function () {
  33100. return this.childAt(0);
  33101. };
  33102. /**
  33103. * Highlight symbol
  33104. */
  33105. Symbol.prototype.highlight = function () {
  33106. enterEmphasis(this.childAt(0));
  33107. };
  33108. /**
  33109. * Downplay symbol
  33110. */
  33111. Symbol.prototype.downplay = function () {
  33112. leaveEmphasis(this.childAt(0));
  33113. };
  33114. /**
  33115. * @param {number} zlevel
  33116. * @param {number} z
  33117. */
  33118. Symbol.prototype.setZ = function (zlevel, z) {
  33119. var symbolPath = this.childAt(0);
  33120. symbolPath.zlevel = zlevel;
  33121. symbolPath.z = z;
  33122. };
  33123. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  33124. var symbolPath = this.childAt(0);
  33125. symbolPath.draggable = draggable;
  33126. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  33127. };
  33128. /**
  33129. * Update symbol properties
  33130. */
  33131. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  33132. this.silent = false;
  33133. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  33134. var seriesModel = data.hostModel;
  33135. var symbolSize = Symbol.getSymbolSize(data, idx);
  33136. var isInit = symbolType !== this._symbolType;
  33137. var disableAnimation = opts && opts.disableAnimation;
  33138. if (isInit) {
  33139. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  33140. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  33141. } else {
  33142. var symbolPath = this.childAt(0);
  33143. symbolPath.silent = false;
  33144. var target = {
  33145. scaleX: symbolSize[0] / 2,
  33146. scaleY: symbolSize[1] / 2
  33147. };
  33148. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  33149. saveOldStyle(symbolPath);
  33150. }
  33151. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  33152. if (isInit) {
  33153. var symbolPath = this.childAt(0);
  33154. if (!disableAnimation) {
  33155. var target = {
  33156. scaleX: this._sizeX,
  33157. scaleY: this._sizeY,
  33158. style: {
  33159. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  33160. opacity: symbolPath.style.opacity
  33161. }
  33162. };
  33163. symbolPath.scaleX = symbolPath.scaleY = 0;
  33164. symbolPath.style.opacity = 0;
  33165. initProps(symbolPath, target, seriesModel, idx);
  33166. }
  33167. }
  33168. if (disableAnimation) {
  33169. // Must stop leave transition manually if don't call initProps or updateProps.
  33170. this.childAt(0).stopAnimation('leave');
  33171. }
  33172. };
  33173. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  33174. var symbolPath = this.childAt(0);
  33175. var seriesModel = data.hostModel;
  33176. var emphasisItemStyle;
  33177. var blurItemStyle;
  33178. var selectItemStyle;
  33179. var focus;
  33180. var blurScope;
  33181. var emphasisDisabled;
  33182. var labelStatesModels;
  33183. var hoverScale;
  33184. var cursorStyle;
  33185. if (seriesScope) {
  33186. emphasisItemStyle = seriesScope.emphasisItemStyle;
  33187. blurItemStyle = seriesScope.blurItemStyle;
  33188. selectItemStyle = seriesScope.selectItemStyle;
  33189. focus = seriesScope.focus;
  33190. blurScope = seriesScope.blurScope;
  33191. labelStatesModels = seriesScope.labelStatesModels;
  33192. hoverScale = seriesScope.hoverScale;
  33193. cursorStyle = seriesScope.cursorStyle;
  33194. emphasisDisabled = seriesScope.emphasisDisabled;
  33195. }
  33196. if (!seriesScope || data.hasItemOption) {
  33197. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  33198. var emphasisModel = itemModel.getModel('emphasis');
  33199. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  33200. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  33201. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  33202. focus = emphasisModel.get('focus');
  33203. blurScope = emphasisModel.get('blurScope');
  33204. emphasisDisabled = emphasisModel.get('disabled');
  33205. labelStatesModels = getLabelStatesModels(itemModel);
  33206. hoverScale = emphasisModel.getShallow('scale');
  33207. cursorStyle = itemModel.getShallow('cursor');
  33208. }
  33209. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  33210. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  33211. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  33212. if (symbolOffset) {
  33213. symbolPath.x = symbolOffset[0];
  33214. symbolPath.y = symbolOffset[1];
  33215. }
  33216. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  33217. var symbolStyle = data.getItemVisual(idx, 'style');
  33218. var visualColor = symbolStyle.fill;
  33219. if (symbolPath instanceof ZRImage) {
  33220. var pathStyle = symbolPath.style;
  33221. symbolPath.useStyle(extend({
  33222. // TODO other properties like x, y ?
  33223. image: pathStyle.image,
  33224. x: pathStyle.x,
  33225. y: pathStyle.y,
  33226. width: pathStyle.width,
  33227. height: pathStyle.height
  33228. }, symbolStyle));
  33229. } else {
  33230. if (symbolPath.__isEmptyBrush) {
  33231. // fill and stroke will be swapped if it's empty.
  33232. // So we cloned a new style to avoid it affecting the original style in visual storage.
  33233. // TODO Better implementation. No empty logic!
  33234. symbolPath.useStyle(extend({}, symbolStyle));
  33235. } else {
  33236. symbolPath.useStyle(symbolStyle);
  33237. } // Disable decal because symbol scale will been applied on the decal.
  33238. symbolPath.style.decal = null;
  33239. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  33240. symbolPath.style.strokeNoScale = true;
  33241. }
  33242. var liftZ = data.getItemVisual(idx, 'liftZ');
  33243. var z2Origin = this._z2;
  33244. if (liftZ != null) {
  33245. if (z2Origin == null) {
  33246. this._z2 = symbolPath.z2;
  33247. symbolPath.z2 += liftZ;
  33248. }
  33249. } else if (z2Origin != null) {
  33250. symbolPath.z2 = z2Origin;
  33251. this._z2 = null;
  33252. }
  33253. var useNameLabel = opts && opts.useNameLabel;
  33254. setLabelStyle(symbolPath, labelStatesModels, {
  33255. labelFetcher: seriesModel,
  33256. labelDataIndex: idx,
  33257. defaultText: getLabelDefaultText,
  33258. inheritColor: visualColor,
  33259. defaultOpacity: symbolStyle.opacity
  33260. }); // Do not execute util needed.
  33261. function getLabelDefaultText(idx) {
  33262. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  33263. }
  33264. this._sizeX = symbolSize[0] / 2;
  33265. this._sizeY = symbolSize[1] / 2;
  33266. var emphasisState = symbolPath.ensureState('emphasis');
  33267. emphasisState.style = emphasisItemStyle;
  33268. symbolPath.ensureState('select').style = selectItemStyle;
  33269. symbolPath.ensureState('blur').style = blurItemStyle;
  33270. if (hoverScale) {
  33271. var scaleRatio = Math.max(isNumber(hoverScale) ? hoverScale : 1.1, 3 / this._sizeY);
  33272. emphasisState.scaleX = this._sizeX * scaleRatio;
  33273. emphasisState.scaleY = this._sizeY * scaleRatio;
  33274. }
  33275. this.setSymbolScale(1);
  33276. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  33277. };
  33278. Symbol.prototype.setSymbolScale = function (scale) {
  33279. this.scaleX = this.scaleY = scale;
  33280. };
  33281. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  33282. var symbolPath = this.childAt(0);
  33283. var dataIndex = getECData(this).dataIndex;
  33284. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  33285. this.silent = symbolPath.silent = true; // Not show text when animating
  33286. if (opt && opt.fadeLabel) {
  33287. var textContent = symbolPath.getTextContent();
  33288. if (textContent) {
  33289. removeElement(textContent, {
  33290. style: {
  33291. opacity: 0
  33292. }
  33293. }, seriesModel, {
  33294. dataIndex: dataIndex,
  33295. removeOpt: animationOpt,
  33296. cb: function () {
  33297. symbolPath.removeTextContent();
  33298. }
  33299. });
  33300. }
  33301. } else {
  33302. symbolPath.removeTextContent();
  33303. }
  33304. removeElement(symbolPath, {
  33305. style: {
  33306. opacity: 0
  33307. },
  33308. scaleX: 0,
  33309. scaleY: 0
  33310. }, seriesModel, {
  33311. dataIndex: dataIndex,
  33312. cb: cb,
  33313. removeOpt: animationOpt
  33314. });
  33315. };
  33316. Symbol.getSymbolSize = function (data, idx) {
  33317. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  33318. };
  33319. return Symbol;
  33320. }(Group);
  33321. function driftSymbol(dx, dy) {
  33322. this.parent.drift(dx, dy);
  33323. }
  33324. function symbolNeedsDraw(data, point, idx, opt) {
  33325. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx)) // We do not set clipShape on group, because it will cut part of
  33326. // the symbol element shape. We use the same clip shape here as
  33327. // the line clip.
  33328. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  33329. }
  33330. function normalizeUpdateOpt(opt) {
  33331. if (opt != null && !isObject(opt)) {
  33332. opt = {
  33333. isIgnore: opt
  33334. };
  33335. }
  33336. return opt || {};
  33337. }
  33338. function makeSeriesScope(data) {
  33339. var seriesModel = data.hostModel;
  33340. var emphasisModel = seriesModel.getModel('emphasis');
  33341. return {
  33342. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  33343. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  33344. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  33345. focus: emphasisModel.get('focus'),
  33346. blurScope: emphasisModel.get('blurScope'),
  33347. emphasisDisabled: emphasisModel.get('disabled'),
  33348. hoverScale: emphasisModel.get('scale'),
  33349. labelStatesModels: getLabelStatesModels(seriesModel),
  33350. cursorStyle: seriesModel.get('cursor')
  33351. };
  33352. }
  33353. var SymbolDraw =
  33354. /** @class */
  33355. function () {
  33356. function SymbolDraw(SymbolCtor) {
  33357. this.group = new Group();
  33358. this._SymbolCtor = SymbolCtor || Symbol;
  33359. }
  33360. /**
  33361. * Update symbols draw by new data
  33362. */
  33363. SymbolDraw.prototype.updateData = function (data, opt) {
  33364. // Remove progressive els.
  33365. this._progressiveEls = null;
  33366. opt = normalizeUpdateOpt(opt);
  33367. var group = this.group;
  33368. var seriesModel = data.hostModel;
  33369. var oldData = this._data;
  33370. var SymbolCtor = this._SymbolCtor;
  33371. var disableAnimation = opt.disableAnimation;
  33372. var seriesScope = makeSeriesScope(data);
  33373. var symbolUpdateOpt = {
  33374. disableAnimation: disableAnimation
  33375. };
  33376. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  33377. return data.getItemLayout(idx);
  33378. }; // There is no oldLineData only when first rendering or switching from
  33379. // stream mode to normal mode, where previous elements should be removed.
  33380. if (!oldData) {
  33381. group.removeAll();
  33382. }
  33383. data.diff(oldData).add(function (newIdx) {
  33384. var point = getSymbolPoint(newIdx);
  33385. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  33386. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  33387. symbolEl.setPosition(point);
  33388. data.setItemGraphicEl(newIdx, symbolEl);
  33389. group.add(symbolEl);
  33390. }
  33391. }).update(function (newIdx, oldIdx) {
  33392. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  33393. var point = getSymbolPoint(newIdx);
  33394. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  33395. group.remove(symbolEl);
  33396. return;
  33397. }
  33398. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  33399. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  33400. if (!symbolEl // Create a new if symbol type changed.
  33401. || oldSymbolType && oldSymbolType !== newSymbolType) {
  33402. group.remove(symbolEl);
  33403. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  33404. symbolEl.setPosition(point);
  33405. } else {
  33406. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  33407. var target = {
  33408. x: point[0],
  33409. y: point[1]
  33410. };
  33411. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  33412. } // Add back
  33413. group.add(symbolEl);
  33414. data.setItemGraphicEl(newIdx, symbolEl);
  33415. }).remove(function (oldIdx) {
  33416. var el = oldData.getItemGraphicEl(oldIdx);
  33417. el && el.fadeOut(function () {
  33418. group.remove(el);
  33419. }, seriesModel);
  33420. }).execute();
  33421. this._getSymbolPoint = getSymbolPoint;
  33422. this._data = data;
  33423. };
  33424. SymbolDraw.prototype.updateLayout = function () {
  33425. var _this = this;
  33426. var data = this._data;
  33427. if (data) {
  33428. // Not use animation
  33429. data.eachItemGraphicEl(function (el, idx) {
  33430. var point = _this._getSymbolPoint(idx);
  33431. el.setPosition(point);
  33432. el.markRedraw();
  33433. });
  33434. }
  33435. };
  33436. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  33437. this._seriesScope = makeSeriesScope(data);
  33438. this._data = null;
  33439. this.group.removeAll();
  33440. };
  33441. /**
  33442. * Update symbols draw by new data
  33443. */
  33444. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  33445. // Clear
  33446. this._progressiveEls = [];
  33447. opt = normalizeUpdateOpt(opt);
  33448. function updateIncrementalAndHover(el) {
  33449. if (!el.isGroup) {
  33450. el.incremental = true;
  33451. el.ensureState('emphasis').hoverLayer = true;
  33452. }
  33453. }
  33454. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33455. var point = data.getItemLayout(idx);
  33456. if (symbolNeedsDraw(data, point, idx, opt)) {
  33457. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  33458. el.traverse(updateIncrementalAndHover);
  33459. el.setPosition(point);
  33460. this.group.add(el);
  33461. data.setItemGraphicEl(idx, el);
  33462. this._progressiveEls.push(el);
  33463. }
  33464. }
  33465. };
  33466. SymbolDraw.prototype.eachRendered = function (cb) {
  33467. traverseElements(this._progressiveEls || this.group, cb);
  33468. };
  33469. SymbolDraw.prototype.remove = function (enableAnimation) {
  33470. var group = this.group;
  33471. var data = this._data; // Incremental model do not have this._data.
  33472. if (data && enableAnimation) {
  33473. data.eachItemGraphicEl(function (el) {
  33474. el.fadeOut(function () {
  33475. group.remove(el);
  33476. }, data.hostModel);
  33477. });
  33478. } else {
  33479. group.removeAll();
  33480. }
  33481. };
  33482. return SymbolDraw;
  33483. }();
  33484. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33485. var baseAxis = coordSys.getBaseAxis();
  33486. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33487. var valueStart = getValueStart(valueAxis, valueOrigin);
  33488. var baseAxisDim = baseAxis.dim;
  33489. var valueAxisDim = valueAxis.dim;
  33490. var valueDim = data.mapDimension(valueAxisDim);
  33491. var baseDim = data.mapDimension(baseAxisDim);
  33492. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33493. var dims = map(coordSys.dimensions, function (coordDim) {
  33494. return data.mapDimension(coordDim);
  33495. });
  33496. var stacked = false;
  33497. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33498. if (isDimensionStacked(data, dims[0]
  33499. /*, dims[1]*/
  33500. )) {
  33501. // jshint ignore:line
  33502. stacked = true;
  33503. dims[0] = stackResultDim;
  33504. }
  33505. if (isDimensionStacked(data, dims[1]
  33506. /*, dims[0]*/
  33507. )) {
  33508. // jshint ignore:line
  33509. stacked = true;
  33510. dims[1] = stackResultDim;
  33511. }
  33512. return {
  33513. dataDimsForPoint: dims,
  33514. valueStart: valueStart,
  33515. valueAxisDim: valueAxisDim,
  33516. baseAxisDim: baseAxisDim,
  33517. stacked: !!stacked,
  33518. valueDim: valueDim,
  33519. baseDim: baseDim,
  33520. baseDataOffset: baseDataOffset,
  33521. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33522. };
  33523. }
  33524. function getValueStart(valueAxis, valueOrigin) {
  33525. var valueStart = 0;
  33526. var extent = valueAxis.scale.getExtent();
  33527. if (valueOrigin === 'start') {
  33528. valueStart = extent[0];
  33529. } else if (valueOrigin === 'end') {
  33530. valueStart = extent[1];
  33531. } // If origin is specified as a number, use it as
  33532. // valueStart directly
  33533. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  33534. valueStart = valueOrigin;
  33535. } // auto
  33536. else {
  33537. // Both positive
  33538. if (extent[0] > 0) {
  33539. valueStart = extent[0];
  33540. } // Both negative
  33541. else if (extent[1] < 0) {
  33542. valueStart = extent[1];
  33543. } // If is one positive, and one negative, onZero shall be true
  33544. }
  33545. return valueStart;
  33546. }
  33547. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33548. var value = NaN;
  33549. if (dataCoordInfo.stacked) {
  33550. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33551. }
  33552. if (isNaN(value)) {
  33553. value = dataCoordInfo.valueStart;
  33554. }
  33555. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33556. var stackedData = [];
  33557. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33558. stackedData[1 - baseDataOffset] = value;
  33559. return coordSys.dataToPoint(stackedData);
  33560. }
  33561. function diffData(oldData, newData) {
  33562. var diffResult = [];
  33563. newData.diff(oldData).add(function (idx) {
  33564. diffResult.push({
  33565. cmd: '+',
  33566. idx: idx
  33567. });
  33568. }).update(function (newIdx, oldIdx) {
  33569. diffResult.push({
  33570. cmd: '=',
  33571. idx: oldIdx,
  33572. idx1: newIdx
  33573. });
  33574. }).remove(function (idx) {
  33575. diffResult.push({
  33576. cmd: '-',
  33577. idx: idx
  33578. });
  33579. }).execute();
  33580. return diffResult;
  33581. }
  33582. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  33583. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  33584. // let oldIdList = oldData.mapArray(oldData.getId);
  33585. // convertToIntId(newIdList, oldIdList);
  33586. // // FIXME One data ?
  33587. // diff = arrayDiff(oldIdList, newIdList);
  33588. var currPoints = [];
  33589. var nextPoints = []; // Points for stacking base line
  33590. var currStackedPoints = [];
  33591. var nextStackedPoints = [];
  33592. var status = [];
  33593. var sortedIndices = [];
  33594. var rawIndices = [];
  33595. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33596. var oldPoints = oldData.getLayout('points') || [];
  33597. var newPoints = newData.getLayout('points') || [];
  33598. for (var i = 0; i < diff.length; i++) {
  33599. var diffItem = diff[i];
  33600. var pointAdded = true;
  33601. var oldIdx2 = void 0;
  33602. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  33603. // Which is in case remvoing or add more than one data in the tail or head
  33604. switch (diffItem.cmd) {
  33605. case '=':
  33606. oldIdx2 = diffItem.idx * 2;
  33607. newIdx2 = diffItem.idx1 * 2;
  33608. var currentX = oldPoints[oldIdx2];
  33609. var currentY = oldPoints[oldIdx2 + 1];
  33610. var nextX = newPoints[newIdx2];
  33611. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  33612. if (isNaN(currentX) || isNaN(currentY)) {
  33613. currentX = nextX;
  33614. currentY = nextY;
  33615. }
  33616. currPoints.push(currentX, currentY);
  33617. nextPoints.push(nextX, nextY);
  33618. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  33619. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  33620. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33621. break;
  33622. case '+':
  33623. var newIdx = diffItem.idx;
  33624. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  33625. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  33626. newIdx2 = newIdx * 2;
  33627. currPoints.push(oldPt[0], oldPt[1]);
  33628. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  33629. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  33630. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  33631. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  33632. rawIndices.push(newData.getRawIndex(newIdx));
  33633. break;
  33634. case '-':
  33635. pointAdded = false;
  33636. } // Original indices
  33637. if (pointAdded) {
  33638. status.push(diffItem);
  33639. sortedIndices.push(sortedIndices.length);
  33640. }
  33641. } // Diff result may be crossed if all items are changed
  33642. // Sort by data index
  33643. sortedIndices.sort(function (a, b) {
  33644. return rawIndices[a] - rawIndices[b];
  33645. });
  33646. var len = currPoints.length;
  33647. var sortedCurrPoints = createFloat32Array(len);
  33648. var sortedNextPoints = createFloat32Array(len);
  33649. var sortedCurrStackedPoints = createFloat32Array(len);
  33650. var sortedNextStackedPoints = createFloat32Array(len);
  33651. var sortedStatus = [];
  33652. for (var i = 0; i < sortedIndices.length; i++) {
  33653. var idx = sortedIndices[i];
  33654. var i2 = i * 2;
  33655. var idx2 = idx * 2;
  33656. sortedCurrPoints[i2] = currPoints[idx2];
  33657. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  33658. sortedNextPoints[i2] = nextPoints[idx2];
  33659. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  33660. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  33661. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  33662. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  33663. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  33664. sortedStatus[i] = status[idx];
  33665. }
  33666. return {
  33667. current: sortedCurrPoints,
  33668. next: sortedNextPoints,
  33669. stackedOnCurrent: sortedCurrStackedPoints,
  33670. stackedOnNext: sortedNextStackedPoints,
  33671. status: sortedStatus
  33672. };
  33673. }
  33674. var mathMin$5 = Math.min;
  33675. var mathMax$5 = Math.max;
  33676. function isPointNull(x, y) {
  33677. return isNaN(x) || isNaN(y);
  33678. }
  33679. /**
  33680. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33681. * situations. This should be used when points are non-monotone neither in x or
  33682. * y dimension.
  33683. */
  33684. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  33685. var prevX;
  33686. var prevY;
  33687. var cpx0;
  33688. var cpy0;
  33689. var cpx1;
  33690. var cpy1;
  33691. var idx = start;
  33692. var k = 0;
  33693. for (; k < segLen; k++) {
  33694. var x = points[idx * 2];
  33695. var y = points[idx * 2 + 1];
  33696. if (idx >= allLen || idx < 0) {
  33697. break;
  33698. }
  33699. if (isPointNull(x, y)) {
  33700. if (connectNulls) {
  33701. idx += dir;
  33702. continue;
  33703. }
  33704. break;
  33705. }
  33706. if (idx === start) {
  33707. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  33708. cpx0 = x;
  33709. cpy0 = y;
  33710. } else {
  33711. var dx = x - prevX;
  33712. var dy = y - prevY; // Ignore tiny segment.
  33713. if (dx * dx + dy * dy < 0.5) {
  33714. idx += dir;
  33715. continue;
  33716. }
  33717. if (smooth > 0) {
  33718. var nextIdx = idx + dir;
  33719. var nextX = points[nextIdx * 2];
  33720. var nextY = points[nextIdx * 2 + 1]; // Ignore duplicate point
  33721. while (nextX === x && nextY === y && k < segLen) {
  33722. k++;
  33723. nextIdx += dir;
  33724. idx += dir;
  33725. nextX = points[nextIdx * 2];
  33726. nextY = points[nextIdx * 2 + 1];
  33727. x = points[idx * 2];
  33728. y = points[idx * 2 + 1];
  33729. dx = x - prevX;
  33730. dy = y - prevY;
  33731. }
  33732. var tmpK = k + 1;
  33733. if (connectNulls) {
  33734. // Find next point not null
  33735. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  33736. tmpK++;
  33737. nextIdx += dir;
  33738. nextX = points[nextIdx * 2];
  33739. nextY = points[nextIdx * 2 + 1];
  33740. }
  33741. }
  33742. var ratioNextSeg = 0.5;
  33743. var vx = 0;
  33744. var vy = 0;
  33745. var nextCpx0 = void 0;
  33746. var nextCpy0 = void 0; // Is last point
  33747. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  33748. cpx1 = x;
  33749. cpy1 = y;
  33750. } else {
  33751. vx = nextX - prevX;
  33752. vy = nextY - prevY;
  33753. var dx0 = x - prevX;
  33754. var dx1 = nextX - x;
  33755. var dy0 = y - prevY;
  33756. var dy1 = nextY - y;
  33757. var lenPrevSeg = void 0;
  33758. var lenNextSeg = void 0;
  33759. if (smoothMonotone === 'x') {
  33760. lenPrevSeg = Math.abs(dx0);
  33761. lenNextSeg = Math.abs(dx1);
  33762. var dir_1 = vx > 0 ? 1 : -1;
  33763. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  33764. cpy1 = y;
  33765. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  33766. nextCpy0 = y;
  33767. } else if (smoothMonotone === 'y') {
  33768. lenPrevSeg = Math.abs(dy0);
  33769. lenNextSeg = Math.abs(dy1);
  33770. var dir_2 = vy > 0 ? 1 : -1;
  33771. cpx1 = x;
  33772. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  33773. nextCpx0 = x;
  33774. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  33775. } else {
  33776. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  33777. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  33778. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33779. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  33780. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  33781. nextCpx0 = x + vx * smooth * ratioNextSeg;
  33782. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  33783. // Avoid exceeding extreme after smoothing.
  33784. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  33785. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  33786. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  33787. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  33788. vx = nextCpx0 - x;
  33789. vy = nextCpy0 - y;
  33790. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  33791. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  33792. // Avoid exceeding extreme after smoothing.
  33793. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  33794. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  33795. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  33796. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  33797. vx = x - cpx1;
  33798. vy = y - cpy1;
  33799. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  33800. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  33801. }
  33802. }
  33803. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  33804. cpx0 = nextCpx0;
  33805. cpy0 = nextCpy0;
  33806. } else {
  33807. ctx.lineTo(x, y);
  33808. }
  33809. }
  33810. prevX = x;
  33811. prevY = y;
  33812. idx += dir;
  33813. }
  33814. return k;
  33815. }
  33816. var ECPolylineShape =
  33817. /** @class */
  33818. function () {
  33819. function ECPolylineShape() {
  33820. this.smooth = 0;
  33821. this.smoothConstraint = true;
  33822. }
  33823. return ECPolylineShape;
  33824. }();
  33825. var ECPolyline =
  33826. /** @class */
  33827. function (_super) {
  33828. __extends(ECPolyline, _super);
  33829. function ECPolyline(opts) {
  33830. var _this = _super.call(this, opts) || this;
  33831. _this.type = 'ec-polyline';
  33832. return _this;
  33833. }
  33834. ECPolyline.prototype.getDefaultStyle = function () {
  33835. return {
  33836. stroke: '#000',
  33837. fill: null
  33838. };
  33839. };
  33840. ECPolyline.prototype.getDefaultShape = function () {
  33841. return new ECPolylineShape();
  33842. };
  33843. ECPolyline.prototype.buildPath = function (ctx, shape) {
  33844. var points = shape.points;
  33845. var i = 0;
  33846. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  33847. if (shape.connectNulls) {
  33848. // Must remove first and last null values avoid draw error in polygon
  33849. for (; len > 0; len--) {
  33850. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  33851. break;
  33852. }
  33853. }
  33854. for (; i < len; i++) {
  33855. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  33856. break;
  33857. }
  33858. }
  33859. }
  33860. while (i < len) {
  33861. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  33862. }
  33863. };
  33864. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  33865. if (!this.path) {
  33866. this.createPathProxy();
  33867. this.buildPath(this.path, this.shape);
  33868. }
  33869. var path = this.path;
  33870. var data = path.data;
  33871. var CMD = PathProxy.CMD;
  33872. var x0;
  33873. var y0;
  33874. var isDimX = dim === 'x';
  33875. var roots = [];
  33876. for (var i = 0; i < data.length;) {
  33877. var cmd = data[i++];
  33878. var x = void 0;
  33879. var y = void 0;
  33880. var x2 = void 0;
  33881. var y2 = void 0;
  33882. var x3 = void 0;
  33883. var y3 = void 0;
  33884. var t = void 0;
  33885. switch (cmd) {
  33886. case CMD.M:
  33887. x0 = data[i++];
  33888. y0 = data[i++];
  33889. break;
  33890. case CMD.L:
  33891. x = data[i++];
  33892. y = data[i++];
  33893. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  33894. if (t <= 1 && t >= 0) {
  33895. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  33896. return isDimX ? [xOrY, val] : [val, xOrY];
  33897. }
  33898. x0 = x;
  33899. y0 = y;
  33900. break;
  33901. case CMD.C:
  33902. x = data[i++];
  33903. y = data[i++];
  33904. x2 = data[i++];
  33905. y2 = data[i++];
  33906. x3 = data[i++];
  33907. y3 = data[i++];
  33908. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  33909. if (nRoot > 0) {
  33910. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  33911. var t_1 = roots[i_1];
  33912. if (t_1 <= 1 && t_1 >= 0) {
  33913. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  33914. return isDimX ? [xOrY, val] : [val, xOrY];
  33915. }
  33916. }
  33917. }
  33918. x0 = x3;
  33919. y0 = y3;
  33920. break;
  33921. }
  33922. }
  33923. };
  33924. return ECPolyline;
  33925. }(Path);
  33926. var ECPolygonShape =
  33927. /** @class */
  33928. function (_super) {
  33929. __extends(ECPolygonShape, _super);
  33930. function ECPolygonShape() {
  33931. return _super !== null && _super.apply(this, arguments) || this;
  33932. }
  33933. return ECPolygonShape;
  33934. }(ECPolylineShape);
  33935. var ECPolygon =
  33936. /** @class */
  33937. function (_super) {
  33938. __extends(ECPolygon, _super);
  33939. function ECPolygon(opts) {
  33940. var _this = _super.call(this, opts) || this;
  33941. _this.type = 'ec-polygon';
  33942. return _this;
  33943. }
  33944. ECPolygon.prototype.getDefaultShape = function () {
  33945. return new ECPolygonShape();
  33946. };
  33947. ECPolygon.prototype.buildPath = function (ctx, shape) {
  33948. var points = shape.points;
  33949. var stackedOnPoints = shape.stackedOnPoints;
  33950. var i = 0;
  33951. var len = points.length / 2;
  33952. var smoothMonotone = shape.smoothMonotone;
  33953. if (shape.connectNulls) {
  33954. // Must remove first and last null values avoid draw error in polygon
  33955. for (; len > 0; len--) {
  33956. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  33957. break;
  33958. }
  33959. }
  33960. for (; i < len; i++) {
  33961. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  33962. break;
  33963. }
  33964. }
  33965. }
  33966. while (i < len) {
  33967. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  33968. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  33969. i += k + 1;
  33970. ctx.closePath();
  33971. }
  33972. };
  33973. return ECPolygon;
  33974. }(Path);
  33975. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  33976. var rect = cartesian.getArea();
  33977. var x = rect.x;
  33978. var y = rect.y;
  33979. var width = rect.width;
  33980. var height = rect.height;
  33981. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33982. x -= lineWidth / 2;
  33983. y -= lineWidth / 2;
  33984. width += lineWidth;
  33985. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  33986. x = Math.floor(x);
  33987. width = Math.round(width);
  33988. var clipPath = new Rect({
  33989. shape: {
  33990. x: x,
  33991. y: y,
  33992. width: width,
  33993. height: height
  33994. }
  33995. });
  33996. if (hasAnimation) {
  33997. var baseAxis = cartesian.getBaseAxis();
  33998. var isHorizontal = baseAxis.isHorizontal();
  33999. var isAxisInversed = baseAxis.inverse;
  34000. if (isHorizontal) {
  34001. if (isAxisInversed) {
  34002. clipPath.shape.x += width;
  34003. }
  34004. clipPath.shape.width = 0;
  34005. } else {
  34006. if (!isAxisInversed) {
  34007. clipPath.shape.y += height;
  34008. }
  34009. clipPath.shape.height = 0;
  34010. }
  34011. var duringCb = isFunction(during) ? function (percent) {
  34012. during(percent, clipPath);
  34013. } : null;
  34014. initProps(clipPath, {
  34015. shape: {
  34016. width: width,
  34017. height: height,
  34018. x: x,
  34019. y: y
  34020. }
  34021. }, seriesModel, null, done, duringCb);
  34022. }
  34023. return clipPath;
  34024. }
  34025. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  34026. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  34027. var r0 = round(sectorArea.r0, 1);
  34028. var r = round(sectorArea.r, 1);
  34029. var clipPath = new Sector({
  34030. shape: {
  34031. cx: round(polar.cx, 1),
  34032. cy: round(polar.cy, 1),
  34033. r0: r0,
  34034. r: r,
  34035. startAngle: sectorArea.startAngle,
  34036. endAngle: sectorArea.endAngle,
  34037. clockwise: sectorArea.clockwise
  34038. }
  34039. });
  34040. if (hasAnimation) {
  34041. var isRadial = polar.getBaseAxis().dim === 'angle';
  34042. if (isRadial) {
  34043. clipPath.shape.endAngle = sectorArea.startAngle;
  34044. } else {
  34045. clipPath.shape.r = r0;
  34046. }
  34047. initProps(clipPath, {
  34048. shape: {
  34049. endAngle: sectorArea.endAngle,
  34050. r: r
  34051. }
  34052. }, seriesModel);
  34053. }
  34054. return clipPath;
  34055. }
  34056. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  34057. if (!coordSys) {
  34058. return null;
  34059. } else if (coordSys.type === 'polar') {
  34060. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34061. } else if (coordSys.type === 'cartesian2d') {
  34062. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  34063. }
  34064. return null;
  34065. }
  34066. /*
  34067. * Licensed to the Apache Software Foundation (ASF) under one
  34068. * or more contributor license agreements. See the NOTICE file
  34069. * distributed with this work for additional information
  34070. * regarding copyright ownership. The ASF licenses this file
  34071. * to you under the Apache License, Version 2.0 (the
  34072. * "License"); you may not use this file except in compliance
  34073. * with the License. You may obtain a copy of the License at
  34074. *
  34075. * http://www.apache.org/licenses/LICENSE-2.0
  34076. *
  34077. * Unless required by applicable law or agreed to in writing,
  34078. * software distributed under the License is distributed on an
  34079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34080. * KIND, either express or implied. See the License for the
  34081. * specific language governing permissions and limitations
  34082. * under the License.
  34083. */
  34084. /**
  34085. * AUTO-GENERATED FILE. DO NOT MODIFY.
  34086. */
  34087. /*
  34088. * Licensed to the Apache Software Foundation (ASF) under one
  34089. * or more contributor license agreements. See the NOTICE file
  34090. * distributed with this work for additional information
  34091. * regarding copyright ownership. The ASF licenses this file
  34092. * to you under the Apache License, Version 2.0 (the
  34093. * "License"); you may not use this file except in compliance
  34094. * with the License. You may obtain a copy of the License at
  34095. *
  34096. * http://www.apache.org/licenses/LICENSE-2.0
  34097. *
  34098. * Unless required by applicable law or agreed to in writing,
  34099. * software distributed under the License is distributed on an
  34100. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34101. * KIND, either express or implied. See the License for the
  34102. * specific language governing permissions and limitations
  34103. * under the License.
  34104. */
  34105. function isCoordinateSystemType(coordSys, type) {
  34106. return coordSys.type === type;
  34107. }
  34108. function isPointsSame(points1, points2) {
  34109. if (points1.length !== points2.length) {
  34110. return;
  34111. }
  34112. for (var i = 0; i < points1.length; i++) {
  34113. if (points1[i] !== points2[i]) {
  34114. return;
  34115. }
  34116. }
  34117. return true;
  34118. }
  34119. function bboxFromPoints(points) {
  34120. var minX = Infinity;
  34121. var minY = Infinity;
  34122. var maxX = -Infinity;
  34123. var maxY = -Infinity;
  34124. for (var i = 0; i < points.length;) {
  34125. var x = points[i++];
  34126. var y = points[i++];
  34127. if (!isNaN(x)) {
  34128. minX = Math.min(x, minX);
  34129. maxX = Math.max(x, maxX);
  34130. }
  34131. if (!isNaN(y)) {
  34132. minY = Math.min(y, minY);
  34133. maxY = Math.max(y, maxY);
  34134. }
  34135. }
  34136. return [[minX, minY], [maxX, maxY]];
  34137. }
  34138. function getBoundingDiff(points1, points2) {
  34139. var _a = bboxFromPoints(points1),
  34140. min1 = _a[0],
  34141. max1 = _a[1];
  34142. var _b = bboxFromPoints(points2),
  34143. min2 = _b[0],
  34144. max2 = _b[1]; // Get a max value from each corner of two boundings.
  34145. 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]));
  34146. }
  34147. function getSmooth(smooth) {
  34148. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  34149. }
  34150. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  34151. if (!dataCoordInfo.valueDim) {
  34152. return [];
  34153. }
  34154. var len = data.count();
  34155. var points = createFloat32Array(len * 2);
  34156. for (var idx = 0; idx < len; idx++) {
  34157. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  34158. points[idx * 2] = pt[0];
  34159. points[idx * 2 + 1] = pt[1];
  34160. }
  34161. return points;
  34162. }
  34163. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  34164. var baseAxis = coordSys.getBaseAxis();
  34165. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  34166. var stepPoints = [];
  34167. var i = 0;
  34168. var stepPt = [];
  34169. var pt = [];
  34170. var nextPt = [];
  34171. var filteredPoints = [];
  34172. if (connectNulls) {
  34173. for (i = 0; i < points.length; i += 2) {
  34174. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  34175. filteredPoints.push(points[i], points[i + 1]);
  34176. }
  34177. }
  34178. points = filteredPoints;
  34179. }
  34180. for (i = 0; i < points.length - 2; i += 2) {
  34181. nextPt[0] = points[i + 2];
  34182. nextPt[1] = points[i + 3];
  34183. pt[0] = points[i];
  34184. pt[1] = points[i + 1];
  34185. stepPoints.push(pt[0], pt[1]);
  34186. switch (stepTurnAt) {
  34187. case 'end':
  34188. stepPt[baseIndex] = nextPt[baseIndex];
  34189. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  34190. stepPoints.push(stepPt[0], stepPt[1]);
  34191. break;
  34192. case 'middle':
  34193. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  34194. var stepPt2 = [];
  34195. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  34196. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  34197. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  34198. stepPoints.push(stepPt[0], stepPt[1]);
  34199. stepPoints.push(stepPt2[0], stepPt2[1]);
  34200. break;
  34201. default:
  34202. // default is start
  34203. stepPt[baseIndex] = pt[baseIndex];
  34204. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  34205. stepPoints.push(stepPt[0], stepPt[1]);
  34206. }
  34207. } // Last points
  34208. stepPoints.push(points[i++], points[i++]);
  34209. return stepPoints;
  34210. }
  34211. /**
  34212. * Clip color stops to edge. Avoid creating too large gradients.
  34213. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  34214. *
  34215. * The stops has been sorted from small to large.
  34216. */
  34217. function clipColorStops(colorStops, maxSize) {
  34218. var newColorStops = [];
  34219. var len = colorStops.length; // coord will always < 0 in prevOutOfRangeColorStop.
  34220. var prevOutOfRangeColorStop;
  34221. var prevInRangeColorStop;
  34222. function lerpStop(stop0, stop1, clippedCoord) {
  34223. var coord0 = stop0.coord;
  34224. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  34225. var color = lerp$1(p, [stop0.color, stop1.color]);
  34226. return {
  34227. coord: clippedCoord,
  34228. color: color
  34229. };
  34230. }
  34231. for (var i = 0; i < len; i++) {
  34232. var stop_1 = colorStops[i];
  34233. var coord = stop_1.coord;
  34234. if (coord < 0) {
  34235. prevOutOfRangeColorStop = stop_1;
  34236. } else if (coord > maxSize) {
  34237. if (prevInRangeColorStop) {
  34238. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  34239. } else if (prevOutOfRangeColorStop) {
  34240. // If there are two stops and coord range is between these two stops
  34241. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  34242. } // All following stop will be out of range. So just ignore them.
  34243. break;
  34244. } else {
  34245. if (prevOutOfRangeColorStop) {
  34246. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0)); // Reset
  34247. prevOutOfRangeColorStop = null;
  34248. }
  34249. newColorStops.push(stop_1);
  34250. prevInRangeColorStop = stop_1;
  34251. }
  34252. }
  34253. return newColorStops;
  34254. }
  34255. function getVisualGradient(data, coordSys, api) {
  34256. var visualMetaList = data.getVisual('visualMeta');
  34257. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  34258. // When data.count() is 0, gradient range can not be calculated.
  34259. return;
  34260. }
  34261. if (coordSys.type !== 'cartesian2d') {
  34262. if ("development" !== 'production') {
  34263. console.warn('Visual map on line style is only supported on cartesian2d.');
  34264. }
  34265. return;
  34266. }
  34267. var coordDim;
  34268. var visualMeta;
  34269. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  34270. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  34271. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  34272. if (coordDim === 'x' || coordDim === 'y') {
  34273. visualMeta = visualMetaList[i];
  34274. break;
  34275. }
  34276. }
  34277. if (!visualMeta) {
  34278. if ("development" !== 'production') {
  34279. console.warn('Visual map on line style only support x or y dimension.');
  34280. }
  34281. return;
  34282. } // If the area to be rendered is bigger than area defined by LinearGradient,
  34283. // the canvas spec prescribes that the color of the first stop and the last
  34284. // stop should be used. But if two stops are added at offset 0, in effect
  34285. // browsers use the color of the second stop to render area outside
  34286. // LinearGradient. So we can only infinitesimally extend area defined in
  34287. // LinearGradient to render `outerColors`.
  34288. var axis = coordSys.getAxis(coordDim); // dataToCoord mapping may not be linear, but must be monotonic.
  34289. var colorStops = map(visualMeta.stops, function (stop) {
  34290. // offset will be calculated later.
  34291. return {
  34292. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  34293. color: stop.color
  34294. };
  34295. });
  34296. var stopLen = colorStops.length;
  34297. var outerColors = visualMeta.outerColors.slice();
  34298. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  34299. colorStops.reverse();
  34300. outerColors.reverse();
  34301. }
  34302. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  34303. var inRangeStopLen = colorStopsInRange.length;
  34304. if (!inRangeStopLen && stopLen) {
  34305. // All stops are out of range. All will be the same color.
  34306. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  34307. }
  34308. var tinyExtent = 10; // Arbitrary value: 10px
  34309. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  34310. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  34311. var coordSpan = maxCoord - minCoord;
  34312. if (coordSpan < 1e-3) {
  34313. return 'transparent';
  34314. }
  34315. each(colorStopsInRange, function (stop) {
  34316. stop.offset = (stop.coord - minCoord) / coordSpan;
  34317. });
  34318. colorStopsInRange.push({
  34319. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  34320. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  34321. color: outerColors[1] || 'transparent'
  34322. });
  34323. colorStopsInRange.unshift({
  34324. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  34325. color: outerColors[0] || 'transparent'
  34326. });
  34327. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  34328. gradient[coordDim] = minCoord;
  34329. gradient[coordDim + '2'] = maxCoord;
  34330. return gradient;
  34331. }
  34332. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  34333. var showAllSymbol = seriesModel.get('showAllSymbol');
  34334. var isAuto = showAllSymbol === 'auto';
  34335. if (showAllSymbol && !isAuto) {
  34336. return;
  34337. }
  34338. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  34339. if (!categoryAxis) {
  34340. return;
  34341. } // Note that category label interval strategy might bring some weird effect
  34342. // in some scenario: users may wonder why some of the symbols are not
  34343. // displayed. So we show all symbols as possible as we can.
  34344. if (isAuto // Simplify the logic, do not determine label overlap here.
  34345. && canShowAllSymbolForCategory(categoryAxis, data)) {
  34346. return;
  34347. } // Otherwise follow the label interval strategy on category axis.
  34348. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  34349. var labelMap = {};
  34350. each(categoryAxis.getViewLabels(), function (labelItem) {
  34351. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  34352. labelMap[ordinalNumber] = 1;
  34353. });
  34354. return function (dataIndex) {
  34355. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  34356. };
  34357. }
  34358. function canShowAllSymbolForCategory(categoryAxis, data) {
  34359. // In mose cases, line is monotonous on category axis, and the label size
  34360. // is close with each other. So we check the symbol size and some of the
  34361. // label size alone with the category axis to estimate whether all symbol
  34362. // can be shown without overlap.
  34363. var axisExtent = categoryAxis.getExtent();
  34364. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  34365. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  34366. // Sampling some points, max 5.
  34367. var dataLen = data.count();
  34368. var step = Math.max(1, Math.round(dataLen / 5));
  34369. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  34370. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  34371. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  34372. * 1.5 > availSize) {
  34373. return false;
  34374. }
  34375. }
  34376. return true;
  34377. }
  34378. function isPointNull$1(x, y) {
  34379. return isNaN(x) || isNaN(y);
  34380. }
  34381. function getLastIndexNotNull(points) {
  34382. var len = points.length / 2;
  34383. for (; len > 0; len--) {
  34384. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  34385. break;
  34386. }
  34387. }
  34388. return len - 1;
  34389. }
  34390. function getPointAtIndex(points, idx) {
  34391. return [points[idx * 2], points[idx * 2 + 1]];
  34392. }
  34393. function getIndexRange(points, xOrY, dim) {
  34394. var len = points.length / 2;
  34395. var dimIdx = dim === 'x' ? 0 : 1;
  34396. var a;
  34397. var b;
  34398. var prevIndex = 0;
  34399. var nextIndex = -1;
  34400. for (var i = 0; i < len; i++) {
  34401. b = points[i * 2 + dimIdx];
  34402. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  34403. continue;
  34404. }
  34405. if (i === 0) {
  34406. a = b;
  34407. continue;
  34408. }
  34409. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  34410. nextIndex = i;
  34411. break;
  34412. }
  34413. prevIndex = i;
  34414. a = b;
  34415. }
  34416. return {
  34417. range: [prevIndex, nextIndex],
  34418. t: (xOrY - a) / (b - a)
  34419. };
  34420. }
  34421. function anyStateShowEndLabel(seriesModel) {
  34422. if (seriesModel.get(['endLabel', 'show'])) {
  34423. return true;
  34424. }
  34425. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  34426. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  34427. return true;
  34428. }
  34429. }
  34430. return false;
  34431. }
  34432. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  34433. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  34434. var endLabelModel_1 = seriesModel.getModel('endLabel');
  34435. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  34436. var data_1 = seriesModel.getData();
  34437. var labelAnimationRecord_1 = {
  34438. lastFrameIndex: 0
  34439. };
  34440. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  34441. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  34442. } : null;
  34443. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  34444. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  34445. var endLabel = lineView._endLabel;
  34446. if (endLabel && hasAnimation) {
  34447. if (labelAnimationRecord_1.originalX != null) {
  34448. endLabel.attr({
  34449. x: labelAnimationRecord_1.originalX,
  34450. y: labelAnimationRecord_1.originalY
  34451. });
  34452. }
  34453. }
  34454. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  34455. if (!seriesModel.get('clip', true)) {
  34456. var rectShape = clipPath.shape;
  34457. var expandSize = Math.max(rectShape.width, rectShape.height);
  34458. if (isHorizontal) {
  34459. rectShape.y -= expandSize;
  34460. rectShape.height += expandSize * 2;
  34461. } else {
  34462. rectShape.x -= expandSize;
  34463. rectShape.width += expandSize * 2;
  34464. }
  34465. } // Set to the final frame. To make sure label layout is right.
  34466. if (during) {
  34467. during(1, clipPath);
  34468. }
  34469. return clipPath;
  34470. } else {
  34471. if ("development" !== 'production') {
  34472. if (seriesModel.get(['endLabel', 'show'])) {
  34473. console.warn('endLabel is not supported for lines in polar systems.');
  34474. }
  34475. }
  34476. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34477. }
  34478. }
  34479. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  34480. var baseAxis = coordSys.getBaseAxis();
  34481. var isHorizontal = baseAxis.isHorizontal();
  34482. var isBaseInversed = baseAxis.inverse;
  34483. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  34484. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  34485. return {
  34486. normal: {
  34487. align: endLabelModel.get('align') || align,
  34488. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  34489. }
  34490. };
  34491. }
  34492. var LineView =
  34493. /** @class */
  34494. function (_super) {
  34495. __extends(LineView, _super);
  34496. function LineView() {
  34497. return _super !== null && _super.apply(this, arguments) || this;
  34498. }
  34499. LineView.prototype.init = function () {
  34500. var lineGroup = new Group();
  34501. var symbolDraw = new SymbolDraw();
  34502. this.group.add(symbolDraw.group);
  34503. this._symbolDraw = symbolDraw;
  34504. this._lineGroup = lineGroup;
  34505. };
  34506. LineView.prototype.render = function (seriesModel, ecModel, api) {
  34507. var _this = this;
  34508. var coordSys = seriesModel.coordinateSystem;
  34509. var group = this.group;
  34510. var data = seriesModel.getData();
  34511. var lineStyleModel = seriesModel.getModel('lineStyle');
  34512. var areaStyleModel = seriesModel.getModel('areaStyle');
  34513. var points = data.getLayout('points') || [];
  34514. var isCoordSysPolar = coordSys.type === 'polar';
  34515. var prevCoordSys = this._coordSys;
  34516. var symbolDraw = this._symbolDraw;
  34517. var polyline = this._polyline;
  34518. var polygon = this._polygon;
  34519. var lineGroup = this._lineGroup;
  34520. var hasAnimation = seriesModel.get('animation');
  34521. var isAreaChart = !areaStyleModel.isEmpty();
  34522. var valueOrigin = areaStyleModel.get('origin');
  34523. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34524. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  34525. var showSymbol = seriesModel.get('showSymbol');
  34526. var connectNulls = seriesModel.get('connectNulls');
  34527. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  34528. var oldData = this._data;
  34529. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34530. if (el.__temp) {
  34531. group.remove(el);
  34532. oldData.setItemGraphicEl(idx, null);
  34533. }
  34534. }); // Remove previous created symbols if showSymbol changed to false
  34535. if (!showSymbol) {
  34536. symbolDraw.remove();
  34537. }
  34538. group.add(lineGroup); // FIXME step not support polar
  34539. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  34540. var clipShapeForSymbol;
  34541. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34542. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  34543. // See #7913 and `test/dataZoom-clip.html`.
  34544. if (clipShapeForSymbol.width != null) {
  34545. clipShapeForSymbol.x -= 0.1;
  34546. clipShapeForSymbol.y -= 0.1;
  34547. clipShapeForSymbol.width += 0.2;
  34548. clipShapeForSymbol.height += 0.2;
  34549. } else if (clipShapeForSymbol.r0) {
  34550. clipShapeForSymbol.r0 -= 0.5;
  34551. clipShapeForSymbol.r += 0.5;
  34552. }
  34553. }
  34554. this._clipShapeForSymbol = clipShapeForSymbol;
  34555. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  34556. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  34557. showSymbol && symbolDraw.updateData(data, {
  34558. isIgnore: isIgnoreFunc,
  34559. clipShape: clipShapeForSymbol,
  34560. disableAnimation: true,
  34561. getSymbolPoint: function (idx) {
  34562. return [points[idx * 2], points[idx * 2 + 1]];
  34563. }
  34564. });
  34565. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  34566. if (step) {
  34567. // TODO If stacked series is not step
  34568. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  34569. if (stackedOnPoints) {
  34570. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  34571. }
  34572. }
  34573. polyline = this._newPolyline(points);
  34574. if (isAreaChart) {
  34575. polygon = this._newPolygon(points, stackedOnPoints);
  34576. } // If areaStyle is removed
  34577. else if (polygon) {
  34578. lineGroup.remove(polygon);
  34579. polygon = this._polygon = null;
  34580. } // NOTE: Must update _endLabel before setClipPath.
  34581. if (!isCoordSysPolar) {
  34582. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  34583. }
  34584. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  34585. } else {
  34586. if (isAreaChart && !polygon) {
  34587. // If areaStyle is added
  34588. polygon = this._newPolygon(points, stackedOnPoints);
  34589. } else if (polygon && !isAreaChart) {
  34590. // If areaStyle is removed
  34591. lineGroup.remove(polygon);
  34592. polygon = this._polygon = null;
  34593. } // NOTE: Must update _endLabel before setClipPath.
  34594. if (!isCoordSysPolar) {
  34595. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  34596. } // Update clipPath
  34597. var oldClipPath = lineGroup.getClipPath();
  34598. if (oldClipPath) {
  34599. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  34600. initProps(oldClipPath, {
  34601. shape: newClipPath.shape
  34602. }, seriesModel);
  34603. } else {
  34604. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  34605. } // Always update, or it is wrong in the case turning on legend
  34606. // because points are not changed
  34607. showSymbol && symbolDraw.updateData(data, {
  34608. isIgnore: isIgnoreFunc,
  34609. clipShape: clipShapeForSymbol,
  34610. disableAnimation: true,
  34611. getSymbolPoint: function (idx) {
  34612. return [points[idx * 2], points[idx * 2 + 1]];
  34613. }
  34614. }); // In the case data zoom triggerred refreshing frequently
  34615. // Data may not change if line has a category axis. So it should animate nothing
  34616. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  34617. if (hasAnimation) {
  34618. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  34619. } else {
  34620. // Not do it in update with animation
  34621. if (step) {
  34622. // TODO If stacked series is not step
  34623. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  34624. if (stackedOnPoints) {
  34625. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  34626. }
  34627. }
  34628. polyline.setShape({
  34629. points: points
  34630. });
  34631. polygon && polygon.setShape({
  34632. points: points,
  34633. stackedOnPoints: stackedOnPoints
  34634. });
  34635. }
  34636. }
  34637. }
  34638. var emphasisModel = seriesModel.getModel('emphasis');
  34639. var focus = emphasisModel.get('focus');
  34640. var blurScope = emphasisModel.get('blurScope');
  34641. var emphasisDisabled = emphasisModel.get('disabled');
  34642. polyline.useStyle(defaults( // Use color in lineStyle first
  34643. lineStyleModel.getLineStyle(), {
  34644. fill: 'none',
  34645. stroke: visualColor,
  34646. lineJoin: 'bevel'
  34647. }));
  34648. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  34649. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  34650. var emphasisLineStyle = polyline.getState('emphasis').style;
  34651. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  34652. } // Needs seriesIndex for focus
  34653. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  34654. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  34655. var smooth = getSmooth(seriesModel.get('smooth'));
  34656. var smoothMonotone = seriesModel.get('smoothMonotone');
  34657. polyline.setShape({
  34658. smooth: smooth,
  34659. smoothMonotone: smoothMonotone,
  34660. connectNulls: connectNulls
  34661. });
  34662. if (polygon) {
  34663. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34664. var stackedOnSmooth = 0;
  34665. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  34666. fill: visualColor,
  34667. opacity: 0.7,
  34668. lineJoin: 'bevel',
  34669. decal: data.getVisual('style').decal
  34670. }));
  34671. if (stackedOnSeries) {
  34672. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34673. }
  34674. polygon.setShape({
  34675. smooth: smooth,
  34676. stackedOnSmooth: stackedOnSmooth,
  34677. smoothMonotone: smoothMonotone,
  34678. connectNulls: connectNulls
  34679. });
  34680. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  34681. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  34682. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  34683. }
  34684. var changePolyState = function (toState) {
  34685. _this._changePolyState(toState);
  34686. };
  34687. data.eachItemGraphicEl(function (el) {
  34688. // Switch polyline / polygon state if element changed its state.
  34689. el && (el.onHoverStateChange = changePolyState);
  34690. });
  34691. this._polyline.onHoverStateChange = changePolyState;
  34692. this._data = data; // Save the coordinate system for transition animation when data changed
  34693. this._coordSys = coordSys;
  34694. this._stackedOnPoints = stackedOnPoints;
  34695. this._points = points;
  34696. this._step = step;
  34697. this._valueOrigin = valueOrigin;
  34698. if (seriesModel.get('triggerLineEvent')) {
  34699. this.packEventData(seriesModel, polyline);
  34700. polygon && this.packEventData(seriesModel, polygon);
  34701. }
  34702. };
  34703. LineView.prototype.packEventData = function (seriesModel, el) {
  34704. getECData(el).eventData = {
  34705. componentType: 'series',
  34706. componentSubType: 'line',
  34707. componentIndex: seriesModel.componentIndex,
  34708. seriesIndex: seriesModel.seriesIndex,
  34709. seriesName: seriesModel.name,
  34710. seriesType: 'line'
  34711. };
  34712. };
  34713. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  34714. var data = seriesModel.getData();
  34715. var dataIndex = queryDataIndex(data, payload);
  34716. this._changePolyState('emphasis');
  34717. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34718. var points = data.getLayout('points');
  34719. var symbol = data.getItemGraphicEl(dataIndex);
  34720. if (!symbol) {
  34721. // Create a temporary symbol if it is not exists
  34722. var x = points[dataIndex * 2];
  34723. var y = points[dataIndex * 2 + 1];
  34724. if (isNaN(x) || isNaN(y)) {
  34725. // Null data
  34726. return;
  34727. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  34728. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  34729. return;
  34730. }
  34731. var zlevel = seriesModel.get('zlevel');
  34732. var z = seriesModel.get('z');
  34733. symbol = new Symbol(data, dataIndex);
  34734. symbol.x = x;
  34735. symbol.y = y;
  34736. symbol.setZ(zlevel, z); // ensure label text of the temporary symbol is in front of line and area polygon
  34737. var symbolLabel = symbol.getSymbolPath().getTextContent();
  34738. if (symbolLabel) {
  34739. symbolLabel.zlevel = zlevel;
  34740. symbolLabel.z = z;
  34741. symbolLabel.z2 = this._polyline.z2 + 1;
  34742. }
  34743. symbol.__temp = true;
  34744. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  34745. symbol.stopSymbolAnimation(true);
  34746. this.group.add(symbol);
  34747. }
  34748. symbol.highlight();
  34749. } else {
  34750. // Highlight whole series
  34751. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  34752. }
  34753. };
  34754. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  34755. var data = seriesModel.getData();
  34756. var dataIndex = queryDataIndex(data, payload);
  34757. this._changePolyState('normal');
  34758. if (dataIndex != null && dataIndex >= 0) {
  34759. var symbol = data.getItemGraphicEl(dataIndex);
  34760. if (symbol) {
  34761. if (symbol.__temp) {
  34762. data.setItemGraphicEl(dataIndex, null);
  34763. this.group.remove(symbol);
  34764. } else {
  34765. symbol.downplay();
  34766. }
  34767. }
  34768. } else {
  34769. // FIXME
  34770. // can not downplay completely.
  34771. // Downplay whole series
  34772. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  34773. }
  34774. };
  34775. LineView.prototype._changePolyState = function (toState) {
  34776. var polygon = this._polygon;
  34777. setStatesFlag(this._polyline, toState);
  34778. polygon && setStatesFlag(polygon, toState);
  34779. };
  34780. LineView.prototype._newPolyline = function (points) {
  34781. var polyline = this._polyline; // Remove previous created polyline
  34782. if (polyline) {
  34783. this._lineGroup.remove(polyline);
  34784. }
  34785. polyline = new ECPolyline({
  34786. shape: {
  34787. points: points
  34788. },
  34789. segmentIgnoreThreshold: 2,
  34790. z2: 10
  34791. });
  34792. this._lineGroup.add(polyline);
  34793. this._polyline = polyline;
  34794. return polyline;
  34795. };
  34796. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  34797. var polygon = this._polygon; // Remove previous created polygon
  34798. if (polygon) {
  34799. this._lineGroup.remove(polygon);
  34800. }
  34801. polygon = new ECPolygon({
  34802. shape: {
  34803. points: points,
  34804. stackedOnPoints: stackedOnPoints
  34805. },
  34806. segmentIgnoreThreshold: 2
  34807. });
  34808. this._lineGroup.add(polygon);
  34809. this._polygon = polygon;
  34810. return polygon;
  34811. };
  34812. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  34813. var isHorizontalOrRadial;
  34814. var isCoordSysPolar;
  34815. var baseAxis = coordSys.getBaseAxis();
  34816. var isAxisInverse = baseAxis.inverse;
  34817. if (coordSys.type === 'cartesian2d') {
  34818. isHorizontalOrRadial = baseAxis.isHorizontal();
  34819. isCoordSysPolar = false;
  34820. } else if (coordSys.type === 'polar') {
  34821. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34822. isCoordSysPolar = true;
  34823. }
  34824. var seriesModel = data.hostModel;
  34825. var seriesDuration = seriesModel.get('animationDuration');
  34826. if (isFunction(seriesDuration)) {
  34827. seriesDuration = seriesDuration(null);
  34828. }
  34829. var seriesDalay = seriesModel.get('animationDelay') || 0;
  34830. var seriesDalayValue = isFunction(seriesDalay) ? seriesDalay(null) : seriesDalay;
  34831. data.eachItemGraphicEl(function (symbol, idx) {
  34832. var el = symbol;
  34833. if (el) {
  34834. var point = [symbol.x, symbol.y];
  34835. var start = void 0;
  34836. var end = void 0;
  34837. var current = void 0;
  34838. if (clipShape) {
  34839. if (isCoordSysPolar) {
  34840. var polarClip = clipShape;
  34841. var coord = coordSys.pointToCoord(point);
  34842. if (isHorizontalOrRadial) {
  34843. start = polarClip.startAngle;
  34844. end = polarClip.endAngle;
  34845. current = -coord[1] / 180 * Math.PI;
  34846. } else {
  34847. start = polarClip.r0;
  34848. end = polarClip.r;
  34849. current = coord[0];
  34850. }
  34851. } else {
  34852. var gridClip = clipShape;
  34853. if (isHorizontalOrRadial) {
  34854. start = gridClip.x;
  34855. end = gridClip.x + gridClip.width;
  34856. current = symbol.x;
  34857. } else {
  34858. start = gridClip.y + gridClip.height;
  34859. end = gridClip.y;
  34860. current = symbol.y;
  34861. }
  34862. }
  34863. }
  34864. var ratio = end === start ? 0 : (current - start) / (end - start);
  34865. if (isAxisInverse) {
  34866. ratio = 1 - ratio;
  34867. }
  34868. var delay = isFunction(seriesDalay) ? seriesDalay(idx) : seriesDuration * ratio + seriesDalayValue;
  34869. var symbolPath = el.getSymbolPath();
  34870. var text = symbolPath.getTextContent();
  34871. el.attr({
  34872. scaleX: 0,
  34873. scaleY: 0
  34874. });
  34875. el.animateTo({
  34876. scaleX: 1,
  34877. scaleY: 1
  34878. }, {
  34879. duration: 200,
  34880. setToFinal: true,
  34881. delay: delay
  34882. });
  34883. if (text) {
  34884. text.animateFrom({
  34885. style: {
  34886. opacity: 0
  34887. }
  34888. }, {
  34889. duration: 300,
  34890. delay: delay
  34891. });
  34892. }
  34893. symbolPath.disableLabelAnimation = true;
  34894. }
  34895. });
  34896. };
  34897. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  34898. var endLabelModel = seriesModel.getModel('endLabel');
  34899. if (anyStateShowEndLabel(seriesModel)) {
  34900. var data_2 = seriesModel.getData();
  34901. var polyline = this._polyline; // series may be filtered.
  34902. var points = data_2.getLayout('points');
  34903. if (!points) {
  34904. polyline.removeTextContent();
  34905. this._endLabel = null;
  34906. return;
  34907. }
  34908. var endLabel = this._endLabel;
  34909. if (!endLabel) {
  34910. endLabel = this._endLabel = new ZRText({
  34911. z2: 200 // should be higher than item symbol
  34912. });
  34913. endLabel.ignoreClip = true;
  34914. polyline.setTextContent(this._endLabel);
  34915. polyline.disableLabelAnimation = true;
  34916. } // Find last non-NaN data to display data
  34917. var dataIndex = getLastIndexNotNull(points);
  34918. if (dataIndex >= 0) {
  34919. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  34920. inheritColor: inheritColor,
  34921. labelFetcher: seriesModel,
  34922. labelDataIndex: dataIndex,
  34923. defaultText: function (dataIndex, opt, interpolatedValue) {
  34924. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  34925. },
  34926. enableTextSetter: true
  34927. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  34928. polyline.textConfig.position = null;
  34929. }
  34930. } else if (this._endLabel) {
  34931. this._polyline.removeTextContent();
  34932. this._endLabel = null;
  34933. }
  34934. };
  34935. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  34936. var endLabel = this._endLabel;
  34937. var polyline = this._polyline;
  34938. if (endLabel) {
  34939. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  34940. // The label is not prepared at this time.
  34941. if (percent < 1 && animationRecord.originalX == null) {
  34942. animationRecord.originalX = endLabel.x;
  34943. animationRecord.originalY = endLabel.y;
  34944. }
  34945. var points = data.getLayout('points');
  34946. var seriesModel = data.hostModel;
  34947. var connectNulls = seriesModel.get('connectNulls');
  34948. var precision = endLabelModel.get('precision');
  34949. var distance = endLabelModel.get('distance') || 0;
  34950. var baseAxis = coordSys.getBaseAxis();
  34951. var isHorizontal = baseAxis.isHorizontal();
  34952. var isBaseInversed = baseAxis.inverse;
  34953. var clipShape = clipRect.shape;
  34954. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  34955. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  34956. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  34957. var dim = isHorizontal ? 'x' : 'y';
  34958. var dataIndexRange = getIndexRange(points, xOrY, dim);
  34959. var indices = dataIndexRange.range;
  34960. var diff = indices[1] - indices[0];
  34961. var value = void 0;
  34962. if (diff >= 1) {
  34963. // diff > 1 && connectNulls, which is on the null data.
  34964. if (diff > 1 && !connectNulls) {
  34965. var pt = getPointAtIndex(points, indices[0]);
  34966. endLabel.attr({
  34967. x: pt[0] + distanceX,
  34968. y: pt[1] + distanceY
  34969. });
  34970. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  34971. } else {
  34972. var pt = polyline.getPointOn(xOrY, dim);
  34973. pt && endLabel.attr({
  34974. x: pt[0] + distanceX,
  34975. y: pt[1] + distanceY
  34976. });
  34977. var startValue = seriesModel.getRawValue(indices[0]);
  34978. var endValue = seriesModel.getRawValue(indices[1]);
  34979. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  34980. }
  34981. animationRecord.lastFrameIndex = indices[0];
  34982. } else {
  34983. // If diff <= 0, which is the range is not found(Include NaN)
  34984. // Choose the first point or last point.
  34985. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  34986. var pt = getPointAtIndex(points, idx);
  34987. valueAnimation && (value = seriesModel.getRawValue(idx));
  34988. endLabel.attr({
  34989. x: pt[0] + distanceX,
  34990. y: pt[1] + distanceY
  34991. });
  34992. }
  34993. if (valueAnimation) {
  34994. labelInner(endLabel).setLabelText(value);
  34995. }
  34996. }
  34997. };
  34998. /**
  34999. * @private
  35000. */
  35001. // FIXME Two value axis
  35002. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  35003. var polyline = this._polyline;
  35004. var polygon = this._polygon;
  35005. var seriesModel = data.hostModel;
  35006. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  35007. var current = diff.current;
  35008. var stackedOnCurrent = diff.stackedOnCurrent;
  35009. var next = diff.next;
  35010. var stackedOnNext = diff.stackedOnNext;
  35011. if (step) {
  35012. // TODO If stacked series is not step
  35013. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  35014. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  35015. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  35016. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  35017. } // Don't apply animation if diff is large.
  35018. // For better result and avoid memory explosion problems like
  35019. // https://github.com/apache/incubator-echarts/issues/12229
  35020. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  35021. polyline.stopAnimation();
  35022. polyline.setShape({
  35023. points: next
  35024. });
  35025. if (polygon) {
  35026. polygon.stopAnimation();
  35027. polygon.setShape({
  35028. points: next,
  35029. stackedOnPoints: stackedOnNext
  35030. });
  35031. }
  35032. return;
  35033. }
  35034. polyline.shape.__points = diff.current;
  35035. polyline.shape.points = current;
  35036. var target = {
  35037. shape: {
  35038. points: next
  35039. }
  35040. }; // Also animate the original points.
  35041. // If points reference is changed when turning into step line.
  35042. if (diff.current !== current) {
  35043. target.shape.__points = diff.next;
  35044. } // Stop previous animation.
  35045. polyline.stopAnimation();
  35046. updateProps(polyline, target, seriesModel);
  35047. if (polygon) {
  35048. polygon.setShape({
  35049. // Reuse the points with polyline.
  35050. points: current,
  35051. stackedOnPoints: stackedOnCurrent
  35052. });
  35053. polygon.stopAnimation();
  35054. updateProps(polygon, {
  35055. shape: {
  35056. stackedOnPoints: stackedOnNext
  35057. }
  35058. }, seriesModel); // If use attr directly in updateProps.
  35059. if (polyline.shape.points !== polygon.shape.points) {
  35060. polygon.shape.points = polyline.shape.points;
  35061. }
  35062. }
  35063. var updatedDataInfo = [];
  35064. var diffStatus = diff.status;
  35065. for (var i = 0; i < diffStatus.length; i++) {
  35066. var cmd = diffStatus[i].cmd;
  35067. if (cmd === '=') {
  35068. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  35069. if (el) {
  35070. updatedDataInfo.push({
  35071. el: el,
  35072. ptIdx: i // Index of points
  35073. });
  35074. }
  35075. }
  35076. }
  35077. if (polyline.animators && polyline.animators.length) {
  35078. polyline.animators[0].during(function () {
  35079. polygon && polygon.dirtyShape();
  35080. var points = polyline.shape.__points;
  35081. for (var i = 0; i < updatedDataInfo.length; i++) {
  35082. var el = updatedDataInfo[i].el;
  35083. var offset = updatedDataInfo[i].ptIdx * 2;
  35084. el.x = points[offset];
  35085. el.y = points[offset + 1];
  35086. el.markRedraw();
  35087. }
  35088. });
  35089. }
  35090. };
  35091. LineView.prototype.remove = function (ecModel) {
  35092. var group = this.group;
  35093. var oldData = this._data;
  35094. this._lineGroup.removeAll();
  35095. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  35096. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  35097. if (el.__temp) {
  35098. group.remove(el);
  35099. oldData.setItemGraphicEl(idx, null);
  35100. }
  35101. });
  35102. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  35103. };
  35104. LineView.type = 'line';
  35105. return LineView;
  35106. }(ChartView);
  35107. function pointsLayout(seriesType, forceStoreInTypedArray) {
  35108. return {
  35109. seriesType: seriesType,
  35110. plan: createRenderPlanner(),
  35111. reset: function (seriesModel) {
  35112. var data = seriesModel.getData();
  35113. var coordSys = seriesModel.coordinateSystem;
  35114. var pipelineContext = seriesModel.pipelineContext;
  35115. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  35116. if (!coordSys) {
  35117. return;
  35118. }
  35119. var dims = map(coordSys.dimensions, function (dim) {
  35120. return data.mapDimension(dim);
  35121. }).slice(0, 2);
  35122. var dimLen = dims.length;
  35123. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  35124. if (isDimensionStacked(data, dims[0])) {
  35125. dims[0] = stackResultDim;
  35126. }
  35127. if (isDimensionStacked(data, dims[1])) {
  35128. dims[1] = stackResultDim;
  35129. }
  35130. var store = data.getStore();
  35131. var dimIdx0 = data.getDimensionIndex(dims[0]);
  35132. var dimIdx1 = data.getDimensionIndex(dims[1]);
  35133. return dimLen && {
  35134. progress: function (params, data) {
  35135. var segCount = params.end - params.start;
  35136. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  35137. var tmpIn = [];
  35138. var tmpOut = [];
  35139. for (var i = params.start, offset = 0; i < params.end; i++) {
  35140. var point = void 0;
  35141. if (dimLen === 1) {
  35142. var x = store.get(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  35143. point = coordSys.dataToPoint(x, null, tmpOut);
  35144. } else {
  35145. tmpIn[0] = store.get(dimIdx0, i);
  35146. tmpIn[1] = store.get(dimIdx1, i); // Let coordinate system to handle the NaN data.
  35147. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  35148. }
  35149. if (useTypedArray) {
  35150. points[offset++] = point[0];
  35151. points[offset++] = point[1];
  35152. } else {
  35153. data.setItemLayout(i, point.slice());
  35154. }
  35155. }
  35156. useTypedArray && data.setLayout('points', points);
  35157. }
  35158. };
  35159. }
  35160. };
  35161. }
  35162. var samplers = {
  35163. average: function (frame) {
  35164. var sum = 0;
  35165. var count = 0;
  35166. for (var i = 0; i < frame.length; i++) {
  35167. if (!isNaN(frame[i])) {
  35168. sum += frame[i];
  35169. count++;
  35170. }
  35171. } // Return NaN if count is 0
  35172. return count === 0 ? NaN : sum / count;
  35173. },
  35174. sum: function (frame) {
  35175. var sum = 0;
  35176. for (var i = 0; i < frame.length; i++) {
  35177. // Ignore NaN
  35178. sum += frame[i] || 0;
  35179. }
  35180. return sum;
  35181. },
  35182. max: function (frame) {
  35183. var max = -Infinity;
  35184. for (var i = 0; i < frame.length; i++) {
  35185. frame[i] > max && (max = frame[i]);
  35186. } // NaN will cause illegal axis extent.
  35187. return isFinite(max) ? max : NaN;
  35188. },
  35189. min: function (frame) {
  35190. var min = Infinity;
  35191. for (var i = 0; i < frame.length; i++) {
  35192. frame[i] < min && (min = frame[i]);
  35193. } // NaN will cause illegal axis extent.
  35194. return isFinite(min) ? min : NaN;
  35195. },
  35196. // TODO
  35197. // Median
  35198. nearest: function (frame) {
  35199. return frame[0];
  35200. }
  35201. };
  35202. var indexSampler = function (frame) {
  35203. return Math.round(frame.length / 2);
  35204. };
  35205. function dataSample(seriesType) {
  35206. return {
  35207. seriesType: seriesType,
  35208. // FIXME:TS never used, so comment it
  35209. // modifyOutputEnd: true,
  35210. reset: function (seriesModel, ecModel, api) {
  35211. var data = seriesModel.getData();
  35212. var sampling = seriesModel.get('sampling');
  35213. var coordSys = seriesModel.coordinateSystem;
  35214. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  35215. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  35216. var baseAxis = coordSys.getBaseAxis();
  35217. var valueAxis = coordSys.getOtherAxis(baseAxis);
  35218. var extent = baseAxis.getExtent();
  35219. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  35220. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  35221. var rate = Math.round(count / size);
  35222. if (isFinite(rate) && rate > 1) {
  35223. if (sampling === 'lttb') {
  35224. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  35225. }
  35226. var sampler = void 0;
  35227. if (isString(sampling)) {
  35228. sampler = samplers[sampling];
  35229. } else if (isFunction(sampling)) {
  35230. sampler = sampling;
  35231. }
  35232. if (sampler) {
  35233. // Only support sample the first dim mapped from value axis.
  35234. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  35235. }
  35236. }
  35237. }
  35238. }
  35239. };
  35240. }
  35241. function install$1(registers) {
  35242. registers.registerChartView(LineView);
  35243. registers.registerSeriesModel(LineSeriesModel);
  35244. registers.registerLayout(pointsLayout('line', true));
  35245. registers.registerVisual({
  35246. seriesType: 'line',
  35247. reset: function (seriesModel) {
  35248. var data = seriesModel.getData(); // Visual coding for legend
  35249. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  35250. if (lineStyle && !lineStyle.stroke) {
  35251. // Fill in visual should be palette color if
  35252. // has color callback
  35253. lineStyle.stroke = data.getVisual('style').fill;
  35254. }
  35255. data.setVisual('legendLineStyle', lineStyle);
  35256. }
  35257. }); // Down sample after filter
  35258. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  35259. }
  35260. var BaseBarSeriesModel =
  35261. /** @class */
  35262. function (_super) {
  35263. __extends(BaseBarSeriesModel, _super);
  35264. function BaseBarSeriesModel() {
  35265. var _this = _super !== null && _super.apply(this, arguments) || this;
  35266. _this.type = BaseBarSeriesModel.type;
  35267. return _this;
  35268. }
  35269. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  35270. return createSeriesData(null, this, {
  35271. useEncodeDefaulter: true
  35272. });
  35273. };
  35274. BaseBarSeriesModel.prototype.getMarkerPosition = function (value) {
  35275. var coordSys = this.coordinateSystem;
  35276. if (coordSys && coordSys.clampData) {
  35277. // PENDING if clamp ?
  35278. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  35279. var data = this.getData();
  35280. var offset = data.getLayout('offset');
  35281. var size = data.getLayout('size');
  35282. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  35283. pt[offsetIndex] += offset + size / 2;
  35284. return pt;
  35285. }
  35286. return [NaN, NaN];
  35287. };
  35288. BaseBarSeriesModel.type = 'series.__base_bar__';
  35289. BaseBarSeriesModel.defaultOption = {
  35290. // zlevel: 0,
  35291. z: 2,
  35292. coordinateSystem: 'cartesian2d',
  35293. legendHoverLink: true,
  35294. // stack: null
  35295. // Cartesian coordinate system
  35296. // xAxisIndex: 0,
  35297. // yAxisIndex: 0,
  35298. barMinHeight: 0,
  35299. barMinAngle: 0,
  35300. // cursor: null,
  35301. large: false,
  35302. largeThreshold: 400,
  35303. progressive: 3e3,
  35304. progressiveChunkMode: 'mod'
  35305. };
  35306. return BaseBarSeriesModel;
  35307. }(SeriesModel);
  35308. SeriesModel.registerClass(BaseBarSeriesModel);
  35309. var BarSeriesModel =
  35310. /** @class */
  35311. function (_super) {
  35312. __extends(BarSeriesModel, _super);
  35313. function BarSeriesModel() {
  35314. var _this = _super !== null && _super.apply(this, arguments) || this;
  35315. _this.type = BarSeriesModel.type;
  35316. return _this;
  35317. }
  35318. BarSeriesModel.prototype.getInitialData = function () {
  35319. return createSeriesData(null, this, {
  35320. useEncodeDefaulter: true,
  35321. createInvertedIndices: !!this.get('realtimeSort', true) || null
  35322. });
  35323. };
  35324. /**
  35325. * @override
  35326. */
  35327. BarSeriesModel.prototype.getProgressive = function () {
  35328. // Do not support progressive in normal mode.
  35329. return this.get('large') ? this.get('progressive') : false;
  35330. };
  35331. /**
  35332. * @override
  35333. */
  35334. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  35335. // Do not support progressive in normal mode.
  35336. var progressiveThreshold = this.get('progressiveThreshold');
  35337. var largeThreshold = this.get('largeThreshold');
  35338. if (largeThreshold > progressiveThreshold) {
  35339. progressiveThreshold = largeThreshold;
  35340. }
  35341. return progressiveThreshold;
  35342. };
  35343. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  35344. return selectors.rect(data.getItemLayout(dataIndex));
  35345. };
  35346. BarSeriesModel.type = 'series.bar';
  35347. BarSeriesModel.dependencies = ['grid', 'polar'];
  35348. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  35349. // If clipped
  35350. // Only available on cartesian2d
  35351. clip: true,
  35352. roundCap: false,
  35353. showBackground: false,
  35354. backgroundStyle: {
  35355. color: 'rgba(180, 180, 180, 0.2)',
  35356. borderColor: null,
  35357. borderWidth: 0,
  35358. borderType: 'solid',
  35359. borderRadius: 0,
  35360. shadowBlur: 0,
  35361. shadowColor: null,
  35362. shadowOffsetX: 0,
  35363. shadowOffsetY: 0,
  35364. opacity: 1
  35365. },
  35366. select: {
  35367. itemStyle: {
  35368. borderColor: '#212121'
  35369. }
  35370. },
  35371. realtimeSort: false
  35372. });
  35373. return BarSeriesModel;
  35374. }(BaseBarSeriesModel);
  35375. /**
  35376. * Sausage: similar to sector, but have half circle on both sides
  35377. */
  35378. var SausageShape =
  35379. /** @class */
  35380. function () {
  35381. function SausageShape() {
  35382. this.cx = 0;
  35383. this.cy = 0;
  35384. this.r0 = 0;
  35385. this.r = 0;
  35386. this.startAngle = 0;
  35387. this.endAngle = Math.PI * 2;
  35388. this.clockwise = true;
  35389. }
  35390. return SausageShape;
  35391. }();
  35392. var SausagePath =
  35393. /** @class */
  35394. function (_super) {
  35395. __extends(SausagePath, _super);
  35396. function SausagePath(opts) {
  35397. var _this = _super.call(this, opts) || this;
  35398. _this.type = 'sausage';
  35399. return _this;
  35400. }
  35401. SausagePath.prototype.getDefaultShape = function () {
  35402. return new SausageShape();
  35403. };
  35404. SausagePath.prototype.buildPath = function (ctx, shape) {
  35405. var cx = shape.cx;
  35406. var cy = shape.cy;
  35407. var r0 = Math.max(shape.r0 || 0, 0);
  35408. var r = Math.max(shape.r, 0);
  35409. var dr = (r - r0) * 0.5;
  35410. var rCenter = r0 + dr;
  35411. var startAngle = shape.startAngle;
  35412. var endAngle = shape.endAngle;
  35413. var clockwise = shape.clockwise;
  35414. var PI2 = Math.PI * 2;
  35415. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  35416. if (!lessThanCircle) {
  35417. // Normalize angles
  35418. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  35419. }
  35420. var unitStartX = Math.cos(startAngle);
  35421. var unitStartY = Math.sin(startAngle);
  35422. var unitEndX = Math.cos(endAngle);
  35423. var unitEndY = Math.sin(endAngle);
  35424. if (lessThanCircle) {
  35425. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  35426. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  35427. } else {
  35428. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  35429. }
  35430. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  35431. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  35432. if (r0 !== 0) {
  35433. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  35434. } // ctx.closePath();
  35435. };
  35436. return SausagePath;
  35437. }(Path);
  35438. function createSectorCalculateTextPosition(positionMapping, opts) {
  35439. opts = opts || {};
  35440. var isRoundCap = opts.isRoundCap;
  35441. return function (out, opts, boundingRect) {
  35442. var textPosition = opts.position;
  35443. if (!textPosition || textPosition instanceof Array) {
  35444. return calculateTextPosition(out, opts, boundingRect);
  35445. }
  35446. var mappedSectorPosition = positionMapping(textPosition);
  35447. var distance = opts.distance != null ? opts.distance : 5;
  35448. var sector = this.shape;
  35449. var cx = sector.cx;
  35450. var cy = sector.cy;
  35451. var r = sector.r;
  35452. var r0 = sector.r0;
  35453. var middleR = (r + r0) / 2;
  35454. var startAngle = sector.startAngle;
  35455. var endAngle = sector.endAngle;
  35456. var middleAngle = (startAngle + endAngle) / 2;
  35457. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  35458. var mathCos = Math.cos;
  35459. var mathSin = Math.sin; // base position: top-left
  35460. var x = cx + r * mathCos(startAngle);
  35461. var y = cy + r * mathSin(startAngle);
  35462. var textAlign = 'left';
  35463. var textVerticalAlign = 'top';
  35464. switch (mappedSectorPosition) {
  35465. case 'startArc':
  35466. x = cx + (r0 - distance) * mathCos(middleAngle);
  35467. y = cy + (r0 - distance) * mathSin(middleAngle);
  35468. textAlign = 'center';
  35469. textVerticalAlign = 'top';
  35470. break;
  35471. case 'insideStartArc':
  35472. x = cx + (r0 + distance) * mathCos(middleAngle);
  35473. y = cy + (r0 + distance) * mathSin(middleAngle);
  35474. textAlign = 'center';
  35475. textVerticalAlign = 'bottom';
  35476. break;
  35477. case 'startAngle':
  35478. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  35479. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  35480. textAlign = 'right';
  35481. textVerticalAlign = 'middle';
  35482. break;
  35483. case 'insideStartAngle':
  35484. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  35485. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  35486. textAlign = 'left';
  35487. textVerticalAlign = 'middle';
  35488. break;
  35489. case 'middle':
  35490. x = cx + middleR * mathCos(middleAngle);
  35491. y = cy + middleR * mathSin(middleAngle);
  35492. textAlign = 'center';
  35493. textVerticalAlign = 'middle';
  35494. break;
  35495. case 'endArc':
  35496. x = cx + (r + distance) * mathCos(middleAngle);
  35497. y = cy + (r + distance) * mathSin(middleAngle);
  35498. textAlign = 'center';
  35499. textVerticalAlign = 'bottom';
  35500. break;
  35501. case 'insideEndArc':
  35502. x = cx + (r - distance) * mathCos(middleAngle);
  35503. y = cy + (r - distance) * mathSin(middleAngle);
  35504. textAlign = 'center';
  35505. textVerticalAlign = 'top';
  35506. break;
  35507. case 'endAngle':
  35508. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  35509. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  35510. textAlign = 'left';
  35511. textVerticalAlign = 'middle';
  35512. break;
  35513. case 'insideEndAngle':
  35514. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  35515. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  35516. textAlign = 'right';
  35517. textVerticalAlign = 'middle';
  35518. break;
  35519. default:
  35520. return calculateTextPosition(out, opts, boundingRect);
  35521. }
  35522. out = out || {};
  35523. out.x = x;
  35524. out.y = y;
  35525. out.align = textAlign;
  35526. out.verticalAlign = textVerticalAlign;
  35527. return out;
  35528. };
  35529. }
  35530. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  35531. if (isNumber(rotateType)) {
  35532. // user-set rotation
  35533. sector.setTextConfig({
  35534. rotation: rotateType
  35535. });
  35536. return;
  35537. } else if (isArray(textPosition)) {
  35538. // user-set position, use 0 as auto rotation
  35539. sector.setTextConfig({
  35540. rotation: 0
  35541. });
  35542. return;
  35543. }
  35544. var shape = sector.shape;
  35545. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  35546. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  35547. var middleAngle = (startAngle + endAngle) / 2;
  35548. var anchorAngle;
  35549. var mappedSectorPosition = positionMapping(textPosition);
  35550. switch (mappedSectorPosition) {
  35551. case 'startArc':
  35552. case 'insideStartArc':
  35553. case 'middle':
  35554. case 'insideEndArc':
  35555. case 'endArc':
  35556. anchorAngle = middleAngle;
  35557. break;
  35558. case 'startAngle':
  35559. case 'insideStartAngle':
  35560. anchorAngle = startAngle;
  35561. break;
  35562. case 'endAngle':
  35563. case 'insideEndAngle':
  35564. anchorAngle = endAngle;
  35565. break;
  35566. default:
  35567. sector.setTextConfig({
  35568. rotation: 0
  35569. });
  35570. return;
  35571. }
  35572. var rotate = Math.PI * 1.5 - anchorAngle;
  35573. /**
  35574. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  35575. * half round flipped to increase readability. However, only middle
  35576. * position supports this for now, because in other positions, the
  35577. * anchor point is not at the center of the text, so the positions
  35578. * after rotating is not as expected.
  35579. */
  35580. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  35581. rotate -= Math.PI;
  35582. }
  35583. sector.setTextConfig({
  35584. rotation: rotate
  35585. });
  35586. }
  35587. function adjustAngleDistanceX(angle, distance, isEnd) {
  35588. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  35589. }
  35590. function adjustAngleDistanceY(angle, distance, isEnd) {
  35591. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  35592. }
  35593. var mathMax$6 = Math.max;
  35594. var mathMin$6 = Math.min;
  35595. function getClipArea(coord, data) {
  35596. var coordSysClipArea = coord.getArea && coord.getArea();
  35597. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  35598. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  35599. // We should not clip this part.
  35600. // See test/bar2.html
  35601. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  35602. var expandWidth = data.getLayout('bandWidth');
  35603. if (baseAxis.isHorizontal()) {
  35604. coordSysClipArea.x -= expandWidth;
  35605. coordSysClipArea.width += expandWidth * 2;
  35606. } else {
  35607. coordSysClipArea.y -= expandWidth;
  35608. coordSysClipArea.height += expandWidth * 2;
  35609. }
  35610. }
  35611. }
  35612. return coordSysClipArea;
  35613. }
  35614. var BarView =
  35615. /** @class */
  35616. function (_super) {
  35617. __extends(BarView, _super);
  35618. function BarView() {
  35619. var _this = _super.call(this) || this;
  35620. _this.type = BarView.type;
  35621. _this._isFirstFrame = true;
  35622. return _this;
  35623. }
  35624. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  35625. this._model = seriesModel;
  35626. this._removeOnRenderedListener(api);
  35627. this._updateDrawMode(seriesModel);
  35628. var coordinateSystemType = seriesModel.get('coordinateSystem');
  35629. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  35630. // Clear previously rendered progressive elements.
  35631. this._progressiveEls = null;
  35632. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  35633. } else if ("development" !== 'production') {
  35634. warn('Only cartesian2d and polar supported for bar.');
  35635. }
  35636. };
  35637. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  35638. this._clear();
  35639. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  35640. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  35641. this._updateLargeClip(seriesModel);
  35642. };
  35643. BarView.prototype.incrementalRender = function (params, seriesModel) {
  35644. // Reset
  35645. this._progressiveEls = []; // Do not support progressive in normal mode.
  35646. this._incrementalRenderLarge(params, seriesModel);
  35647. };
  35648. BarView.prototype.eachRendered = function (cb) {
  35649. traverseElements(this._progressiveEls || this.group, cb);
  35650. };
  35651. BarView.prototype._updateDrawMode = function (seriesModel) {
  35652. var isLargeDraw = seriesModel.pipelineContext.large;
  35653. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  35654. this._isLargeDraw = isLargeDraw;
  35655. this._clear();
  35656. }
  35657. };
  35658. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  35659. var group = this.group;
  35660. var data = seriesModel.getData();
  35661. var oldData = this._data;
  35662. var coord = seriesModel.coordinateSystem;
  35663. var baseAxis = coord.getBaseAxis();
  35664. var isHorizontalOrRadial;
  35665. if (coord.type === 'cartesian2d') {
  35666. isHorizontalOrRadial = baseAxis.isHorizontal();
  35667. } else if (coord.type === 'polar') {
  35668. isHorizontalOrRadial = baseAxis.dim === 'angle';
  35669. }
  35670. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  35671. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  35672. if (realtimeSortCfg) {
  35673. this._enableRealtimeSort(realtimeSortCfg, data, api);
  35674. }
  35675. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  35676. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  35677. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  35678. // And don't want the label are clipped.
  35679. var roundCap = seriesModel.get('roundCap', true);
  35680. var drawBackground = seriesModel.get('showBackground', true);
  35681. var backgroundModel = seriesModel.getModel('backgroundStyle');
  35682. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  35683. var bgEls = [];
  35684. var oldBgEls = this._backgroundEls;
  35685. var isInitSort = payload && payload.isInitSort;
  35686. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  35687. function createBackground(dataIndex) {
  35688. var bgLayout = getLayout[coord.type](data, dataIndex);
  35689. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  35690. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  35691. if (coord.type === 'cartesian2d') {
  35692. bgEl.setShape('r', barBorderRadius);
  35693. }
  35694. bgEls[dataIndex] = bgEl;
  35695. return bgEl;
  35696. }
  35697. data.diff(oldData).add(function (dataIndex) {
  35698. var itemModel = data.getItemModel(dataIndex);
  35699. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  35700. if (drawBackground) {
  35701. createBackground(dataIndex);
  35702. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  35703. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  35704. return;
  35705. }
  35706. var isClipped = false;
  35707. if (needsClip) {
  35708. // Clip will modify the layout params.
  35709. // And return a boolean to determine if the shape are fully clipped.
  35710. isClipped = clip[coord.type](coordSysClipArea, layout);
  35711. }
  35712. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  35713. if (realtimeSortCfg) {
  35714. /**
  35715. * Force label animation because even if the element is
  35716. * ignored because it's clipped, it may not be clipped after
  35717. * changing order. Then, if not using forceLabelAnimation,
  35718. * the label animation was never started, in which case,
  35719. * the label will be the final value and doesn't have label
  35720. * animation.
  35721. */
  35722. el.forceLabelAnimation = true;
  35723. }
  35724. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  35725. if (isInitSort) {
  35726. el.attr({
  35727. shape: layout
  35728. });
  35729. } else if (realtimeSortCfg) {
  35730. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  35731. } else {
  35732. initProps(el, {
  35733. shape: layout
  35734. }, seriesModel, dataIndex);
  35735. }
  35736. data.setItemGraphicEl(dataIndex, el);
  35737. group.add(el);
  35738. el.ignore = isClipped;
  35739. }).update(function (newIndex, oldIndex) {
  35740. var itemModel = data.getItemModel(newIndex);
  35741. var layout = getLayout[coord.type](data, newIndex, itemModel);
  35742. if (drawBackground) {
  35743. var bgEl = void 0;
  35744. if (oldBgEls.length === 0) {
  35745. bgEl = createBackground(oldIndex);
  35746. } else {
  35747. bgEl = oldBgEls[oldIndex];
  35748. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  35749. if (coord.type === 'cartesian2d') {
  35750. bgEl.setShape('r', barBorderRadius);
  35751. }
  35752. bgEls[newIndex] = bgEl;
  35753. }
  35754. var bgLayout = getLayout[coord.type](data, newIndex);
  35755. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  35756. updateProps(bgEl, {
  35757. shape: shape
  35758. }, animationModel, newIndex);
  35759. }
  35760. var el = oldData.getItemGraphicEl(oldIndex);
  35761. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  35762. group.remove(el);
  35763. return;
  35764. }
  35765. var isClipped = false;
  35766. if (needsClip) {
  35767. isClipped = clip[coord.type](coordSysClipArea, layout);
  35768. if (isClipped) {
  35769. group.remove(el);
  35770. }
  35771. }
  35772. if (!el) {
  35773. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  35774. } else {
  35775. saveOldStyle(el);
  35776. }
  35777. if (realtimeSortCfg) {
  35778. el.forceLabelAnimation = true;
  35779. }
  35780. if (isChangeOrder) {
  35781. var textEl = el.getTextContent();
  35782. if (textEl) {
  35783. var labelInnerStore = labelInner(textEl);
  35784. if (labelInnerStore.prevValue != null) {
  35785. /**
  35786. * Set preValue to be value so that no new label
  35787. * should be started, otherwise, it will take a full
  35788. * `animationDurationUpdate` time to finish the
  35789. * animation, which is not expected.
  35790. */
  35791. labelInnerStore.prevValue = labelInnerStore.value;
  35792. }
  35793. }
  35794. } // Not change anything if only order changed.
  35795. // Especially not change label.
  35796. else {
  35797. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  35798. }
  35799. if (isInitSort) {
  35800. el.attr({
  35801. shape: layout
  35802. });
  35803. } else if (realtimeSortCfg) {
  35804. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  35805. } else {
  35806. updateProps(el, {
  35807. shape: layout
  35808. }, seriesModel, newIndex, null);
  35809. }
  35810. data.setItemGraphicEl(newIndex, el);
  35811. el.ignore = isClipped;
  35812. group.add(el);
  35813. }).remove(function (dataIndex) {
  35814. var el = oldData.getItemGraphicEl(dataIndex);
  35815. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  35816. }).execute();
  35817. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  35818. bgGroup.removeAll();
  35819. for (var i = 0; i < bgEls.length; ++i) {
  35820. bgGroup.add(bgEls[i]);
  35821. }
  35822. group.add(bgGroup);
  35823. this._backgroundEls = bgEls;
  35824. this._data = data;
  35825. };
  35826. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  35827. this._clear();
  35828. createLarge(seriesModel, this.group);
  35829. this._updateLargeClip(seriesModel);
  35830. };
  35831. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  35832. this._removeBackground();
  35833. createLarge(seriesModel, this.group, this._progressiveEls, true);
  35834. };
  35835. BarView.prototype._updateLargeClip = function (seriesModel) {
  35836. // Use clipPath in large mode.
  35837. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  35838. var group = this.group;
  35839. if (clipPath) {
  35840. group.setClipPath(clipPath);
  35841. } else {
  35842. group.removeClipPath();
  35843. }
  35844. };
  35845. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  35846. var _this = this; // If no data in the first frame, wait for data to initSort
  35847. if (!data.count()) {
  35848. return;
  35849. }
  35850. var baseAxis = realtimeSortCfg.baseAxis;
  35851. if (this._isFirstFrame) {
  35852. this._dispatchInitSort(data, realtimeSortCfg, api);
  35853. this._isFirstFrame = false;
  35854. } else {
  35855. var orderMapping_1 = function (idx) {
  35856. var el = data.getItemGraphicEl(idx);
  35857. var shape = el && el.shape;
  35858. return shape && // The result should be consistent with the initial sort by data value.
  35859. // Do not support the case that both positive and negative exist.
  35860. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width) // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  35861. || 0;
  35862. };
  35863. this._onRendered = function () {
  35864. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  35865. };
  35866. api.getZr().on('rendered', this._onRendered);
  35867. }
  35868. };
  35869. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  35870. var info = [];
  35871. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  35872. var mappedValue = orderMapping(dataIdx);
  35873. mappedValue = mappedValue == null ? NaN : mappedValue;
  35874. info.push({
  35875. dataIndex: dataIdx,
  35876. mappedValue: mappedValue,
  35877. ordinalNumber: ordinalNumber
  35878. });
  35879. });
  35880. info.sort(function (a, b) {
  35881. // If NaN, it will be treated as min val.
  35882. return b.mappedValue - a.mappedValue;
  35883. });
  35884. return {
  35885. ordinalNumbers: map(info, function (item) {
  35886. return item.ordinalNumber;
  35887. })
  35888. };
  35889. };
  35890. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  35891. var scale = baseAxis.scale;
  35892. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  35893. var lastValue = Number.MAX_VALUE;
  35894. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  35895. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  35896. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  35897. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  35898. : orderMapping(data.indexOfRawIndex(rawIdx));
  35899. if (value > lastValue) {
  35900. return true;
  35901. }
  35902. lastValue = value;
  35903. }
  35904. return false;
  35905. };
  35906. /*
  35907. * Consider the case when A and B changed order, whose representing
  35908. * bars are both out of sight, we don't wish to trigger reorder action
  35909. * as long as the order in the view doesn't change.
  35910. */
  35911. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  35912. var scale = baseAxis.scale;
  35913. var extent = scale.getExtent();
  35914. var tickNum = Math.max(0, extent[0]);
  35915. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  35916. for (; tickNum <= tickMax; ++tickNum) {
  35917. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  35918. return true;
  35919. }
  35920. }
  35921. };
  35922. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  35923. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  35924. return;
  35925. }
  35926. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  35927. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  35928. this._removeOnRenderedListener(api);
  35929. api.dispatchAction({
  35930. type: 'changeAxisOrder',
  35931. componentType: baseAxis.dim + 'Axis',
  35932. axisId: baseAxis.index,
  35933. sortInfo: sortInfo
  35934. });
  35935. }
  35936. };
  35937. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  35938. var baseAxis = realtimeSortCfg.baseAxis;
  35939. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  35940. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  35941. });
  35942. api.dispatchAction({
  35943. type: 'changeAxisOrder',
  35944. componentType: baseAxis.dim + 'Axis',
  35945. isInitSort: true,
  35946. axisId: baseAxis.index,
  35947. sortInfo: sortResult
  35948. });
  35949. };
  35950. BarView.prototype.remove = function (ecModel, api) {
  35951. this._clear(this._model);
  35952. this._removeOnRenderedListener(api);
  35953. };
  35954. BarView.prototype.dispose = function (ecModel, api) {
  35955. this._removeOnRenderedListener(api);
  35956. };
  35957. BarView.prototype._removeOnRenderedListener = function (api) {
  35958. if (this._onRendered) {
  35959. api.getZr().off('rendered', this._onRendered);
  35960. this._onRendered = null;
  35961. }
  35962. };
  35963. BarView.prototype._clear = function (model) {
  35964. var group = this.group;
  35965. var data = this._data;
  35966. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  35967. this._removeBackground();
  35968. this._backgroundEls = [];
  35969. data.eachItemGraphicEl(function (el) {
  35970. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  35971. });
  35972. } else {
  35973. group.removeAll();
  35974. }
  35975. this._data = null;
  35976. this._isFirstFrame = true;
  35977. };
  35978. BarView.prototype._removeBackground = function () {
  35979. this.group.remove(this._backgroundGroup);
  35980. this._backgroundGroup = null;
  35981. };
  35982. BarView.type = 'bar';
  35983. return BarView;
  35984. }(ChartView);
  35985. var clip = {
  35986. cartesian2d: function (coordSysBoundingRect, layout) {
  35987. var signWidth = layout.width < 0 ? -1 : 1;
  35988. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  35989. if (signWidth < 0) {
  35990. layout.x += layout.width;
  35991. layout.width = -layout.width;
  35992. }
  35993. if (signHeight < 0) {
  35994. layout.y += layout.height;
  35995. layout.height = -layout.height;
  35996. }
  35997. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  35998. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  35999. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  36000. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  36001. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  36002. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  36003. var xClipped = x2 < x;
  36004. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  36005. // But we should also place the element at the edge of the coord sys bounding rect.
  36006. // Beause if data changed and the bar show again, its transition animaiton
  36007. // will begin at this place.
  36008. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  36009. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  36010. layout.width = xClipped ? 0 : x2 - x;
  36011. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  36012. if (signWidth < 0) {
  36013. layout.x += layout.width;
  36014. layout.width = -layout.width;
  36015. }
  36016. if (signHeight < 0) {
  36017. layout.y += layout.height;
  36018. layout.height = -layout.height;
  36019. }
  36020. return xClipped || yClipped;
  36021. },
  36022. polar: function (coordSysClipArea, layout) {
  36023. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  36024. if (signR < 0) {
  36025. var tmp = layout.r;
  36026. layout.r = layout.r0;
  36027. layout.r0 = tmp;
  36028. }
  36029. var r = mathMin$6(layout.r, coordSysClipArea.r);
  36030. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  36031. layout.r = r;
  36032. layout.r0 = r0;
  36033. var clipped = r - r0 < 0; // Reverse back
  36034. if (signR < 0) {
  36035. var tmp = layout.r;
  36036. layout.r = layout.r0;
  36037. layout.r0 = tmp;
  36038. }
  36039. return clipped;
  36040. }
  36041. };
  36042. var elementCreator = {
  36043. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  36044. var rect = new Rect({
  36045. shape: extend({}, layout),
  36046. z2: 1
  36047. });
  36048. rect.__dataIndex = newIndex;
  36049. rect.name = 'item';
  36050. if (animationModel) {
  36051. var rectShape = rect.shape;
  36052. var animateProperty = isHorizontal ? 'height' : 'width';
  36053. rectShape[animateProperty] = 0;
  36054. }
  36055. return rect;
  36056. },
  36057. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  36058. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  36059. var sector = new ShapeClass({
  36060. shape: layout,
  36061. z2: 1
  36062. });
  36063. sector.name = 'item';
  36064. var positionMap = createPolarPositionMapping(isRadial);
  36065. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  36066. isRoundCap: ShapeClass === SausagePath
  36067. }); // Animation
  36068. if (animationModel) {
  36069. var sectorShape = sector.shape;
  36070. var animateProperty = isRadial ? 'r' : 'endAngle';
  36071. var animateTarget = {};
  36072. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  36073. animateTarget[animateProperty] = layout[animateProperty];
  36074. (isUpdate ? updateProps : initProps)(sector, {
  36075. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  36076. }, animationModel);
  36077. }
  36078. return sector;
  36079. }
  36080. };
  36081. function shouldRealtimeSort(seriesModel, coordSys) {
  36082. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  36083. var baseAxis = coordSys.getBaseAxis();
  36084. if ("development" !== 'production') {
  36085. if (realtimeSortOption) {
  36086. if (baseAxis.type !== 'category') {
  36087. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  36088. }
  36089. if (coordSys.type !== 'cartesian2d') {
  36090. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  36091. }
  36092. }
  36093. }
  36094. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  36095. return {
  36096. baseAxis: baseAxis,
  36097. otherAxis: coordSys.getOtherAxis(baseAxis)
  36098. };
  36099. }
  36100. }
  36101. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  36102. var seriesTarget;
  36103. var axisTarget;
  36104. if (isHorizontal) {
  36105. axisTarget = {
  36106. x: layout.x,
  36107. width: layout.width
  36108. };
  36109. seriesTarget = {
  36110. y: layout.y,
  36111. height: layout.height
  36112. };
  36113. } else {
  36114. axisTarget = {
  36115. y: layout.y,
  36116. height: layout.height
  36117. };
  36118. seriesTarget = {
  36119. x: layout.x,
  36120. width: layout.width
  36121. };
  36122. }
  36123. if (!isChangeOrder) {
  36124. // Keep the original growth animation if only axis order changed.
  36125. // Not start a new animation.
  36126. (isUpdate ? updateProps : initProps)(el, {
  36127. shape: seriesTarget
  36128. }, seriesAnimationModel, newIndex, null);
  36129. }
  36130. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  36131. (isUpdate ? updateProps : initProps)(el, {
  36132. shape: axisTarget
  36133. }, axisAnimationModel, newIndex);
  36134. }
  36135. function checkPropertiesNotValid(obj, props) {
  36136. for (var i = 0; i < props.length; i++) {
  36137. if (!isFinite(obj[props[i]])) {
  36138. return true;
  36139. }
  36140. }
  36141. return false;
  36142. }
  36143. var rectPropties = ['x', 'y', 'width', 'height'];
  36144. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  36145. var isValidLayout = {
  36146. cartesian2d: function (layout) {
  36147. return !checkPropertiesNotValid(layout, rectPropties);
  36148. },
  36149. polar: function (layout) {
  36150. return !checkPropertiesNotValid(layout, polarPropties);
  36151. }
  36152. };
  36153. var getLayout = {
  36154. // itemModel is only used to get borderWidth, which is not needed
  36155. // when calculating bar background layout.
  36156. cartesian2d: function (data, dataIndex, itemModel) {
  36157. var layout = data.getItemLayout(dataIndex);
  36158. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  36159. var signX = layout.width > 0 ? 1 : -1;
  36160. var signY = layout.height > 0 ? 1 : -1;
  36161. return {
  36162. x: layout.x + signX * fixedLineWidth / 2,
  36163. y: layout.y + signY * fixedLineWidth / 2,
  36164. width: layout.width - signX * fixedLineWidth,
  36165. height: layout.height - signY * fixedLineWidth
  36166. };
  36167. },
  36168. polar: function (data, dataIndex, itemModel) {
  36169. var layout = data.getItemLayout(dataIndex);
  36170. return {
  36171. cx: layout.cx,
  36172. cy: layout.cy,
  36173. r0: layout.r0,
  36174. r: layout.r,
  36175. startAngle: layout.startAngle,
  36176. endAngle: layout.endAngle,
  36177. clockwise: layout.clockwise
  36178. };
  36179. }
  36180. };
  36181. function isZeroOnPolar(layout) {
  36182. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  36183. }
  36184. function createPolarPositionMapping(isRadial) {
  36185. return function (isRadial) {
  36186. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  36187. return function (position) {
  36188. switch (position) {
  36189. case 'start':
  36190. case 'insideStart':
  36191. case 'end':
  36192. case 'insideEnd':
  36193. return position + arcOrAngle;
  36194. default:
  36195. return position;
  36196. }
  36197. };
  36198. }(isRadial);
  36199. }
  36200. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  36201. var style = data.getItemVisual(dataIndex, 'style');
  36202. if (!isPolar) {
  36203. el.setShape('r', itemModel.get(['itemStyle', 'borderRadius']) || 0);
  36204. }
  36205. el.useStyle(style);
  36206. var cursorStyle = itemModel.getShallow('cursor');
  36207. cursorStyle && el.attr('cursor', cursorStyle);
  36208. 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';
  36209. var labelStatesModels = getLabelStatesModels(itemModel);
  36210. setLabelStyle(el, labelStatesModels, {
  36211. labelFetcher: seriesModel,
  36212. labelDataIndex: dataIndex,
  36213. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  36214. inheritColor: style.fill,
  36215. defaultOpacity: style.opacity,
  36216. defaultOutsidePosition: labelPositionOutside
  36217. });
  36218. var label = el.getTextContent();
  36219. if (isPolar && label) {
  36220. var position = itemModel.get(['label', 'position']);
  36221. el.textConfig.inside = position === 'middle' ? true : null;
  36222. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  36223. }
  36224. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  36225. return getDefaultInterpolatedLabel(data, value);
  36226. });
  36227. var emphasisModel = itemModel.getModel(['emphasis']);
  36228. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  36229. setStatesStylesFromModel(el, itemModel);
  36230. if (isZeroOnPolar(layout)) {
  36231. el.style.fill = 'none';
  36232. el.style.stroke = 'none';
  36233. each(el.states, function (state) {
  36234. if (state.style) {
  36235. state.style.fill = state.style.stroke = 'none';
  36236. }
  36237. });
  36238. }
  36239. } // In case width or height are too small.
  36240. function getLineWidth(itemModel, rawLayout) {
  36241. // Has no border.
  36242. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  36243. if (!borderColor || borderColor === 'none') {
  36244. return 0;
  36245. }
  36246. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0; // width or height may be NaN for empty data
  36247. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  36248. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  36249. return Math.min(lineWidth, width, height);
  36250. }
  36251. var LagePathShape =
  36252. /** @class */
  36253. function () {
  36254. function LagePathShape() {}
  36255. return LagePathShape;
  36256. }();
  36257. var LargePath =
  36258. /** @class */
  36259. function (_super) {
  36260. __extends(LargePath, _super);
  36261. function LargePath(opts) {
  36262. var _this = _super.call(this, opts) || this;
  36263. _this.type = 'largeBar';
  36264. return _this;
  36265. }
  36266. LargePath.prototype.getDefaultShape = function () {
  36267. return new LagePathShape();
  36268. };
  36269. LargePath.prototype.buildPath = function (ctx, shape) {
  36270. // Drawing lines is more efficient than drawing
  36271. // a whole line or drawing rects.
  36272. var points = shape.points;
  36273. var baseDimIdx = this.baseDimIdx;
  36274. var valueDimIdx = 1 - this.baseDimIdx;
  36275. var startPoint = [];
  36276. var size = [];
  36277. var barWidth = this.barWidth;
  36278. for (var i = 0; i < points.length; i += 3) {
  36279. size[baseDimIdx] = barWidth;
  36280. size[valueDimIdx] = points[i + 2];
  36281. startPoint[baseDimIdx] = points[i + baseDimIdx];
  36282. startPoint[valueDimIdx] = points[i + valueDimIdx];
  36283. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  36284. }
  36285. };
  36286. return LargePath;
  36287. }(Path);
  36288. function createLarge(seriesModel, group, progressiveEls, incremental) {
  36289. // TODO support polar
  36290. var data = seriesModel.getData();
  36291. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  36292. var largeDataIndices = data.getLayout('largeDataIndices');
  36293. var barWidth = data.getLayout('size');
  36294. var backgroundModel = seriesModel.getModel('backgroundStyle');
  36295. var bgPoints = data.getLayout('largeBackgroundPoints');
  36296. if (bgPoints) {
  36297. var bgEl = new LargePath({
  36298. shape: {
  36299. points: bgPoints
  36300. },
  36301. incremental: !!incremental,
  36302. silent: true,
  36303. z2: 0
  36304. });
  36305. bgEl.baseDimIdx = baseDimIdx;
  36306. bgEl.largeDataIndices = largeDataIndices;
  36307. bgEl.barWidth = barWidth;
  36308. bgEl.useStyle(backgroundModel.getItemStyle());
  36309. group.add(bgEl);
  36310. progressiveEls && progressiveEls.push(bgEl);
  36311. }
  36312. var el = new LargePath({
  36313. shape: {
  36314. points: data.getLayout('largePoints')
  36315. },
  36316. incremental: !!incremental,
  36317. z2: 1
  36318. });
  36319. el.baseDimIdx = baseDimIdx;
  36320. el.largeDataIndices = largeDataIndices;
  36321. el.barWidth = barWidth;
  36322. group.add(el);
  36323. el.useStyle(data.getVisual('style')); // Enable tooltip and user mouse/touch event handlers.
  36324. getECData(el).seriesIndex = seriesModel.seriesIndex;
  36325. if (!seriesModel.get('silent')) {
  36326. el.on('mousedown', largePathUpdateDataIndex);
  36327. el.on('mousemove', largePathUpdateDataIndex);
  36328. }
  36329. progressiveEls && progressiveEls.push(el);
  36330. } // Use throttle to avoid frequently traverse to find dataIndex.
  36331. var largePathUpdateDataIndex = throttle(function (event) {
  36332. var largePath = this;
  36333. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  36334. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  36335. }, 30, false);
  36336. function largePathFindDataIndex(largePath, x, y) {
  36337. var baseDimIdx = largePath.baseDimIdx;
  36338. var valueDimIdx = 1 - baseDimIdx;
  36339. var points = largePath.shape.points;
  36340. var largeDataIndices = largePath.largeDataIndices;
  36341. var startPoint = [];
  36342. var size = [];
  36343. var barWidth = largePath.barWidth;
  36344. for (var i = 0, len = points.length / 3; i < len; i++) {
  36345. var ii = i * 3;
  36346. size[baseDimIdx] = barWidth;
  36347. size[valueDimIdx] = points[ii + 2];
  36348. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  36349. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  36350. if (size[valueDimIdx] < 0) {
  36351. startPoint[valueDimIdx] += size[valueDimIdx];
  36352. size[valueDimIdx] = -size[valueDimIdx];
  36353. }
  36354. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  36355. return largeDataIndices[i];
  36356. }
  36357. }
  36358. return -1;
  36359. }
  36360. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  36361. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  36362. var rectShape = layout;
  36363. var coordLayout = coord.getArea();
  36364. return {
  36365. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  36366. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  36367. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  36368. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  36369. };
  36370. } else {
  36371. var coordLayout = coord.getArea();
  36372. var sectorShape = layout;
  36373. return {
  36374. cx: coordLayout.cx,
  36375. cy: coordLayout.cy,
  36376. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  36377. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  36378. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  36379. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  36380. };
  36381. }
  36382. }
  36383. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  36384. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  36385. return new ElementClz({
  36386. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  36387. silent: true,
  36388. z2: 0
  36389. });
  36390. }
  36391. function install$2(registers) {
  36392. registers.registerChartView(BarView);
  36393. registers.registerSeriesModel(BarSeriesModel);
  36394. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Do layout after other overall layout, which can preapre some informations.
  36395. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar')); // Down sample after filter
  36396. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  36397. /**
  36398. * @payload
  36399. * @property {string} [componentType=series]
  36400. * @property {number} [dx]
  36401. * @property {number} [dy]
  36402. * @property {number} [zoom]
  36403. * @property {number} [originX]
  36404. * @property {number} [originY]
  36405. */
  36406. registers.registerAction({
  36407. type: 'changeAxisOrder',
  36408. event: 'changeAxisOrder',
  36409. update: 'update'
  36410. }, function (payload, ecModel) {
  36411. var componentType = payload.componentType || 'series';
  36412. ecModel.eachComponent({
  36413. mainType: componentType,
  36414. query: payload
  36415. }, function (componentModel) {
  36416. if (payload.sortInfo) {
  36417. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  36418. }
  36419. });
  36420. });
  36421. }
  36422. var PI2$6 = Math.PI * 2;
  36423. var RADIAN = Math.PI / 180;
  36424. function getViewRect(seriesModel, api) {
  36425. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  36426. width: api.getWidth(),
  36427. height: api.getHeight()
  36428. });
  36429. }
  36430. function getBasicPieLayout(seriesModel, api) {
  36431. var viewRect = getViewRect(seriesModel, api);
  36432. var center = seriesModel.get('center');
  36433. var radius = seriesModel.get('radius');
  36434. if (!isArray(radius)) {
  36435. radius = [0, radius];
  36436. }
  36437. if (!isArray(center)) {
  36438. center = [center, center];
  36439. }
  36440. var width = parsePercent$1(viewRect.width, api.getWidth());
  36441. var height = parsePercent$1(viewRect.height, api.getHeight());
  36442. var size = Math.min(width, height);
  36443. var cx = parsePercent$1(center[0], width) + viewRect.x;
  36444. var cy = parsePercent$1(center[1], height) + viewRect.y;
  36445. var r0 = parsePercent$1(radius[0], size / 2);
  36446. var r = parsePercent$1(radius[1], size / 2);
  36447. return {
  36448. cx: cx,
  36449. cy: cy,
  36450. r0: r0,
  36451. r: r
  36452. };
  36453. }
  36454. function pieLayout(seriesType, ecModel, api) {
  36455. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36456. var data = seriesModel.getData();
  36457. var valueDim = data.mapDimension('value');
  36458. var viewRect = getViewRect(seriesModel, api);
  36459. var _a = getBasicPieLayout(seriesModel, api),
  36460. cx = _a.cx,
  36461. cy = _a.cy,
  36462. r = _a.r,
  36463. r0 = _a.r0;
  36464. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  36465. var minAngle = seriesModel.get('minAngle') * RADIAN;
  36466. var validDataCount = 0;
  36467. data.each(valueDim, function (value) {
  36468. !isNaN(value) && validDataCount++;
  36469. });
  36470. var sum = data.getSum(valueDim); // Sum may be 0
  36471. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  36472. var clockwise = seriesModel.get('clockwise');
  36473. var roseType = seriesModel.get('roseType');
  36474. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  36475. var extent = data.getDataExtent(valueDim);
  36476. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  36477. var restAngle = PI2$6;
  36478. var valueSumLargerThanMinAngle = 0;
  36479. var currentAngle = startAngle;
  36480. var dir = clockwise ? 1 : -1;
  36481. data.setLayout({
  36482. viewRect: viewRect,
  36483. r: r
  36484. });
  36485. data.each(valueDim, function (value, idx) {
  36486. var angle;
  36487. if (isNaN(value)) {
  36488. data.setItemLayout(idx, {
  36489. angle: NaN,
  36490. startAngle: NaN,
  36491. endAngle: NaN,
  36492. clockwise: clockwise,
  36493. cx: cx,
  36494. cy: cy,
  36495. r0: r0,
  36496. r: roseType ? NaN : r
  36497. });
  36498. return;
  36499. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  36500. if (roseType !== 'area') {
  36501. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  36502. } else {
  36503. angle = PI2$6 / validDataCount;
  36504. }
  36505. if (angle < minAngle) {
  36506. angle = minAngle;
  36507. restAngle -= minAngle;
  36508. } else {
  36509. valueSumLargerThanMinAngle += value;
  36510. }
  36511. var endAngle = currentAngle + dir * angle;
  36512. data.setItemLayout(idx, {
  36513. angle: angle,
  36514. startAngle: currentAngle,
  36515. endAngle: endAngle,
  36516. clockwise: clockwise,
  36517. cx: cx,
  36518. cy: cy,
  36519. r0: r0,
  36520. r: roseType ? linearMap(value, extent, [r0, r]) : r
  36521. });
  36522. currentAngle = endAngle;
  36523. }); // Some sector is constrained by minAngle
  36524. // Rest sectors needs recalculate angle
  36525. if (restAngle < PI2$6 && validDataCount) {
  36526. // Average the angle if rest angle is not enough after all angles is
  36527. // Constrained by minAngle
  36528. if (restAngle <= 1e-3) {
  36529. var angle_1 = PI2$6 / validDataCount;
  36530. data.each(valueDim, function (value, idx) {
  36531. if (!isNaN(value)) {
  36532. var layout_1 = data.getItemLayout(idx);
  36533. layout_1.angle = angle_1;
  36534. layout_1.startAngle = startAngle + dir * idx * angle_1;
  36535. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  36536. }
  36537. });
  36538. } else {
  36539. unitRadian = restAngle / valueSumLargerThanMinAngle;
  36540. currentAngle = startAngle;
  36541. data.each(valueDim, function (value, idx) {
  36542. if (!isNaN(value)) {
  36543. var layout_2 = data.getItemLayout(idx);
  36544. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  36545. layout_2.startAngle = currentAngle;
  36546. layout_2.endAngle = currentAngle + dir * angle;
  36547. currentAngle += dir * angle;
  36548. }
  36549. });
  36550. }
  36551. }
  36552. });
  36553. }
  36554. /*
  36555. * Licensed to the Apache Software Foundation (ASF) under one
  36556. * or more contributor license agreements. See the NOTICE file
  36557. * distributed with this work for additional information
  36558. * regarding copyright ownership. The ASF licenses this file
  36559. * to you under the Apache License, Version 2.0 (the
  36560. * "License"); you may not use this file except in compliance
  36561. * with the License. You may obtain a copy of the License at
  36562. *
  36563. * http://www.apache.org/licenses/LICENSE-2.0
  36564. *
  36565. * Unless required by applicable law or agreed to in writing,
  36566. * software distributed under the License is distributed on an
  36567. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36568. * KIND, either express or implied. See the License for the
  36569. * specific language governing permissions and limitations
  36570. * under the License.
  36571. */
  36572. /**
  36573. * AUTO-GENERATED FILE. DO NOT MODIFY.
  36574. */
  36575. /*
  36576. * Licensed to the Apache Software Foundation (ASF) under one
  36577. * or more contributor license agreements. See the NOTICE file
  36578. * distributed with this work for additional information
  36579. * regarding copyright ownership. The ASF licenses this file
  36580. * to you under the Apache License, Version 2.0 (the
  36581. * "License"); you may not use this file except in compliance
  36582. * with the License. You may obtain a copy of the License at
  36583. *
  36584. * http://www.apache.org/licenses/LICENSE-2.0
  36585. *
  36586. * Unless required by applicable law or agreed to in writing,
  36587. * software distributed under the License is distributed on an
  36588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36589. * KIND, either express or implied. See the License for the
  36590. * specific language governing permissions and limitations
  36591. * under the License.
  36592. */
  36593. function dataFilter(seriesType) {
  36594. return {
  36595. seriesType: seriesType,
  36596. reset: function (seriesModel, ecModel) {
  36597. var legendModels = ecModel.findComponents({
  36598. mainType: 'legend'
  36599. });
  36600. if (!legendModels || !legendModels.length) {
  36601. return;
  36602. }
  36603. var data = seriesModel.getData();
  36604. data.filterSelf(function (idx) {
  36605. var name = data.getName(idx); // If in any legend component the status is not selected.
  36606. for (var i = 0; i < legendModels.length; i++) {
  36607. // @ts-ignore FIXME: LegendModel
  36608. if (!legendModels[i].isSelected(name)) {
  36609. return false;
  36610. }
  36611. }
  36612. return true;
  36613. });
  36614. }
  36615. };
  36616. }
  36617. var RADIAN$1 = Math.PI / 180;
  36618. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  36619. if (list.length < 2) {
  36620. return;
  36621. }
  36622. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  36623. var rB = semi.rB;
  36624. var rB2 = rB * rB;
  36625. for (var i = 0; i < semi.list.length; i++) {
  36626. var item = semi.list[i];
  36627. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  36628. var rA = r + item.len;
  36629. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  36630. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  36631. var newX = cx + (dx + item.len2) * dir;
  36632. var deltaX = newX - item.label.x;
  36633. var newTargetWidth = item.targetTextWidth - deltaX * dir; // text x is changed, so need to recalculate width.
  36634. constrainTextWidth(item, newTargetWidth, true);
  36635. item.label.x = newX;
  36636. }
  36637. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  36638. function recalculateX(items) {
  36639. // Extremes of
  36640. var topSemi = {
  36641. list: [],
  36642. maxY: 0
  36643. };
  36644. var bottomSemi = {
  36645. list: [],
  36646. maxY: 0
  36647. };
  36648. for (var i = 0; i < items.length; i++) {
  36649. if (items[i].labelAlignTo !== 'none') {
  36650. continue;
  36651. }
  36652. var item = items[i];
  36653. var semi = item.label.y > cy ? bottomSemi : topSemi;
  36654. var dy = Math.abs(item.label.y - cy);
  36655. if (dy >= semi.maxY) {
  36656. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  36657. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  36658. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  36659. semi.rB = rB;
  36660. semi.maxY = dy;
  36661. }
  36662. semi.list.push(item);
  36663. }
  36664. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  36665. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  36666. }
  36667. var len = list.length;
  36668. for (var i = 0; i < len; i++) {
  36669. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  36670. var dx = list[i].label.x - farthestX;
  36671. list[i].linePoints[1][0] += dx;
  36672. list[i].label.x = farthestX;
  36673. }
  36674. }
  36675. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  36676. recalculateX(list);
  36677. }
  36678. }
  36679. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  36680. var leftList = [];
  36681. var rightList = [];
  36682. var leftmostX = Number.MAX_VALUE;
  36683. var rightmostX = -Number.MAX_VALUE;
  36684. for (var i = 0; i < labelLayoutList.length; i++) {
  36685. var label = labelLayoutList[i].label;
  36686. if (isPositionCenter(labelLayoutList[i])) {
  36687. continue;
  36688. }
  36689. if (label.x < cx) {
  36690. leftmostX = Math.min(leftmostX, label.x);
  36691. leftList.push(labelLayoutList[i]);
  36692. } else {
  36693. rightmostX = Math.max(rightmostX, label.x);
  36694. rightList.push(labelLayoutList[i]);
  36695. }
  36696. }
  36697. for (var i = 0; i < labelLayoutList.length; i++) {
  36698. var layout = labelLayoutList[i];
  36699. if (!isPositionCenter(layout) && layout.linePoints) {
  36700. if (layout.labelStyleWidth != null) {
  36701. continue;
  36702. }
  36703. var label = layout.label;
  36704. var linePoints = layout.linePoints;
  36705. var targetTextWidth = void 0;
  36706. if (layout.labelAlignTo === 'edge') {
  36707. if (label.x < cx) {
  36708. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  36709. } else {
  36710. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  36711. }
  36712. } else if (layout.labelAlignTo === 'labelLine') {
  36713. if (label.x < cx) {
  36714. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  36715. } else {
  36716. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  36717. }
  36718. } else {
  36719. if (label.x < cx) {
  36720. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  36721. } else {
  36722. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  36723. }
  36724. }
  36725. layout.targetTextWidth = targetTextWidth;
  36726. constrainTextWidth(layout, targetTextWidth);
  36727. }
  36728. }
  36729. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  36730. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  36731. for (var i = 0; i < labelLayoutList.length; i++) {
  36732. var layout = labelLayoutList[i];
  36733. if (!isPositionCenter(layout) && layout.linePoints) {
  36734. var label = layout.label;
  36735. var linePoints = layout.linePoints;
  36736. var isAlignToEdge = layout.labelAlignTo === 'edge';
  36737. var padding = label.style.padding;
  36738. var paddingH = padding ? padding[1] + padding[3] : 0; // textRect.width already contains paddingH if bgColor is set
  36739. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  36740. var realTextWidth = layout.rect.width + extraPaddingH;
  36741. var dist = linePoints[1][0] - linePoints[2][0];
  36742. if (isAlignToEdge) {
  36743. if (label.x < cx) {
  36744. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  36745. } else {
  36746. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  36747. }
  36748. } else {
  36749. if (label.x < cx) {
  36750. linePoints[2][0] = label.x + layout.labelDistance;
  36751. } else {
  36752. linePoints[2][0] = label.x - layout.labelDistance;
  36753. }
  36754. linePoints[1][0] = linePoints[2][0] + dist;
  36755. }
  36756. linePoints[1][1] = linePoints[2][1] = label.y;
  36757. }
  36758. }
  36759. }
  36760. /**
  36761. * Set max width of each label, and then wrap each label to the max width.
  36762. *
  36763. * @param layout label layout
  36764. * @param availableWidth max width for the label to display
  36765. * @param forceRecalculate recaculate the text layout even if the current width
  36766. * is smaller than `availableWidth`. This is useful when the text was previously
  36767. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  36768. * which case, previous wrapping should be redo.
  36769. */
  36770. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  36771. if (forceRecalculate === void 0) {
  36772. forceRecalculate = false;
  36773. }
  36774. if (layout.labelStyleWidth != null) {
  36775. // User-defined style.width has the highest priority.
  36776. return;
  36777. }
  36778. var label = layout.label;
  36779. var style = label.style;
  36780. var textRect = layout.rect;
  36781. var bgColor = style.backgroundColor;
  36782. var padding = style.padding;
  36783. var paddingH = padding ? padding[1] + padding[3] : 0;
  36784. var overflow = style.overflow; // textRect.width already contains paddingH if bgColor is set
  36785. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  36786. if (availableWidth < oldOuterWidth || forceRecalculate) {
  36787. var oldHeight = textRect.height;
  36788. if (overflow && overflow.match('break')) {
  36789. // Temporarily set background to be null to calculate
  36790. // the bounding box without backgroud.
  36791. label.setStyle('backgroundColor', null); // Set constraining width
  36792. label.setStyle('width', availableWidth - paddingH); // This is the real bounding box of the text without padding
  36793. var innerRect = label.getBoundingRect();
  36794. label.setStyle('width', Math.ceil(innerRect.width));
  36795. label.setStyle('backgroundColor', bgColor);
  36796. } else {
  36797. var availableInnerWidth = availableWidth - paddingH;
  36798. var newWidth = availableWidth < oldOuterWidth // Current text is too wide, use `availableWidth` as max width.
  36799. ? availableInnerWidth : // Current available width is enough, but the text may have
  36800. // already been wrapped with a smaller available width.
  36801. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth // Current available is larger than text width,
  36802. // so don't constrain width (otherwise it may have
  36803. // empty space in the background).
  36804. ? null // Current available is smaller than text width, so
  36805. // use the current available width as constraining
  36806. // width.
  36807. : availableInnerWidth : // Current available width is enough, so no need to
  36808. // constrain.
  36809. null;
  36810. label.setStyle('width', newWidth);
  36811. }
  36812. var newRect = label.getBoundingRect();
  36813. textRect.width = newRect.width;
  36814. var margin = (label.style.margin || 0) + 2.1;
  36815. textRect.height = newRect.height + margin;
  36816. textRect.y -= (textRect.height - oldHeight) / 2;
  36817. }
  36818. }
  36819. function isPositionCenter(sectorShape) {
  36820. // Not change x for center label
  36821. return sectorShape.position === 'center';
  36822. }
  36823. function pieLabelLayout(seriesModel) {
  36824. var data = seriesModel.getData();
  36825. var labelLayoutList = [];
  36826. var cx;
  36827. var cy;
  36828. var hasLabelRotate = false;
  36829. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  36830. var viewRect = data.getLayout('viewRect');
  36831. var r = data.getLayout('r');
  36832. var viewWidth = viewRect.width;
  36833. var viewLeft = viewRect.x;
  36834. var viewTop = viewRect.y;
  36835. var viewHeight = viewRect.height;
  36836. function setNotShow(el) {
  36837. el.ignore = true;
  36838. }
  36839. function isLabelShown(label) {
  36840. if (!label.ignore) {
  36841. return true;
  36842. }
  36843. for (var key in label.states) {
  36844. if (label.states[key].ignore === false) {
  36845. return true;
  36846. }
  36847. }
  36848. return false;
  36849. }
  36850. data.each(function (idx) {
  36851. var sector = data.getItemGraphicEl(idx);
  36852. var sectorShape = sector.shape;
  36853. var label = sector.getTextContent();
  36854. var labelLine = sector.getTextGuideLine();
  36855. var itemModel = data.getItemModel(idx);
  36856. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  36857. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  36858. var labelDistance = labelModel.get('distanceToLabelLine');
  36859. var labelAlignTo = labelModel.get('alignTo');
  36860. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  36861. var bleedMargin = labelModel.get('bleedMargin');
  36862. var labelLineModel = itemModel.getModel('labelLine');
  36863. var labelLineLen = labelLineModel.get('length');
  36864. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  36865. var labelLineLen2 = labelLineModel.get('length2');
  36866. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  36867. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  36868. each(label.states, setNotShow);
  36869. label.ignore = true;
  36870. return;
  36871. }
  36872. if (!isLabelShown(label)) {
  36873. return;
  36874. }
  36875. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  36876. var nx = Math.cos(midAngle);
  36877. var ny = Math.sin(midAngle);
  36878. var textX;
  36879. var textY;
  36880. var linePoints;
  36881. var textAlign;
  36882. cx = sectorShape.cx;
  36883. cy = sectorShape.cy;
  36884. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  36885. if (labelPosition === 'center') {
  36886. textX = sectorShape.cx;
  36887. textY = sectorShape.cy;
  36888. textAlign = 'center';
  36889. } else {
  36890. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  36891. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  36892. textX = x1 + nx * 3;
  36893. textY = y1 + ny * 3;
  36894. if (!isLabelInside) {
  36895. // For roseType
  36896. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  36897. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  36898. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  36899. var y3 = y2;
  36900. if (labelAlignTo === 'edge') {
  36901. // Adjust textX because text align of edge is opposite
  36902. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  36903. } else {
  36904. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  36905. }
  36906. textY = y3;
  36907. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  36908. }
  36909. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  36910. }
  36911. var PI = Math.PI;
  36912. var labelRotate = 0;
  36913. var rotate = labelModel.get('rotate');
  36914. if (isNumber(rotate)) {
  36915. labelRotate = rotate * (PI / 180);
  36916. } else if (labelPosition === 'center') {
  36917. labelRotate = 0;
  36918. } else if (rotate === 'radial' || rotate === true) {
  36919. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  36920. labelRotate = radialAngle;
  36921. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  36922. var rad = Math.atan2(nx, ny);
  36923. if (rad < 0) {
  36924. rad = PI * 2 + rad;
  36925. }
  36926. var isDown = ny > 0;
  36927. if (isDown) {
  36928. rad = PI + rad;
  36929. }
  36930. labelRotate = rad - PI;
  36931. }
  36932. hasLabelRotate = !!labelRotate;
  36933. label.x = textX;
  36934. label.y = textY;
  36935. label.rotation = labelRotate;
  36936. label.setStyle({
  36937. verticalAlign: 'middle'
  36938. }); // Not sectorShape the inside label
  36939. if (!isLabelInside) {
  36940. var textRect = label.getBoundingRect().clone();
  36941. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  36942. var margin = (label.style.margin || 0) + 2.1;
  36943. textRect.y -= margin / 2;
  36944. textRect.height += margin;
  36945. labelLayoutList.push({
  36946. label: label,
  36947. labelLine: labelLine,
  36948. position: labelPosition,
  36949. len: labelLineLen,
  36950. len2: labelLineLen2,
  36951. minTurnAngle: labelLineModel.get('minTurnAngle'),
  36952. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  36953. surfaceNormal: new Point(nx, ny),
  36954. linePoints: linePoints,
  36955. textAlign: textAlign,
  36956. labelDistance: labelDistance,
  36957. labelAlignTo: labelAlignTo,
  36958. edgeDistance: edgeDistance,
  36959. bleedMargin: bleedMargin,
  36960. rect: textRect,
  36961. unconstrainedWidth: textRect.width,
  36962. labelStyleWidth: label.style.width
  36963. });
  36964. } else {
  36965. label.setStyle({
  36966. align: textAlign
  36967. });
  36968. var selectState = label.states.select;
  36969. if (selectState) {
  36970. selectState.x += label.x;
  36971. selectState.y += label.y;
  36972. }
  36973. }
  36974. sector.setTextConfig({
  36975. inside: isLabelInside
  36976. });
  36977. });
  36978. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  36979. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  36980. }
  36981. for (var i = 0; i < labelLayoutList.length; i++) {
  36982. var layout = labelLayoutList[i];
  36983. var label = layout.label;
  36984. var labelLine = layout.labelLine;
  36985. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  36986. if (label) {
  36987. label.setStyle({
  36988. align: layout.textAlign
  36989. });
  36990. if (notShowLabel) {
  36991. each(label.states, setNotShow);
  36992. label.ignore = true;
  36993. }
  36994. var selectState = label.states.select;
  36995. if (selectState) {
  36996. selectState.x += label.x;
  36997. selectState.y += label.y;
  36998. }
  36999. }
  37000. if (labelLine) {
  37001. var linePoints = layout.linePoints;
  37002. if (notShowLabel || !linePoints) {
  37003. each(labelLine.states, setNotShow);
  37004. labelLine.ignore = true;
  37005. } else {
  37006. limitTurnAngle(linePoints, layout.minTurnAngle);
  37007. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  37008. labelLine.setShape({
  37009. points: linePoints
  37010. }); // Set the anchor to the midpoint of sector
  37011. label.__hostTarget.textGuideLineConfig = {
  37012. anchor: new Point(linePoints[0][0], linePoints[0][1])
  37013. };
  37014. }
  37015. }
  37016. }
  37017. }
  37018. function getSectorCornerRadius(model, shape, zeroIfNull) {
  37019. var cornerRadius = model.get('borderRadius');
  37020. if (cornerRadius == null) {
  37021. return zeroIfNull ? {
  37022. cornerRadius: 0
  37023. } : null;
  37024. }
  37025. if (!isArray(cornerRadius)) {
  37026. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  37027. }
  37028. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  37029. return {
  37030. cornerRadius: map(cornerRadius, function (cr) {
  37031. return parsePercent(cr, dr);
  37032. })
  37033. };
  37034. }
  37035. /**
  37036. * Piece of pie including Sector, Label, LabelLine
  37037. */
  37038. var PiePiece =
  37039. /** @class */
  37040. function (_super) {
  37041. __extends(PiePiece, _super);
  37042. function PiePiece(data, idx, startAngle) {
  37043. var _this = _super.call(this) || this;
  37044. _this.z2 = 2;
  37045. var text = new ZRText();
  37046. _this.setTextContent(text);
  37047. _this.updateData(data, idx, startAngle, true);
  37048. return _this;
  37049. }
  37050. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  37051. var sector = this;
  37052. var seriesModel = data.hostModel;
  37053. var itemModel = data.getItemModel(idx);
  37054. var emphasisModel = itemModel.getModel('emphasis');
  37055. var layout = data.getItemLayout(idx); // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  37056. // see `setItemLayout` in `pieLayout.ts`.
  37057. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout); // Ignore NaN data.
  37058. if (isNaN(sectorShape.startAngle)) {
  37059. // Use NaN shape to avoid drawing shape.
  37060. sector.setShape(sectorShape);
  37061. return;
  37062. }
  37063. if (firstCreate) {
  37064. sector.setShape(sectorShape);
  37065. var animationType = seriesModel.getShallow('animationType');
  37066. if (seriesModel.ecModel.ssr) {
  37067. // Use scale animation in SSR mode(opacity?)
  37068. // Because CSS SVG animation doesn't support very customized shape animation.
  37069. initProps(sector, {
  37070. scaleX: 0,
  37071. scaleY: 0
  37072. }, seriesModel, {
  37073. dataIndex: idx,
  37074. isFrom: true
  37075. });
  37076. sector.originX = sectorShape.cx;
  37077. sector.originY = sectorShape.cy;
  37078. } else if (animationType === 'scale') {
  37079. sector.shape.r = layout.r0;
  37080. initProps(sector, {
  37081. shape: {
  37082. r: layout.r
  37083. }
  37084. }, seriesModel, idx);
  37085. } // Expansion
  37086. else {
  37087. if (startAngle != null) {
  37088. sector.setShape({
  37089. startAngle: startAngle,
  37090. endAngle: startAngle
  37091. });
  37092. initProps(sector, {
  37093. shape: {
  37094. startAngle: layout.startAngle,
  37095. endAngle: layout.endAngle
  37096. }
  37097. }, seriesModel, idx);
  37098. } else {
  37099. sector.shape.endAngle = layout.startAngle;
  37100. updateProps(sector, {
  37101. shape: {
  37102. endAngle: layout.endAngle
  37103. }
  37104. }, seriesModel, idx);
  37105. }
  37106. }
  37107. } else {
  37108. saveOldStyle(sector); // Transition animation from the old shape
  37109. updateProps(sector, {
  37110. shape: sectorShape
  37111. }, seriesModel, idx);
  37112. }
  37113. sector.useStyle(data.getItemVisual(idx, 'style'));
  37114. setStatesStylesFromModel(sector, itemModel);
  37115. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37116. var offset = seriesModel.get('selectedOffset');
  37117. var dx = Math.cos(midAngle) * offset;
  37118. var dy = Math.sin(midAngle) * offset;
  37119. var cursorStyle = itemModel.getShallow('cursor');
  37120. cursorStyle && sector.attr('cursor', cursorStyle);
  37121. this._updateLabel(seriesModel, data, idx);
  37122. sector.ensureState('emphasis').shape = extend({
  37123. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  37124. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  37125. extend(sector.ensureState('select'), {
  37126. x: dx,
  37127. y: dy,
  37128. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  37129. });
  37130. extend(sector.ensureState('blur'), {
  37131. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  37132. });
  37133. var labelLine = sector.getTextGuideLine();
  37134. var labelText = sector.getTextContent();
  37135. labelLine && extend(labelLine.ensureState('select'), {
  37136. x: dx,
  37137. y: dy
  37138. }); // TODO: needs dx, dy in zrender?
  37139. extend(labelText.ensureState('select'), {
  37140. x: dx,
  37141. y: dy
  37142. });
  37143. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  37144. };
  37145. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  37146. var sector = this;
  37147. var itemModel = data.getItemModel(idx);
  37148. var labelLineModel = itemModel.getModel('labelLine');
  37149. var style = data.getItemVisual(idx, 'style');
  37150. var visualColor = style && style.fill;
  37151. var visualOpacity = style && style.opacity;
  37152. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  37153. labelFetcher: data.hostModel,
  37154. labelDataIndex: idx,
  37155. inheritColor: visualColor,
  37156. defaultOpacity: visualOpacity,
  37157. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  37158. });
  37159. var labelText = sector.getTextContent(); // Set textConfig on sector.
  37160. sector.setTextConfig({
  37161. // reset position, rotation
  37162. position: null,
  37163. rotation: null
  37164. }); // Make sure update style on labelText after setLabelStyle.
  37165. // Because setLabelStyle will replace a new style on it.
  37166. labelText.attr({
  37167. z2: 10
  37168. });
  37169. var labelPosition = seriesModel.get(['label', 'position']);
  37170. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  37171. sector.removeTextGuideLine();
  37172. } else {
  37173. var polyline = this.getTextGuideLine();
  37174. if (!polyline) {
  37175. polyline = new Polyline();
  37176. this.setTextGuideLine(polyline);
  37177. } // Default use item visual color
  37178. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  37179. stroke: visualColor,
  37180. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  37181. });
  37182. }
  37183. };
  37184. return PiePiece;
  37185. }(Sector); // Pie view
  37186. var PieView =
  37187. /** @class */
  37188. function (_super) {
  37189. __extends(PieView, _super);
  37190. function PieView() {
  37191. var _this = _super !== null && _super.apply(this, arguments) || this;
  37192. _this.ignoreLabelLineUpdate = true;
  37193. return _this;
  37194. }
  37195. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  37196. var data = seriesModel.getData();
  37197. var oldData = this._data;
  37198. var group = this.group;
  37199. var startAngle; // First render
  37200. if (!oldData && data.count() > 0) {
  37201. var shape = data.getItemLayout(0);
  37202. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  37203. shape = data.getItemLayout(s);
  37204. }
  37205. if (shape) {
  37206. startAngle = shape.startAngle;
  37207. }
  37208. } // remove empty-circle if it exists
  37209. if (this._emptyCircleSector) {
  37210. group.remove(this._emptyCircleSector);
  37211. } // when all data are filtered, show lightgray empty circle
  37212. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  37213. var sector = new Sector({
  37214. shape: getBasicPieLayout(seriesModel, api)
  37215. });
  37216. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  37217. this._emptyCircleSector = sector;
  37218. group.add(sector);
  37219. }
  37220. data.diff(oldData).add(function (idx) {
  37221. var piePiece = new PiePiece(data, idx, startAngle);
  37222. data.setItemGraphicEl(idx, piePiece);
  37223. group.add(piePiece);
  37224. }).update(function (newIdx, oldIdx) {
  37225. var piePiece = oldData.getItemGraphicEl(oldIdx);
  37226. piePiece.updateData(data, newIdx, startAngle);
  37227. piePiece.off('click');
  37228. group.add(piePiece);
  37229. data.setItemGraphicEl(newIdx, piePiece);
  37230. }).remove(function (idx) {
  37231. var piePiece = oldData.getItemGraphicEl(idx);
  37232. removeElementWithFadeOut(piePiece, seriesModel, idx);
  37233. }).execute();
  37234. pieLabelLayout(seriesModel); // Always use initial animation.
  37235. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  37236. this._data = data;
  37237. }
  37238. };
  37239. PieView.prototype.dispose = function () {};
  37240. PieView.prototype.containPoint = function (point, seriesModel) {
  37241. var data = seriesModel.getData();
  37242. var itemLayout = data.getItemLayout(0);
  37243. if (itemLayout) {
  37244. var dx = point[0] - itemLayout.cx;
  37245. var dy = point[1] - itemLayout.cy;
  37246. var radius = Math.sqrt(dx * dx + dy * dy);
  37247. return radius <= itemLayout.r && radius >= itemLayout.r0;
  37248. }
  37249. };
  37250. PieView.type = 'pie';
  37251. return PieView;
  37252. }(ChartView);
  37253. /**
  37254. * [Usage]:
  37255. * (1)
  37256. * createListSimply(seriesModel, ['value']);
  37257. * (2)
  37258. * createListSimply(seriesModel, {
  37259. * coordDimensions: ['value'],
  37260. * dimensionsCount: 5
  37261. * });
  37262. */
  37263. function createSeriesDataSimply(seriesModel, opt, nameList) {
  37264. opt = isArray(opt) && {
  37265. coordDimensions: opt
  37266. } || extend({
  37267. encodeDefine: seriesModel.getEncode()
  37268. }, opt);
  37269. var source = seriesModel.getSource();
  37270. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  37271. var list = new SeriesData(dimensions, seriesModel);
  37272. list.initData(source, nameList);
  37273. return list;
  37274. }
  37275. /*
  37276. * Licensed to the Apache Software Foundation (ASF) under one
  37277. * or more contributor license agreements. See the NOTICE file
  37278. * distributed with this work for additional information
  37279. * regarding copyright ownership. The ASF licenses this file
  37280. * to you under the Apache License, Version 2.0 (the
  37281. * "License"); you may not use this file except in compliance
  37282. * with the License. You may obtain a copy of the License at
  37283. *
  37284. * http://www.apache.org/licenses/LICENSE-2.0
  37285. *
  37286. * Unless required by applicable law or agreed to in writing,
  37287. * software distributed under the License is distributed on an
  37288. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37289. * KIND, either express or implied. See the License for the
  37290. * specific language governing permissions and limitations
  37291. * under the License.
  37292. */
  37293. /**
  37294. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37295. */
  37296. /*
  37297. * Licensed to the Apache Software Foundation (ASF) under one
  37298. * or more contributor license agreements. See the NOTICE file
  37299. * distributed with this work for additional information
  37300. * regarding copyright ownership. The ASF licenses this file
  37301. * to you under the Apache License, Version 2.0 (the
  37302. * "License"); you may not use this file except in compliance
  37303. * with the License. You may obtain a copy of the License at
  37304. *
  37305. * http://www.apache.org/licenses/LICENSE-2.0
  37306. *
  37307. * Unless required by applicable law or agreed to in writing,
  37308. * software distributed under the License is distributed on an
  37309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37310. * KIND, either express or implied. See the License for the
  37311. * specific language governing permissions and limitations
  37312. * under the License.
  37313. */
  37314. /**
  37315. * LegendVisualProvider is an bridge that pick encoded color from data and
  37316. * provide to the legend component.
  37317. */
  37318. var LegendVisualProvider =
  37319. /** @class */
  37320. function () {
  37321. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  37322. getDataWithEncodedVisual, // Function to get raw data before filtered.
  37323. getRawData) {
  37324. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  37325. this._getRawData = getRawData;
  37326. }
  37327. LegendVisualProvider.prototype.getAllNames = function () {
  37328. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  37329. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  37330. return rawData.mapArray(rawData.getName);
  37331. };
  37332. LegendVisualProvider.prototype.containName = function (name) {
  37333. var rawData = this._getRawData();
  37334. return rawData.indexOfName(name) >= 0;
  37335. };
  37336. LegendVisualProvider.prototype.indexOfName = function (name) {
  37337. // Only get data when necessary.
  37338. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  37339. // Invoking Series#getData immediately will throw an error.
  37340. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  37341. return dataWithEncodedVisual.indexOfName(name);
  37342. };
  37343. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  37344. // Get encoded visual properties from final filtered data.
  37345. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  37346. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  37347. };
  37348. return LegendVisualProvider;
  37349. }();
  37350. var PieSeriesModel =
  37351. /** @class */
  37352. function (_super) {
  37353. __extends(PieSeriesModel, _super);
  37354. function PieSeriesModel() {
  37355. return _super !== null && _super.apply(this, arguments) || this;
  37356. }
  37357. /**
  37358. * @overwrite
  37359. */
  37360. PieSeriesModel.prototype.init = function (option) {
  37361. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  37362. // Use a function instead of direct access because data reference may changed
  37363. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  37364. this._defaultLabelLine(option);
  37365. };
  37366. /**
  37367. * @overwrite
  37368. */
  37369. PieSeriesModel.prototype.mergeOption = function () {
  37370. _super.prototype.mergeOption.apply(this, arguments);
  37371. };
  37372. /**
  37373. * @overwrite
  37374. */
  37375. PieSeriesModel.prototype.getInitialData = function () {
  37376. return createSeriesDataSimply(this, {
  37377. coordDimensions: ['value'],
  37378. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  37379. });
  37380. };
  37381. /**
  37382. * @overwrite
  37383. */
  37384. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  37385. var data = this.getData();
  37386. var params = _super.prototype.getDataParams.call(this, dataIndex); // FIXME toFixed?
  37387. var valueList = [];
  37388. data.each(data.mapDimension('value'), function (value) {
  37389. valueList.push(value);
  37390. });
  37391. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  37392. params.$vars.push('percent');
  37393. return params;
  37394. };
  37395. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  37396. // Extend labelLine emphasis
  37397. defaultEmphasis(option, 'labelLine', ['show']);
  37398. var labelLineNormalOpt = option.labelLine;
  37399. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  37400. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  37401. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  37402. };
  37403. PieSeriesModel.type = 'series.pie';
  37404. PieSeriesModel.defaultOption = {
  37405. // zlevel: 0,
  37406. z: 2,
  37407. legendHoverLink: true,
  37408. colorBy: 'data',
  37409. // 默认全局居中
  37410. center: ['50%', '50%'],
  37411. radius: [0, '75%'],
  37412. // 默认顺时针
  37413. clockwise: true,
  37414. startAngle: 90,
  37415. // 最小角度改为0
  37416. minAngle: 0,
  37417. // If the angle of a sector less than `minShowLabelAngle`,
  37418. // the label will not be displayed.
  37419. minShowLabelAngle: 0,
  37420. // 选中时扇区偏移量
  37421. selectedOffset: 10,
  37422. // 选择模式,默认关闭,可选single,multiple
  37423. // selectedMode: false,
  37424. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  37425. // roseType: null,
  37426. percentPrecision: 2,
  37427. // If still show when all data zero.
  37428. stillShowZeroSum: true,
  37429. // cursor: null,
  37430. left: 0,
  37431. top: 0,
  37432. right: 0,
  37433. bottom: 0,
  37434. width: null,
  37435. height: null,
  37436. label: {
  37437. // color: 'inherit',
  37438. // If rotate around circle
  37439. rotate: 0,
  37440. show: true,
  37441. overflow: 'truncate',
  37442. // 'outer', 'inside', 'center'
  37443. position: 'outer',
  37444. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  37445. alignTo: 'none',
  37446. // Closest distance between label and chart edge.
  37447. // Works only position is 'outer' and alignTo is 'edge'.
  37448. edgeDistance: '25%',
  37449. // Works only position is 'outer' and alignTo is not 'edge'.
  37450. bleedMargin: 10,
  37451. // Distance between text and label line.
  37452. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37453. // 默认使用全局文本样式,详见TEXTSTYLE
  37454. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  37455. },
  37456. // Enabled when label.normal.position is 'outer'
  37457. labelLine: {
  37458. show: true,
  37459. // 引导线两段中的第一段长度
  37460. length: 15,
  37461. // 引导线两段中的第二段长度
  37462. length2: 15,
  37463. smooth: false,
  37464. minTurnAngle: 90,
  37465. maxSurfaceAngle: 90,
  37466. lineStyle: {
  37467. // color: 各异,
  37468. width: 1,
  37469. type: 'solid'
  37470. }
  37471. },
  37472. itemStyle: {
  37473. borderWidth: 1,
  37474. borderJoin: 'round'
  37475. },
  37476. showEmptyCircle: true,
  37477. emptyCircleStyle: {
  37478. color: 'lightgray',
  37479. opacity: 1
  37480. },
  37481. labelLayout: {
  37482. // Hide the overlapped label.
  37483. hideOverlap: true
  37484. },
  37485. emphasis: {
  37486. scale: true,
  37487. scaleSize: 5
  37488. },
  37489. // If use strategy to avoid label overlapping
  37490. avoidLabelOverlap: true,
  37491. // Animation type. Valid values: expansion, scale
  37492. animationType: 'expansion',
  37493. animationDuration: 1000,
  37494. // Animation type when update. Valid values: transition, expansion
  37495. animationTypeUpdate: 'transition',
  37496. animationEasingUpdate: 'cubicInOut',
  37497. animationDurationUpdate: 500,
  37498. animationEasing: 'cubicInOut'
  37499. };
  37500. return PieSeriesModel;
  37501. }(SeriesModel);
  37502. function negativeDataFilter(seriesType) {
  37503. return {
  37504. seriesType: seriesType,
  37505. reset: function (seriesModel, ecModel) {
  37506. var data = seriesModel.getData();
  37507. data.filterSelf(function (idx) {
  37508. // handle negative value condition
  37509. var valueDim = data.mapDimension('value');
  37510. var curValue = data.get(valueDim, idx);
  37511. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  37512. return false;
  37513. }
  37514. return true;
  37515. });
  37516. }
  37517. };
  37518. }
  37519. function install$3(registers) {
  37520. registers.registerChartView(PieView);
  37521. registers.registerSeriesModel(PieSeriesModel);
  37522. createLegacyDataSelectAction('pie', registers.registerAction);
  37523. registers.registerLayout(curry(pieLayout, 'pie'));
  37524. registers.registerProcessor(dataFilter('pie'));
  37525. registers.registerProcessor(negativeDataFilter('pie'));
  37526. }
  37527. var GridModel =
  37528. /** @class */
  37529. function (_super) {
  37530. __extends(GridModel, _super);
  37531. function GridModel() {
  37532. return _super !== null && _super.apply(this, arguments) || this;
  37533. }
  37534. GridModel.type = 'grid';
  37535. GridModel.dependencies = ['xAxis', 'yAxis'];
  37536. GridModel.layoutMode = 'box';
  37537. GridModel.defaultOption = {
  37538. show: false,
  37539. // zlevel: 0,
  37540. z: 0,
  37541. left: '10%',
  37542. top: 60,
  37543. right: '10%',
  37544. bottom: 70,
  37545. // If grid size contain label
  37546. containLabel: false,
  37547. // width: {totalWidth} - left - right,
  37548. // height: {totalHeight} - top - bottom,
  37549. backgroundColor: 'rgba(0,0,0,0)',
  37550. borderWidth: 1,
  37551. borderColor: '#ccc'
  37552. };
  37553. return GridModel;
  37554. }(ComponentModel);
  37555. var CartesianAxisModel =
  37556. /** @class */
  37557. function (_super) {
  37558. __extends(CartesianAxisModel, _super);
  37559. function CartesianAxisModel() {
  37560. return _super !== null && _super.apply(this, arguments) || this;
  37561. }
  37562. CartesianAxisModel.prototype.getCoordSysModel = function () {
  37563. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  37564. };
  37565. CartesianAxisModel.type = 'cartesian2dAxis';
  37566. return CartesianAxisModel;
  37567. }(ComponentModel);
  37568. mixin(CartesianAxisModel, AxisModelCommonMixin);
  37569. var defaultOption = {
  37570. show: true,
  37571. // zlevel: 0,
  37572. z: 0,
  37573. // Inverse the axis.
  37574. inverse: false,
  37575. // Axis name displayed.
  37576. name: '',
  37577. // 'start' | 'middle' | 'end'
  37578. nameLocation: 'end',
  37579. // By degree. By default auto rotate by nameLocation.
  37580. nameRotate: null,
  37581. nameTruncate: {
  37582. maxWidth: null,
  37583. ellipsis: '...',
  37584. placeholder: '.'
  37585. },
  37586. // Use global text style by default.
  37587. nameTextStyle: {},
  37588. // The gap between axisName and axisLine.
  37589. nameGap: 15,
  37590. // Default `false` to support tooltip.
  37591. silent: false,
  37592. // Default `false` to avoid legacy user event listener fail.
  37593. triggerEvent: false,
  37594. tooltip: {
  37595. show: false
  37596. },
  37597. axisPointer: {},
  37598. axisLine: {
  37599. show: true,
  37600. onZero: true,
  37601. onZeroAxisIndex: null,
  37602. lineStyle: {
  37603. color: '#6E7079',
  37604. width: 1,
  37605. type: 'solid'
  37606. },
  37607. // The arrow at both ends the the axis.
  37608. symbol: ['none', 'none'],
  37609. symbolSize: [10, 15]
  37610. },
  37611. axisTick: {
  37612. show: true,
  37613. // Whether axisTick is inside the grid or outside the grid.
  37614. inside: false,
  37615. // The length of axisTick.
  37616. length: 5,
  37617. lineStyle: {
  37618. width: 1
  37619. }
  37620. },
  37621. axisLabel: {
  37622. show: true,
  37623. // Whether axisLabel is inside the grid or outside the grid.
  37624. inside: false,
  37625. rotate: 0,
  37626. // true | false | null/undefined (auto)
  37627. showMinLabel: null,
  37628. // true | false | null/undefined (auto)
  37629. showMaxLabel: null,
  37630. margin: 8,
  37631. // formatter: null,
  37632. fontSize: 12
  37633. },
  37634. splitLine: {
  37635. show: true,
  37636. lineStyle: {
  37637. color: ['#E0E6F1'],
  37638. width: 1,
  37639. type: 'solid'
  37640. }
  37641. },
  37642. splitArea: {
  37643. show: false,
  37644. areaStyle: {
  37645. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  37646. }
  37647. }
  37648. };
  37649. var categoryAxis = merge({
  37650. // The gap at both ends of the axis. For categoryAxis, boolean.
  37651. boundaryGap: true,
  37652. // Set false to faster category collection.
  37653. deduplication: null,
  37654. // splitArea: {
  37655. // show: false
  37656. // },
  37657. splitLine: {
  37658. show: false
  37659. },
  37660. axisTick: {
  37661. // If tick is align with label when boundaryGap is true
  37662. alignWithLabel: false,
  37663. interval: 'auto'
  37664. },
  37665. axisLabel: {
  37666. interval: 'auto'
  37667. }
  37668. }, defaultOption);
  37669. var valueAxis = merge({
  37670. boundaryGap: [0, 0],
  37671. axisLine: {
  37672. // Not shown when other axis is categoryAxis in cartesian
  37673. show: 'auto'
  37674. },
  37675. axisTick: {
  37676. // Not shown when other axis is categoryAxis in cartesian
  37677. show: 'auto'
  37678. },
  37679. // TODO
  37680. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  37681. splitNumber: 5,
  37682. minorTick: {
  37683. // Minor tick, not available for cateogry axis.
  37684. show: false,
  37685. // Split number of minor ticks. The value should be in range of (0, 100)
  37686. splitNumber: 5,
  37687. // Lenght of minor tick
  37688. length: 3,
  37689. // Line style
  37690. lineStyle: {// Default to be same with axisTick
  37691. }
  37692. },
  37693. minorSplitLine: {
  37694. show: false,
  37695. lineStyle: {
  37696. color: '#F4F7FD',
  37697. width: 1
  37698. }
  37699. }
  37700. }, defaultOption);
  37701. var timeAxis = merge({
  37702. splitNumber: 6,
  37703. axisLabel: {
  37704. // To eliminate labels that are not nice
  37705. showMinLabel: false,
  37706. showMaxLabel: false,
  37707. rich: {
  37708. primary: {
  37709. fontWeight: 'bold'
  37710. }
  37711. }
  37712. },
  37713. splitLine: {
  37714. show: false
  37715. }
  37716. }, valueAxis);
  37717. var logAxis = defaults({
  37718. logBase: 10
  37719. }, valueAxis);
  37720. var axisDefault = {
  37721. category: categoryAxis,
  37722. value: valueAxis,
  37723. time: timeAxis,
  37724. log: logAxis
  37725. };
  37726. /*
  37727. * Licensed to the Apache Software Foundation (ASF) under one
  37728. * or more contributor license agreements. See the NOTICE file
  37729. * distributed with this work for additional information
  37730. * regarding copyright ownership. The ASF licenses this file
  37731. * to you under the Apache License, Version 2.0 (the
  37732. * "License"); you may not use this file except in compliance
  37733. * with the License. You may obtain a copy of the License at
  37734. *
  37735. * http://www.apache.org/licenses/LICENSE-2.0
  37736. *
  37737. * Unless required by applicable law or agreed to in writing,
  37738. * software distributed under the License is distributed on an
  37739. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37740. * KIND, either express or implied. See the License for the
  37741. * specific language governing permissions and limitations
  37742. * under the License.
  37743. */
  37744. /**
  37745. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37746. */
  37747. /*
  37748. * Licensed to the Apache Software Foundation (ASF) under one
  37749. * or more contributor license agreements. See the NOTICE file
  37750. * distributed with this work for additional information
  37751. * regarding copyright ownership. The ASF licenses this file
  37752. * to you under the Apache License, Version 2.0 (the
  37753. * "License"); you may not use this file except in compliance
  37754. * with the License. You may obtain a copy of the License at
  37755. *
  37756. * http://www.apache.org/licenses/LICENSE-2.0
  37757. *
  37758. * Unless required by applicable law or agreed to in writing,
  37759. * software distributed under the License is distributed on an
  37760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37761. * KIND, either express or implied. See the License for the
  37762. * specific language governing permissions and limitations
  37763. * under the License.
  37764. */
  37765. var AXIS_TYPES = {
  37766. value: 1,
  37767. category: 1,
  37768. time: 1,
  37769. log: 1
  37770. };
  37771. /**
  37772. * Generate sub axis model class
  37773. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  37774. */
  37775. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  37776. each(AXIS_TYPES, function (v, axisType) {
  37777. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  37778. var AxisModel =
  37779. /** @class */
  37780. function (_super) {
  37781. __extends(AxisModel, _super);
  37782. function AxisModel() {
  37783. var _this = _super !== null && _super.apply(this, arguments) || this;
  37784. _this.type = axisName + 'Axis.' + axisType;
  37785. return _this;
  37786. }
  37787. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  37788. var layoutMode = fetchLayoutMode(this);
  37789. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  37790. var themeModel = ecModel.getTheme();
  37791. merge(option, themeModel.get(axisType + 'Axis'));
  37792. merge(option, this.getDefaultOption());
  37793. option.type = getAxisType(option);
  37794. if (layoutMode) {
  37795. mergeLayoutParam(option, inputPositionParams, layoutMode);
  37796. }
  37797. };
  37798. AxisModel.prototype.optionUpdated = function () {
  37799. var thisOption = this.option;
  37800. if (thisOption.type === 'category') {
  37801. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  37802. }
  37803. };
  37804. /**
  37805. * Should not be called before all of 'getInitailData' finished.
  37806. * Because categories are collected during initializing data.
  37807. */
  37808. AxisModel.prototype.getCategories = function (rawData) {
  37809. var option = this.option; // FIXME
  37810. // warning if called before all of 'getInitailData' finished.
  37811. if (option.type === 'category') {
  37812. if (rawData) {
  37813. return option.data;
  37814. }
  37815. return this.__ordinalMeta.categories;
  37816. }
  37817. };
  37818. AxisModel.prototype.getOrdinalMeta = function () {
  37819. return this.__ordinalMeta;
  37820. };
  37821. AxisModel.type = axisName + 'Axis.' + axisType;
  37822. AxisModel.defaultOption = defaultOption;
  37823. return AxisModel;
  37824. }(BaseAxisModelClass);
  37825. registers.registerComponentModel(AxisModel);
  37826. });
  37827. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  37828. }
  37829. function getAxisType(option) {
  37830. // Default axis with data is category axis
  37831. return option.type || (option.data ? 'category' : 'value');
  37832. }
  37833. var Cartesian =
  37834. /** @class */
  37835. function () {
  37836. function Cartesian(name) {
  37837. this.type = 'cartesian';
  37838. this._dimList = [];
  37839. this._axes = {};
  37840. this.name = name || '';
  37841. }
  37842. Cartesian.prototype.getAxis = function (dim) {
  37843. return this._axes[dim];
  37844. };
  37845. Cartesian.prototype.getAxes = function () {
  37846. return map(this._dimList, function (dim) {
  37847. return this._axes[dim];
  37848. }, this);
  37849. };
  37850. Cartesian.prototype.getAxesByScale = function (scaleType) {
  37851. scaleType = scaleType.toLowerCase();
  37852. return filter(this.getAxes(), function (axis) {
  37853. return axis.scale.type === scaleType;
  37854. });
  37855. };
  37856. Cartesian.prototype.addAxis = function (axis) {
  37857. var dim = axis.dim;
  37858. this._axes[dim] = axis;
  37859. this._dimList.push(dim);
  37860. };
  37861. return Cartesian;
  37862. }();
  37863. var cartesian2DDimensions = ['x', 'y'];
  37864. function canCalculateAffineTransform(scale) {
  37865. return scale.type === 'interval' || scale.type === 'time';
  37866. }
  37867. var Cartesian2D =
  37868. /** @class */
  37869. function (_super) {
  37870. __extends(Cartesian2D, _super);
  37871. function Cartesian2D() {
  37872. var _this = _super !== null && _super.apply(this, arguments) || this;
  37873. _this.type = 'cartesian2d';
  37874. _this.dimensions = cartesian2DDimensions;
  37875. return _this;
  37876. }
  37877. /**
  37878. * Calculate an affine transform matrix if two axes are time or value.
  37879. * It's mainly for accelartion on the large time series data.
  37880. */
  37881. Cartesian2D.prototype.calcAffineTransform = function () {
  37882. this._transform = this._invTransform = null;
  37883. var xAxisScale = this.getAxis('x').scale;
  37884. var yAxisScale = this.getAxis('y').scale;
  37885. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  37886. return;
  37887. }
  37888. var xScaleExtent = xAxisScale.getExtent();
  37889. var yScaleExtent = yAxisScale.getExtent();
  37890. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  37891. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  37892. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  37893. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  37894. if (!xScaleSpan || !yScaleSpan) {
  37895. return;
  37896. } // Accelerate data to point calculation on the special large time series data.
  37897. var scaleX = (end[0] - start[0]) / xScaleSpan;
  37898. var scaleY = (end[1] - start[1]) / yScaleSpan;
  37899. var translateX = start[0] - xScaleExtent[0] * scaleX;
  37900. var translateY = start[1] - yScaleExtent[0] * scaleY;
  37901. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  37902. this._invTransform = invert([], m);
  37903. };
  37904. /**
  37905. * Base axis will be used on stacking.
  37906. */
  37907. Cartesian2D.prototype.getBaseAxis = function () {
  37908. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  37909. };
  37910. Cartesian2D.prototype.containPoint = function (point) {
  37911. var axisX = this.getAxis('x');
  37912. var axisY = this.getAxis('y');
  37913. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  37914. };
  37915. Cartesian2D.prototype.containData = function (data) {
  37916. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  37917. };
  37918. Cartesian2D.prototype.containZone = function (data1, data2) {
  37919. var zoneDiag1 = this.dataToPoint(data1);
  37920. var zoneDiag2 = this.dataToPoint(data2);
  37921. var area = this.getArea();
  37922. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  37923. return area.intersect(zone);
  37924. };
  37925. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  37926. out = out || [];
  37927. var xVal = data[0];
  37928. var yVal = data[1]; // Fast path
  37929. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  37930. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  37931. return applyTransform(out, data, this._transform);
  37932. }
  37933. var xAxis = this.getAxis('x');
  37934. var yAxis = this.getAxis('y');
  37935. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  37936. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  37937. return out;
  37938. };
  37939. Cartesian2D.prototype.clampData = function (data, out) {
  37940. var xScale = this.getAxis('x').scale;
  37941. var yScale = this.getAxis('y').scale;
  37942. var xAxisExtent = xScale.getExtent();
  37943. var yAxisExtent = yScale.getExtent();
  37944. var x = xScale.parse(data[0]);
  37945. var y = yScale.parse(data[1]);
  37946. out = out || [];
  37947. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  37948. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  37949. return out;
  37950. };
  37951. Cartesian2D.prototype.pointToData = function (point, clamp) {
  37952. var out = [];
  37953. if (this._invTransform) {
  37954. return applyTransform(out, point, this._invTransform);
  37955. }
  37956. var xAxis = this.getAxis('x');
  37957. var yAxis = this.getAxis('y');
  37958. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  37959. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  37960. return out;
  37961. };
  37962. Cartesian2D.prototype.getOtherAxis = function (axis) {
  37963. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  37964. };
  37965. /**
  37966. * Get rect area of cartesian.
  37967. * Area will have a contain function to determine if a point is in the coordinate system.
  37968. */
  37969. Cartesian2D.prototype.getArea = function () {
  37970. var xExtent = this.getAxis('x').getGlobalExtent();
  37971. var yExtent = this.getAxis('y').getGlobalExtent();
  37972. var x = Math.min(xExtent[0], xExtent[1]);
  37973. var y = Math.min(yExtent[0], yExtent[1]);
  37974. var width = Math.max(xExtent[0], xExtent[1]) - x;
  37975. var height = Math.max(yExtent[0], yExtent[1]) - y;
  37976. return new BoundingRect(x, y, width, height);
  37977. };
  37978. return Cartesian2D;
  37979. }(Cartesian);
  37980. var Axis2D =
  37981. /** @class */
  37982. function (_super) {
  37983. __extends(Axis2D, _super);
  37984. function Axis2D(dim, scale, coordExtent, axisType, position) {
  37985. var _this = _super.call(this, dim, scale, coordExtent) || this;
  37986. /**
  37987. * Index of axis, can be used as key
  37988. * Injected outside.
  37989. */
  37990. _this.index = 0;
  37991. _this.type = axisType || 'value';
  37992. _this.position = position || 'bottom';
  37993. return _this;
  37994. }
  37995. Axis2D.prototype.isHorizontal = function () {
  37996. var position = this.position;
  37997. return position === 'top' || position === 'bottom';
  37998. };
  37999. /**
  38000. * Each item cooresponds to this.getExtent(), which
  38001. * means globalExtent[0] may greater than globalExtent[1],
  38002. * unless `asc` is input.
  38003. *
  38004. * @param {boolean} [asc]
  38005. * @return {Array.<number>}
  38006. */
  38007. Axis2D.prototype.getGlobalExtent = function (asc) {
  38008. var ret = this.getExtent();
  38009. ret[0] = this.toGlobalCoord(ret[0]);
  38010. ret[1] = this.toGlobalCoord(ret[1]);
  38011. asc && ret[0] > ret[1] && ret.reverse();
  38012. return ret;
  38013. };
  38014. Axis2D.prototype.pointToData = function (point, clamp) {
  38015. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  38016. };
  38017. /**
  38018. * Set ordinalSortInfo
  38019. * @param info new OrdinalSortInfo
  38020. */
  38021. Axis2D.prototype.setCategorySortInfo = function (info) {
  38022. if (this.type !== 'category') {
  38023. return false;
  38024. }
  38025. this.model.option.categorySortInfo = info;
  38026. this.scale.setSortInfo(info);
  38027. };
  38028. return Axis2D;
  38029. }(Axis);
  38030. /**
  38031. * Can only be called after coordinate system creation stage.
  38032. * (Can be called before coordinate system update stage).
  38033. */
  38034. function layout$1(gridModel, axisModel, opt) {
  38035. opt = opt || {};
  38036. var grid = gridModel.coordinateSystem;
  38037. var axis = axisModel.axis;
  38038. var layout = {};
  38039. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  38040. var rawAxisPosition = axis.position;
  38041. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  38042. var axisDim = axis.dim;
  38043. var rect = grid.getRect();
  38044. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  38045. var idx = {
  38046. left: 0,
  38047. right: 1,
  38048. top: 0,
  38049. bottom: 1,
  38050. onZero: 2
  38051. };
  38052. var axisOffset = axisModel.get('offset') || 0;
  38053. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  38054. if (otherAxisOnZeroOf) {
  38055. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  38056. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  38057. } // Axis position
  38058. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  38059. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  38060. var dirMap = {
  38061. top: -1,
  38062. bottom: 1,
  38063. left: -1,
  38064. right: 1
  38065. };
  38066. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  38067. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  38068. if (axisModel.get(['axisTick', 'inside'])) {
  38069. layout.tickDirection = -layout.tickDirection;
  38070. }
  38071. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  38072. layout.labelDirection = -layout.labelDirection;
  38073. } // Special label rotation
  38074. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  38075. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  38076. layout.z2 = 1;
  38077. return layout;
  38078. }
  38079. function isCartesian2DSeries(seriesModel) {
  38080. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  38081. }
  38082. function findAxisModels(seriesModel) {
  38083. var axisModelMap = {
  38084. xAxisModel: null,
  38085. yAxisModel: null
  38086. };
  38087. each(axisModelMap, function (v, key) {
  38088. var axisType = key.replace(/Model$/, '');
  38089. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  38090. if ("development" !== 'production') {
  38091. if (!axisModel) {
  38092. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  38093. }
  38094. }
  38095. axisModelMap[key] = axisModel;
  38096. });
  38097. return axisModelMap;
  38098. }
  38099. var mathLog$1 = Math.log;
  38100. function alignScaleTicks(scale, axisModel, alignToScale) {
  38101. var intervalScaleProto = IntervalScale.prototype; // NOTE: There is a precondition for log scale here:
  38102. // In log scale we store _interval and _extent of exponent value.
  38103. // So if we use the method of InternalScale to set/get these data.
  38104. // It process the exponent value, which is linear and what we want here.
  38105. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  38106. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  38107. var alignToSplitNumber = alignToTicks.length - 1;
  38108. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  38109. var scaleExtent = getScaleExtent(scale, axisModel);
  38110. var rawExtent = scaleExtent.extent;
  38111. var isMinFixed = scaleExtent.fixMin;
  38112. var isMaxFixed = scaleExtent.fixMax;
  38113. if (scale.type === 'log') {
  38114. var logBase = mathLog$1(scale.base);
  38115. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  38116. }
  38117. scale.setExtent(rawExtent[0], rawExtent[1]);
  38118. scale.calcNiceExtent({
  38119. splitNumber: alignToSplitNumber,
  38120. fixMin: isMinFixed,
  38121. fixMax: isMaxFixed
  38122. });
  38123. var extent = intervalScaleProto.getExtent.call(scale); // Need to update the rawExtent.
  38124. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  38125. if (isMinFixed) {
  38126. rawExtent[0] = extent[0];
  38127. }
  38128. if (isMaxFixed) {
  38129. rawExtent[1] = extent[1];
  38130. }
  38131. var interval = intervalScaleProto.getInterval.call(scale);
  38132. var min = rawExtent[0];
  38133. var max = rawExtent[1];
  38134. if (isMinFixed && isMaxFixed) {
  38135. // User set min, max, divide to get new interval
  38136. interval = (max - min) / alignToSplitNumber;
  38137. } else if (isMinFixed) {
  38138. max = rawExtent[0] + interval * alignToSplitNumber; // User set min, expand extent on the other side
  38139. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  38140. interval = increaseInterval(interval);
  38141. max = rawExtent[0] + interval * alignToSplitNumber;
  38142. }
  38143. } else if (isMaxFixed) {
  38144. // User set max, expand extent on the other side
  38145. min = rawExtent[1] - interval * alignToSplitNumber;
  38146. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  38147. interval = increaseInterval(interval);
  38148. min = rawExtent[1] - interval * alignToSplitNumber;
  38149. }
  38150. } else {
  38151. var nicedSplitNumber = scale.getTicks().length - 1;
  38152. if (nicedSplitNumber > alignToSplitNumber) {
  38153. interval = increaseInterval(interval);
  38154. }
  38155. var range = interval * alignToSplitNumber;
  38156. max = Math.ceil(rawExtent[1] / interval) * interval;
  38157. min = round(max - range); // Not change the result that crossing zero.
  38158. if (min < 0 && rawExtent[0] >= 0) {
  38159. min = 0;
  38160. max = round(range);
  38161. } else if (max > 0 && rawExtent[1] <= 0) {
  38162. max = 0;
  38163. min = -round(range);
  38164. }
  38165. } // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  38166. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  38167. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval; // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  38168. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  38169. intervalScaleProto.setInterval.call(scale, interval);
  38170. if (t0 || t1) {
  38171. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  38172. }
  38173. if ("development" !== 'production') {
  38174. var ticks = intervalScaleProto.getTicks.call(scale);
  38175. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  38176. warn( // eslint-disable-next-line
  38177. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  38178. }
  38179. }
  38180. }
  38181. var Grid =
  38182. /** @class */
  38183. function () {
  38184. function Grid(gridModel, ecModel, api) {
  38185. // FIXME:TS where used (different from registered type 'cartesian2d')?
  38186. this.type = 'grid';
  38187. this._coordsMap = {};
  38188. this._coordsList = [];
  38189. this._axesMap = {};
  38190. this._axesList = [];
  38191. this.axisPointerEnabled = true;
  38192. this.dimensions = cartesian2DDimensions;
  38193. this._initCartesian(gridModel, ecModel, api);
  38194. this.model = gridModel;
  38195. }
  38196. Grid.prototype.getRect = function () {
  38197. return this._rect;
  38198. };
  38199. Grid.prototype.update = function (ecModel, api) {
  38200. var axesMap = this._axesMap;
  38201. this._updateScale(ecModel, this.model);
  38202. function updateAxisTicks(axes) {
  38203. var alignTo; // Axis is added in order of axisIndex.
  38204. var axesIndices = keys(axes);
  38205. var len = axesIndices.length;
  38206. if (!len) {
  38207. return;
  38208. }
  38209. var axisNeedsAlign = []; // Process once and calculate the ticks for those don't use alignTicks.
  38210. for (var i = len - 1; i >= 0; i--) {
  38211. var idx = +axesIndices[i]; // Convert to number.
  38212. var axis = axes[idx];
  38213. var model = axis.model;
  38214. var scale = axis.scale;
  38215. if ( // Only value and log axis without interval support alignTicks.
  38216. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  38217. axisNeedsAlign.push(axis);
  38218. } else {
  38219. niceScaleExtent(scale, model);
  38220. if (isIntervalOrLogScale(scale)) {
  38221. // Can only align to interval or log axis.
  38222. alignTo = axis;
  38223. }
  38224. }
  38225. }
  38226. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  38227. if (axisNeedsAlign.length) {
  38228. if (!alignTo) {
  38229. alignTo = axisNeedsAlign.pop();
  38230. niceScaleExtent(alignTo.scale, alignTo.model);
  38231. }
  38232. each(axisNeedsAlign, function (axis) {
  38233. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  38234. });
  38235. }
  38236. }
  38237. updateAxisTicks(axesMap.x);
  38238. updateAxisTicks(axesMap.y); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  38239. var onZeroRecords = {};
  38240. each(axesMap.x, function (xAxis) {
  38241. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  38242. });
  38243. each(axesMap.y, function (yAxis) {
  38244. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  38245. }); // Resize again if containLabel is enabled
  38246. // FIXME It may cause getting wrong grid size in data processing stage
  38247. this.resize(this.model, api);
  38248. };
  38249. /**
  38250. * Resize the grid
  38251. */
  38252. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  38253. var boxLayoutParams = gridModel.getBoxLayoutParams();
  38254. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  38255. var gridRect = getLayoutRect(boxLayoutParams, {
  38256. width: api.getWidth(),
  38257. height: api.getHeight()
  38258. });
  38259. this._rect = gridRect;
  38260. var axesList = this._axesList;
  38261. adjustAxes(); // Minus label size
  38262. if (isContainLabel) {
  38263. each(axesList, function (axis) {
  38264. if (!axis.model.get(['axisLabel', 'inside'])) {
  38265. var labelUnionRect = estimateLabelUnionRect(axis);
  38266. if (labelUnionRect) {
  38267. var dim = axis.isHorizontal() ? 'height' : 'width';
  38268. var margin = axis.model.get(['axisLabel', 'margin']);
  38269. gridRect[dim] -= labelUnionRect[dim] + margin;
  38270. if (axis.position === 'top') {
  38271. gridRect.y += labelUnionRect.height + margin;
  38272. } else if (axis.position === 'left') {
  38273. gridRect.x += labelUnionRect.width + margin;
  38274. }
  38275. }
  38276. }
  38277. });
  38278. adjustAxes();
  38279. }
  38280. each(this._coordsList, function (coord) {
  38281. // Calculate affine matrix to accelerate the data to point transform.
  38282. // If all the axes scales are time or value.
  38283. coord.calcAffineTransform();
  38284. });
  38285. function adjustAxes() {
  38286. each(axesList, function (axis) {
  38287. var isHorizontal = axis.isHorizontal();
  38288. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  38289. var idx = axis.inverse ? 1 : 0;
  38290. axis.setExtent(extent[idx], extent[1 - idx]);
  38291. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  38292. });
  38293. }
  38294. };
  38295. Grid.prototype.getAxis = function (dim, axisIndex) {
  38296. var axesMapOnDim = this._axesMap[dim];
  38297. if (axesMapOnDim != null) {
  38298. return axesMapOnDim[axisIndex || 0];
  38299. }
  38300. };
  38301. Grid.prototype.getAxes = function () {
  38302. return this._axesList.slice();
  38303. };
  38304. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  38305. if (xAxisIndex != null && yAxisIndex != null) {
  38306. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  38307. return this._coordsMap[key];
  38308. }
  38309. if (isObject(xAxisIndex)) {
  38310. yAxisIndex = xAxisIndex.yAxisIndex;
  38311. xAxisIndex = xAxisIndex.xAxisIndex;
  38312. }
  38313. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  38314. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  38315. return coordList[i];
  38316. }
  38317. }
  38318. };
  38319. Grid.prototype.getCartesians = function () {
  38320. return this._coordsList.slice();
  38321. };
  38322. /**
  38323. * @implements
  38324. */
  38325. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  38326. var target = this._findConvertTarget(finder);
  38327. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  38328. };
  38329. /**
  38330. * @implements
  38331. */
  38332. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  38333. var target = this._findConvertTarget(finder);
  38334. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  38335. };
  38336. Grid.prototype._findConvertTarget = function (finder) {
  38337. var seriesModel = finder.seriesModel;
  38338. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  38339. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  38340. var gridModel = finder.gridModel;
  38341. var coordsList = this._coordsList;
  38342. var cartesian;
  38343. var axis;
  38344. if (seriesModel) {
  38345. cartesian = seriesModel.coordinateSystem;
  38346. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  38347. } else if (xAxisModel && yAxisModel) {
  38348. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  38349. } else if (xAxisModel) {
  38350. axis = this.getAxis('x', xAxisModel.componentIndex);
  38351. } else if (yAxisModel) {
  38352. axis = this.getAxis('y', yAxisModel.componentIndex);
  38353. } // Lowest priority.
  38354. else if (gridModel) {
  38355. var grid = gridModel.coordinateSystem;
  38356. if (grid === this) {
  38357. cartesian = this._coordsList[0];
  38358. }
  38359. }
  38360. return {
  38361. cartesian: cartesian,
  38362. axis: axis
  38363. };
  38364. };
  38365. /**
  38366. * @implements
  38367. */
  38368. Grid.prototype.containPoint = function (point) {
  38369. var coord = this._coordsList[0];
  38370. if (coord) {
  38371. return coord.containPoint(point);
  38372. }
  38373. };
  38374. /**
  38375. * Initialize cartesian coordinate systems
  38376. */
  38377. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  38378. var _this = this;
  38379. var grid = this;
  38380. var axisPositionUsed = {
  38381. left: false,
  38382. right: false,
  38383. top: false,
  38384. bottom: false
  38385. };
  38386. var axesMap = {
  38387. x: {},
  38388. y: {}
  38389. };
  38390. var axesCount = {
  38391. x: 0,
  38392. y: 0
  38393. }; /// Create axis
  38394. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  38395. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  38396. if (!axesCount.x || !axesCount.y) {
  38397. // Roll back when there no either x or y axis
  38398. this._axesMap = {};
  38399. this._axesList = [];
  38400. return;
  38401. }
  38402. this._axesMap = axesMap; /// Create cartesian2d
  38403. each(axesMap.x, function (xAxis, xAxisIndex) {
  38404. each(axesMap.y, function (yAxis, yAxisIndex) {
  38405. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  38406. var cartesian = new Cartesian2D(key);
  38407. cartesian.master = _this;
  38408. cartesian.model = gridModel;
  38409. _this._coordsMap[key] = cartesian;
  38410. _this._coordsList.push(cartesian);
  38411. cartesian.addAxis(xAxis);
  38412. cartesian.addAxis(yAxis);
  38413. });
  38414. });
  38415. function createAxisCreator(dimName) {
  38416. return function (axisModel, idx) {
  38417. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  38418. return;
  38419. }
  38420. var axisPosition = axisModel.get('position');
  38421. if (dimName === 'x') {
  38422. // Fix position
  38423. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  38424. // Default bottom of X
  38425. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  38426. }
  38427. } else {
  38428. // Fix position
  38429. if (axisPosition !== 'left' && axisPosition !== 'right') {
  38430. // Default left of Y
  38431. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  38432. }
  38433. }
  38434. axisPositionUsed[axisPosition] = true;
  38435. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  38436. var isCategory = axis.type === 'category';
  38437. axis.onBand = isCategory && axisModel.get('boundaryGap');
  38438. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  38439. axisModel.axis = axis; // Inject axisModel into axis
  38440. axis.model = axisModel; // Inject grid info axis
  38441. axis.grid = grid; // Index of axis, can be used as key
  38442. axis.index = idx;
  38443. grid._axesList.push(axis);
  38444. axesMap[dimName][idx] = axis;
  38445. axesCount[dimName]++;
  38446. };
  38447. }
  38448. };
  38449. /**
  38450. * Update cartesian properties from series.
  38451. */
  38452. Grid.prototype._updateScale = function (ecModel, gridModel) {
  38453. // Reset scale
  38454. each(this._axesList, function (axis) {
  38455. axis.scale.setExtent(Infinity, -Infinity);
  38456. if (axis.type === 'category') {
  38457. var categorySortInfo = axis.model.get('categorySortInfo');
  38458. axis.scale.setSortInfo(categorySortInfo);
  38459. }
  38460. });
  38461. ecModel.eachSeries(function (seriesModel) {
  38462. if (isCartesian2DSeries(seriesModel)) {
  38463. var axesModelMap = findAxisModels(seriesModel);
  38464. var xAxisModel = axesModelMap.xAxisModel;
  38465. var yAxisModel = axesModelMap.yAxisModel;
  38466. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  38467. return;
  38468. }
  38469. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  38470. var data = seriesModel.getData();
  38471. var xAxis = cartesian.getAxis('x');
  38472. var yAxis = cartesian.getAxis('y');
  38473. unionExtent(data, xAxis);
  38474. unionExtent(data, yAxis);
  38475. }
  38476. }, this);
  38477. function unionExtent(data, axis) {
  38478. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  38479. axis.scale.unionExtentFromData(data, dim);
  38480. });
  38481. }
  38482. };
  38483. /**
  38484. * @param dim 'x' or 'y' or 'auto' or null/undefined
  38485. */
  38486. Grid.prototype.getTooltipAxes = function (dim) {
  38487. var baseAxes = [];
  38488. var otherAxes = [];
  38489. each(this.getCartesians(), function (cartesian) {
  38490. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  38491. var otherAxis = cartesian.getOtherAxis(baseAxis);
  38492. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  38493. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  38494. });
  38495. return {
  38496. baseAxes: baseAxes,
  38497. otherAxes: otherAxes
  38498. };
  38499. };
  38500. Grid.create = function (ecModel, api) {
  38501. var grids = [];
  38502. ecModel.eachComponent('grid', function (gridModel, idx) {
  38503. var grid = new Grid(gridModel, ecModel, api);
  38504. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  38505. // should be performed in create stage.
  38506. grid.resize(gridModel, api, true);
  38507. gridModel.coordinateSystem = grid;
  38508. grids.push(grid);
  38509. }); // Inject the coordinateSystems into seriesModel
  38510. ecModel.eachSeries(function (seriesModel) {
  38511. if (!isCartesian2DSeries(seriesModel)) {
  38512. return;
  38513. }
  38514. var axesModelMap = findAxisModels(seriesModel);
  38515. var xAxisModel = axesModelMap.xAxisModel;
  38516. var yAxisModel = axesModelMap.yAxisModel;
  38517. var gridModel = xAxisModel.getCoordSysModel();
  38518. if ("development" !== 'production') {
  38519. if (!gridModel) {
  38520. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  38521. }
  38522. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  38523. throw new Error('xAxis and yAxis must use the same grid');
  38524. }
  38525. }
  38526. var grid = gridModel.coordinateSystem;
  38527. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  38528. });
  38529. return grids;
  38530. }; // For deciding which dimensions to use when creating list data
  38531. Grid.dimensions = cartesian2DDimensions;
  38532. return Grid;
  38533. }();
  38534. /**
  38535. * Check if the axis is used in the specified grid.
  38536. */
  38537. function isAxisUsedInTheGrid(axisModel, gridModel) {
  38538. return axisModel.getCoordSysModel() === gridModel;
  38539. }
  38540. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  38541. onZeroRecords) {
  38542. axis.getAxesOnZeroOf = function () {
  38543. // TODO: onZero of multiple axes.
  38544. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  38545. }; // onZero can not be enabled in these two situations:
  38546. // 1. When any other axis is a category axis.
  38547. // 2. When no axis is cross 0 point.
  38548. var otherAxes = axesMap[otherAxisDim];
  38549. var otherAxisOnZeroOf;
  38550. var axisModel = axis.model;
  38551. var onZero = axisModel.get(['axisLine', 'onZero']);
  38552. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  38553. if (!onZero) {
  38554. return;
  38555. } // If target axis is specified.
  38556. if (onZeroAxisIndex != null) {
  38557. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  38558. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  38559. }
  38560. } else {
  38561. // Find the first available other axis.
  38562. for (var idx in otherAxes) {
  38563. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  38564. // if both onZero, the two Y axes overlap.
  38565. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  38566. otherAxisOnZeroOf = otherAxes[idx];
  38567. break;
  38568. }
  38569. }
  38570. }
  38571. if (otherAxisOnZeroOf) {
  38572. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  38573. }
  38574. function getOnZeroRecordKey(axis) {
  38575. return axis.dim + '_' + axis.index;
  38576. }
  38577. }
  38578. function canOnZeroToAxis(axis) {
  38579. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  38580. }
  38581. function updateAxisTransform(axis, coordBase) {
  38582. var axisExtent = axis.getExtent();
  38583. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  38584. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  38585. return coord + coordBase;
  38586. } : function (coord) {
  38587. return axisExtentSum - coord + coordBase;
  38588. };
  38589. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  38590. return coord - coordBase;
  38591. } : function (coord) {
  38592. return axisExtentSum - coord + coordBase;
  38593. };
  38594. }
  38595. var PI$4 = Math.PI;
  38596. /**
  38597. * A final axis is translated and rotated from a "standard axis".
  38598. * So opt.position and opt.rotation is required.
  38599. *
  38600. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  38601. * for example: (0, 0) ------------> (0, 50)
  38602. *
  38603. * nameDirection or tickDirection or labelDirection is 1 means tick
  38604. * or label is below the standard axis, whereas is -1 means above
  38605. * the standard axis. labelOffset means offset between label and axis,
  38606. * which is useful when 'onZero', where axisLabel is in the grid and
  38607. * label in outside grid.
  38608. *
  38609. * Tips: like always,
  38610. * positive rotation represents anticlockwise, and negative rotation
  38611. * represents clockwise.
  38612. * The direction of position coordinate is the same as the direction
  38613. * of screen coordinate.
  38614. *
  38615. * Do not need to consider axis 'inverse', which is auto processed by
  38616. * axis extent.
  38617. */
  38618. var AxisBuilder =
  38619. /** @class */
  38620. function () {
  38621. function AxisBuilder(axisModel, opt) {
  38622. this.group = new Group();
  38623. this.opt = opt;
  38624. this.axisModel = axisModel; // Default value
  38625. defaults(opt, {
  38626. labelOffset: 0,
  38627. nameDirection: 1,
  38628. tickDirection: 1,
  38629. labelDirection: 1,
  38630. silent: true,
  38631. handleAutoShown: function () {
  38632. return true;
  38633. }
  38634. }); // FIXME Not use a seperate text group?
  38635. var transformGroup = new Group({
  38636. x: opt.position[0],
  38637. y: opt.position[1],
  38638. rotation: opt.rotation
  38639. }); // this.group.add(transformGroup);
  38640. // this._transformGroup = transformGroup;
  38641. transformGroup.updateTransform();
  38642. this._transformGroup = transformGroup;
  38643. }
  38644. AxisBuilder.prototype.hasBuilder = function (name) {
  38645. return !!builders[name];
  38646. };
  38647. AxisBuilder.prototype.add = function (name) {
  38648. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  38649. };
  38650. AxisBuilder.prototype.getGroup = function () {
  38651. return this.group;
  38652. };
  38653. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  38654. var rotationDiff = remRadian(textRotation - axisRotation);
  38655. var textAlign;
  38656. var textVerticalAlign;
  38657. if (isRadianAroundZero(rotationDiff)) {
  38658. // Label is parallel with axis line.
  38659. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  38660. textAlign = 'center';
  38661. } else if (isRadianAroundZero(rotationDiff - PI$4)) {
  38662. // Label is inverse parallel with axis line.
  38663. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  38664. textAlign = 'center';
  38665. } else {
  38666. textVerticalAlign = 'middle';
  38667. if (rotationDiff > 0 && rotationDiff < PI$4) {
  38668. textAlign = direction > 0 ? 'right' : 'left';
  38669. } else {
  38670. textAlign = direction > 0 ? 'left' : 'right';
  38671. }
  38672. }
  38673. return {
  38674. rotation: rotationDiff,
  38675. textAlign: textAlign,
  38676. textVerticalAlign: textVerticalAlign
  38677. };
  38678. };
  38679. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  38680. var eventData = {
  38681. componentType: axisModel.mainType,
  38682. componentIndex: axisModel.componentIndex
  38683. };
  38684. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  38685. return eventData;
  38686. };
  38687. AxisBuilder.isLabelSilent = function (axisModel) {
  38688. var tooltipOpt = axisModel.get('tooltip');
  38689. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  38690. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  38691. };
  38692. return AxisBuilder;
  38693. }();
  38694. var builders = {
  38695. axisLine: function (opt, axisModel, group, transformGroup) {
  38696. var shown = axisModel.get(['axisLine', 'show']);
  38697. if (shown === 'auto' && opt.handleAutoShown) {
  38698. shown = opt.handleAutoShown('axisLine');
  38699. }
  38700. if (!shown) {
  38701. return;
  38702. }
  38703. var extent = axisModel.axis.getExtent();
  38704. var matrix = transformGroup.transform;
  38705. var pt1 = [extent[0], 0];
  38706. var pt2 = [extent[1], 0];
  38707. if (matrix) {
  38708. applyTransform(pt1, pt1, matrix);
  38709. applyTransform(pt2, pt2, matrix);
  38710. }
  38711. var lineStyle = extend({
  38712. lineCap: 'round'
  38713. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  38714. var line = new Line({
  38715. // Id for animation
  38716. subPixelOptimize: true,
  38717. shape: {
  38718. x1: pt1[0],
  38719. y1: pt1[1],
  38720. x2: pt2[0],
  38721. y2: pt2[1]
  38722. },
  38723. style: lineStyle,
  38724. strokeContainThreshold: opt.strokeContainThreshold || 5,
  38725. silent: true,
  38726. z2: 1
  38727. });
  38728. line.anid = 'line';
  38729. group.add(line);
  38730. var arrows = axisModel.get(['axisLine', 'symbol']);
  38731. if (arrows != null) {
  38732. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  38733. if (isString(arrows)) {
  38734. // Use the same arrow for start and end point
  38735. arrows = [arrows, arrows];
  38736. }
  38737. if (isString(arrowSize) || isNumber(arrowSize)) {
  38738. // Use the same size for width and height
  38739. arrowSize = [arrowSize, arrowSize];
  38740. }
  38741. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  38742. var symbolWidth_1 = arrowSize[0];
  38743. var symbolHeight_1 = arrowSize[1];
  38744. each([{
  38745. rotate: opt.rotation + Math.PI / 2,
  38746. offset: arrowOffset[0],
  38747. r: 0
  38748. }, {
  38749. rotate: opt.rotation - Math.PI / 2,
  38750. offset: arrowOffset[1],
  38751. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  38752. }], function (point, index) {
  38753. if (arrows[index] !== 'none' && arrows[index] != null) {
  38754. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  38755. var r = point.r + point.offset;
  38756. symbol.attr({
  38757. rotation: point.rotate,
  38758. x: pt1[0] + r * Math.cos(opt.rotation),
  38759. y: pt1[1] - r * Math.sin(opt.rotation),
  38760. silent: true,
  38761. z2: 11
  38762. });
  38763. group.add(symbol);
  38764. }
  38765. });
  38766. }
  38767. },
  38768. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  38769. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  38770. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  38771. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  38772. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection); // This bit fixes the label overlap issue for the time chart.
  38773. // See https://github.com/apache/echarts/issues/14266 for more.
  38774. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  38775. var labelList = prepareLayoutList(map(labelEls, function (label) {
  38776. return {
  38777. label: label,
  38778. priority: label.z2,
  38779. defaultAttr: {
  38780. ignore: label.ignore
  38781. }
  38782. };
  38783. }));
  38784. hideOverlap(labelList);
  38785. }
  38786. },
  38787. axisName: function (opt, axisModel, group, transformGroup) {
  38788. var name = retrieve(opt.axisName, axisModel.get('name'));
  38789. if (!name) {
  38790. return;
  38791. }
  38792. var nameLocation = axisModel.get('nameLocation');
  38793. var nameDirection = opt.nameDirection;
  38794. var textStyleModel = axisModel.getModel('nameTextStyle');
  38795. var gap = axisModel.get('nameGap') || 0;
  38796. var extent = axisModel.axis.getExtent();
  38797. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  38798. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  38799. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  38800. var labelLayout;
  38801. var nameRotation = axisModel.get('nameRotate');
  38802. if (nameRotation != null) {
  38803. nameRotation = nameRotation * PI$4 / 180; // To radian.
  38804. }
  38805. var axisNameAvailableWidth;
  38806. if (isNameLocationCenter(nameLocation)) {
  38807. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  38808. nameDirection);
  38809. } else {
  38810. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  38811. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  38812. if (axisNameAvailableWidth != null) {
  38813. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  38814. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  38815. }
  38816. }
  38817. var textFont = textStyleModel.getFont();
  38818. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  38819. var ellipsis = truncateOpt.ellipsis;
  38820. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  38821. var textEl = new ZRText({
  38822. x: pos[0],
  38823. y: pos[1],
  38824. rotation: labelLayout.rotation,
  38825. silent: AxisBuilder.isLabelSilent(axisModel),
  38826. style: createTextStyle(textStyleModel, {
  38827. text: name,
  38828. font: textFont,
  38829. overflow: 'truncate',
  38830. width: maxWidth,
  38831. ellipsis: ellipsis,
  38832. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  38833. align: textStyleModel.get('align') || labelLayout.textAlign,
  38834. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  38835. }),
  38836. z2: 1
  38837. });
  38838. setTooltipConfig({
  38839. el: textEl,
  38840. componentModel: axisModel,
  38841. itemName: name
  38842. });
  38843. textEl.__fullText = name; // Id for animation
  38844. textEl.anid = 'name';
  38845. if (axisModel.get('triggerEvent')) {
  38846. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  38847. eventData.targetType = 'axisName';
  38848. eventData.name = name;
  38849. getECData(textEl).eventData = eventData;
  38850. } // FIXME
  38851. transformGroup.add(textEl);
  38852. textEl.updateTransform();
  38853. group.add(textEl);
  38854. textEl.decomposeTransform();
  38855. }
  38856. };
  38857. function endTextLayout(rotation, textPosition, textRotate, extent) {
  38858. var rotationDiff = remRadian(textRotate - rotation);
  38859. var textAlign;
  38860. var textVerticalAlign;
  38861. var inverse = extent[0] > extent[1];
  38862. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  38863. if (isRadianAroundZero(rotationDiff - PI$4 / 2)) {
  38864. textVerticalAlign = onLeft ? 'bottom' : 'top';
  38865. textAlign = 'center';
  38866. } else if (isRadianAroundZero(rotationDiff - PI$4 * 1.5)) {
  38867. textVerticalAlign = onLeft ? 'top' : 'bottom';
  38868. textAlign = 'center';
  38869. } else {
  38870. textVerticalAlign = 'middle';
  38871. if (rotationDiff < PI$4 * 1.5 && rotationDiff > PI$4 / 2) {
  38872. textAlign = onLeft ? 'left' : 'right';
  38873. } else {
  38874. textAlign = onLeft ? 'right' : 'left';
  38875. }
  38876. }
  38877. return {
  38878. rotation: rotationDiff,
  38879. textAlign: textAlign,
  38880. textVerticalAlign: textVerticalAlign
  38881. };
  38882. }
  38883. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  38884. if (shouldShowAllLabels(axisModel.axis)) {
  38885. return;
  38886. } // If min or max are user set, we need to check
  38887. // If the tick on min(max) are overlap on their neighbour tick
  38888. // If they are overlapped, we need to hide the min(max) tick label
  38889. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  38890. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  38891. // Have not consider onBand yet, where tick els is more than label els.
  38892. labelEls = labelEls || [];
  38893. tickEls = tickEls || [];
  38894. var firstLabel = labelEls[0];
  38895. var nextLabel = labelEls[1];
  38896. var lastLabel = labelEls[labelEls.length - 1];
  38897. var prevLabel = labelEls[labelEls.length - 2];
  38898. var firstTick = tickEls[0];
  38899. var nextTick = tickEls[1];
  38900. var lastTick = tickEls[tickEls.length - 1];
  38901. var prevTick = tickEls[tickEls.length - 2];
  38902. if (showMinLabel === false) {
  38903. ignoreEl(firstLabel);
  38904. ignoreEl(firstTick);
  38905. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  38906. if (showMinLabel) {
  38907. ignoreEl(nextLabel);
  38908. ignoreEl(nextTick);
  38909. } else {
  38910. ignoreEl(firstLabel);
  38911. ignoreEl(firstTick);
  38912. }
  38913. }
  38914. if (showMaxLabel === false) {
  38915. ignoreEl(lastLabel);
  38916. ignoreEl(lastTick);
  38917. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  38918. if (showMaxLabel) {
  38919. ignoreEl(prevLabel);
  38920. ignoreEl(prevTick);
  38921. } else {
  38922. ignoreEl(lastLabel);
  38923. ignoreEl(lastTick);
  38924. }
  38925. }
  38926. }
  38927. function ignoreEl(el) {
  38928. el && (el.ignore = true);
  38929. }
  38930. function isTwoLabelOverlapped(current, next) {
  38931. // current and next has the same rotation.
  38932. var firstRect = current && current.getBoundingRect().clone();
  38933. var nextRect = next && next.getBoundingRect().clone();
  38934. if (!firstRect || !nextRect) {
  38935. return;
  38936. } // When checking intersect of two rotated labels, we use mRotationBack
  38937. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  38938. var mRotationBack = identity([]);
  38939. rotate(mRotationBack, mRotationBack, -current.rotation);
  38940. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  38941. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  38942. return firstRect.intersect(nextRect);
  38943. }
  38944. function isNameLocationCenter(nameLocation) {
  38945. return nameLocation === 'middle' || nameLocation === 'center';
  38946. }
  38947. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  38948. var tickEls = [];
  38949. var pt1 = [];
  38950. var pt2 = [];
  38951. for (var i = 0; i < ticksCoords.length; i++) {
  38952. var tickCoord = ticksCoords[i].coord;
  38953. pt1[0] = tickCoord;
  38954. pt1[1] = 0;
  38955. pt2[0] = tickCoord;
  38956. pt2[1] = tickEndCoord;
  38957. if (tickTransform) {
  38958. applyTransform(pt1, pt1, tickTransform);
  38959. applyTransform(pt2, pt2, tickTransform);
  38960. } // Tick line, Not use group transform to have better line draw
  38961. var tickEl = new Line({
  38962. subPixelOptimize: true,
  38963. shape: {
  38964. x1: pt1[0],
  38965. y1: pt1[1],
  38966. x2: pt2[0],
  38967. y2: pt2[1]
  38968. },
  38969. style: tickLineStyle,
  38970. z2: 2,
  38971. autoBatch: true,
  38972. silent: true
  38973. });
  38974. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  38975. tickEls.push(tickEl);
  38976. }
  38977. return tickEls;
  38978. }
  38979. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  38980. var axis = axisModel.axis;
  38981. var tickModel = axisModel.getModel('axisTick');
  38982. var shown = tickModel.get('show');
  38983. if (shown === 'auto' && opt.handleAutoShown) {
  38984. shown = opt.handleAutoShown('axisTick');
  38985. }
  38986. if (!shown || axis.scale.isBlank()) {
  38987. return;
  38988. }
  38989. var lineStyleModel = tickModel.getModel('lineStyle');
  38990. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  38991. var ticksCoords = axis.getTicksCoords();
  38992. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  38993. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  38994. }), 'ticks');
  38995. for (var i = 0; i < ticksEls.length; i++) {
  38996. group.add(ticksEls[i]);
  38997. }
  38998. return ticksEls;
  38999. }
  39000. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  39001. var axis = axisModel.axis;
  39002. var minorTickModel = axisModel.getModel('minorTick');
  39003. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  39004. return;
  39005. }
  39006. var minorTicksCoords = axis.getMinorTicksCoords();
  39007. if (!minorTicksCoords.length) {
  39008. return;
  39009. }
  39010. var lineStyleModel = minorTickModel.getModel('lineStyle');
  39011. var tickEndCoord = tickDirection * minorTickModel.get('length');
  39012. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  39013. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  39014. }));
  39015. for (var i = 0; i < minorTicksCoords.length; i++) {
  39016. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  39017. for (var k = 0; k < minorTicksEls.length; k++) {
  39018. group.add(minorTicksEls[k]);
  39019. }
  39020. }
  39021. }
  39022. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  39023. var axis = axisModel.axis;
  39024. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  39025. if (!show || axis.scale.isBlank()) {
  39026. return;
  39027. }
  39028. var labelModel = axisModel.getModel('axisLabel');
  39029. var labelMargin = labelModel.get('margin');
  39030. var labels = axis.getViewLabels(); // Special label rotate.
  39031. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$4 / 180;
  39032. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  39033. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  39034. var labelEls = [];
  39035. var silent = AxisBuilder.isLabelSilent(axisModel);
  39036. var triggerEvent = axisModel.get('triggerEvent');
  39037. each(labels, function (labelItem, index) {
  39038. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  39039. var formattedLabel = labelItem.formattedLabel;
  39040. var rawLabel = labelItem.rawLabel;
  39041. var itemLabelModel = labelModel;
  39042. if (rawCategoryData && rawCategoryData[tickValue]) {
  39043. var rawCategoryItem = rawCategoryData[tickValue];
  39044. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  39045. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  39046. }
  39047. }
  39048. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  39049. var tickCoord = axis.dataToCoord(tickValue);
  39050. var textEl = new ZRText({
  39051. x: tickCoord,
  39052. y: opt.labelOffset + opt.labelDirection * labelMargin,
  39053. rotation: labelLayout.rotation,
  39054. silent: silent,
  39055. z2: 10 + (labelItem.level || 0),
  39056. style: createTextStyle(itemLabelModel, {
  39057. text: formattedLabel,
  39058. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  39059. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  39060. fill: isFunction(textColor) ? textColor( // (1) In category axis with data zoom, tick is not the original
  39061. // index of axis.data. So tick should not be exposed to user
  39062. // in category axis.
  39063. // (2) Compatible with previous version, which always use formatted label as
  39064. // input. But in interval scale the formatted label is like '223,445', which
  39065. // maked user repalce ','. So we modify it to return original val but remain
  39066. // it as 'string' to avoid error in replacing.
  39067. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  39068. })
  39069. });
  39070. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  39071. if (triggerEvent) {
  39072. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  39073. eventData.targetType = 'axisLabel';
  39074. eventData.value = rawLabel;
  39075. eventData.tickIndex = index;
  39076. if (axis.type === 'category') {
  39077. eventData.dataIndex = tickValue;
  39078. }
  39079. getECData(textEl).eventData = eventData;
  39080. } // FIXME
  39081. transformGroup.add(textEl);
  39082. textEl.updateTransform();
  39083. labelEls.push(textEl);
  39084. group.add(textEl);
  39085. textEl.decomposeTransform();
  39086. });
  39087. return labelEls;
  39088. }
  39089. function fixValue(axisModel) {
  39090. var axisInfo = getAxisInfo(axisModel);
  39091. if (!axisInfo) {
  39092. return;
  39093. }
  39094. var axisPointerModel = axisInfo.axisPointerModel;
  39095. var scale = axisInfo.axis.scale;
  39096. var option = axisPointerModel.option;
  39097. var status = axisPointerModel.get('status');
  39098. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  39099. if (value != null) {
  39100. value = scale.parse(value);
  39101. }
  39102. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  39103. // and status should be initialized.
  39104. if (status == null) {
  39105. option.status = useHandle ? 'show' : 'hide';
  39106. }
  39107. var extent = scale.getExtent().slice();
  39108. extent[0] > extent[1] && extent.reverse();
  39109. if ( // Pick a value on axis when initializing.
  39110. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  39111. // where we should re-pick a value to keep `handle` displaying normally.
  39112. || value > extent[1]) {
  39113. // Make handle displayed on the end of the axis when init, which looks better.
  39114. value = extent[1];
  39115. }
  39116. if (value < extent[0]) {
  39117. value = extent[0];
  39118. }
  39119. option.value = value;
  39120. if (useHandle) {
  39121. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  39122. }
  39123. }
  39124. function getAxisInfo(axisModel) {
  39125. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  39126. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  39127. }
  39128. function getAxisPointerModel(axisModel) {
  39129. var axisInfo = getAxisInfo(axisModel);
  39130. return axisInfo && axisInfo.axisPointerModel;
  39131. }
  39132. function isHandleTrigger(axisPointerModel) {
  39133. return !!axisPointerModel.get(['handle', 'show']);
  39134. }
  39135. /**
  39136. * @param {module:echarts/model/Model} model
  39137. * @return {string} unique key
  39138. */
  39139. function makeKey(model) {
  39140. return model.type + '||' + model.id;
  39141. }
  39142. var axisPointerClazz = {};
  39143. /**
  39144. * Base class of AxisView.
  39145. */
  39146. var AxisView =
  39147. /** @class */
  39148. function (_super) {
  39149. __extends(AxisView, _super);
  39150. function AxisView() {
  39151. var _this = _super !== null && _super.apply(this, arguments) || this;
  39152. _this.type = AxisView.type;
  39153. return _this;
  39154. }
  39155. /**
  39156. * @override
  39157. */
  39158. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  39159. // FIXME
  39160. // This process should proformed after coordinate systems updated
  39161. // (axis scale updated), and should be performed each time update.
  39162. // So put it here temporarily, although it is not appropriate to
  39163. // put a model-writing procedure in `view`.
  39164. this.axisPointerClass && fixValue(axisModel);
  39165. _super.prototype.render.apply(this, arguments);
  39166. this._doUpdateAxisPointerClass(axisModel, api, true);
  39167. };
  39168. /**
  39169. * Action handler.
  39170. */
  39171. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  39172. this._doUpdateAxisPointerClass(axisModel, api, false);
  39173. };
  39174. /**
  39175. * @override
  39176. */
  39177. AxisView.prototype.remove = function (ecModel, api) {
  39178. var axisPointer = this._axisPointer;
  39179. axisPointer && axisPointer.remove(api);
  39180. };
  39181. /**
  39182. * @override
  39183. */
  39184. AxisView.prototype.dispose = function (ecModel, api) {
  39185. this._disposeAxisPointer(api);
  39186. _super.prototype.dispose.apply(this, arguments);
  39187. };
  39188. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  39189. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  39190. if (!Clazz) {
  39191. return;
  39192. }
  39193. var axisPointerModel = getAxisPointerModel(axisModel);
  39194. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  39195. };
  39196. AxisView.prototype._disposeAxisPointer = function (api) {
  39197. this._axisPointer && this._axisPointer.dispose(api);
  39198. this._axisPointer = null;
  39199. };
  39200. AxisView.registerAxisPointerClass = function (type, clazz) {
  39201. if ("development" !== 'production') {
  39202. if (axisPointerClazz[type]) {
  39203. throw new Error('axisPointer ' + type + ' exists');
  39204. }
  39205. }
  39206. axisPointerClazz[type] = clazz;
  39207. };
  39208. AxisView.getAxisPointerClass = function (type) {
  39209. return type && axisPointerClazz[type];
  39210. };
  39211. AxisView.type = 'axis';
  39212. return AxisView;
  39213. }(ComponentView);
  39214. var inner$6 = makeInner();
  39215. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  39216. var axis = axisModel.axis;
  39217. if (axis.scale.isBlank()) {
  39218. return;
  39219. } // TODO: TYPE
  39220. var splitAreaModel = axisModel.getModel('splitArea');
  39221. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  39222. var areaColors = areaStyleModel.get('color');
  39223. var gridRect = gridModel.coordinateSystem.getRect();
  39224. var ticksCoords = axis.getTicksCoords({
  39225. tickModel: splitAreaModel,
  39226. clamp: true
  39227. });
  39228. if (!ticksCoords.length) {
  39229. return;
  39230. } // For Making appropriate splitArea animation, the color and anid
  39231. // should be corresponding to previous one if possible.
  39232. var areaColorsLen = areaColors.length;
  39233. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  39234. var newSplitAreaColors = createHashMap();
  39235. var colorIndex = 0;
  39236. if (lastSplitAreaColors) {
  39237. for (var i = 0; i < ticksCoords.length; i++) {
  39238. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  39239. if (cIndex != null) {
  39240. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  39241. break;
  39242. }
  39243. }
  39244. }
  39245. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  39246. var areaStyle = areaStyleModel.getAreaStyle();
  39247. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  39248. for (var i = 1; i < ticksCoords.length; i++) {
  39249. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  39250. var x = void 0;
  39251. var y = void 0;
  39252. var width = void 0;
  39253. var height = void 0;
  39254. if (axis.isHorizontal()) {
  39255. x = prev;
  39256. y = gridRect.y;
  39257. width = tickCoord - x;
  39258. height = gridRect.height;
  39259. prev = x + width;
  39260. } else {
  39261. x = gridRect.x;
  39262. y = prev;
  39263. width = gridRect.width;
  39264. height = tickCoord - y;
  39265. prev = y + height;
  39266. }
  39267. var tickValue = ticksCoords[i - 1].tickValue;
  39268. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  39269. axisGroup.add(new Rect({
  39270. anid: tickValue != null ? 'area_' + tickValue : null,
  39271. shape: {
  39272. x: x,
  39273. y: y,
  39274. width: width,
  39275. height: height
  39276. },
  39277. style: defaults({
  39278. fill: areaColors[colorIndex]
  39279. }, areaStyle),
  39280. autoBatch: true,
  39281. silent: true
  39282. }));
  39283. colorIndex = (colorIndex + 1) % areaColorsLen;
  39284. }
  39285. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  39286. }
  39287. function rectCoordAxisHandleRemove(axisView) {
  39288. inner$6(axisView).splitAreaColors = null;
  39289. }
  39290. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  39291. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  39292. var CartesianAxisView =
  39293. /** @class */
  39294. function (_super) {
  39295. __extends(CartesianAxisView, _super);
  39296. function CartesianAxisView() {
  39297. var _this = _super !== null && _super.apply(this, arguments) || this;
  39298. _this.type = CartesianAxisView.type;
  39299. _this.axisPointerClass = 'CartesianAxisPointer';
  39300. return _this;
  39301. }
  39302. /**
  39303. * @override
  39304. */
  39305. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  39306. this.group.removeAll();
  39307. var oldAxisGroup = this._axisGroup;
  39308. this._axisGroup = new Group();
  39309. this.group.add(this._axisGroup);
  39310. if (!axisModel.get('show')) {
  39311. return;
  39312. }
  39313. var gridModel = axisModel.getCoordSysModel();
  39314. var layout = layout$1(gridModel, axisModel);
  39315. var axisBuilder = new AxisBuilder(axisModel, extend({
  39316. handleAutoShown: function (elementType) {
  39317. var cartesians = gridModel.coordinateSystem.getCartesians();
  39318. for (var i = 0; i < cartesians.length; i++) {
  39319. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  39320. // Still show axis tick or axisLine if other axis is value / log
  39321. return true;
  39322. }
  39323. } // Not show axisTick or axisLine if other axis is category / time
  39324. return false;
  39325. }
  39326. }, layout));
  39327. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  39328. this._axisGroup.add(axisBuilder.getGroup());
  39329. each(selfBuilderAttrs, function (name) {
  39330. if (axisModel.get([name, 'show'])) {
  39331. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  39332. }
  39333. }, this); // THIS is a special case for bar racing chart.
  39334. // Update the axis label from the natural initial layout to
  39335. // sorted layout should has no animation.
  39336. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  39337. if (!isInitialSortFromBarRacing) {
  39338. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  39339. }
  39340. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  39341. };
  39342. CartesianAxisView.prototype.remove = function () {
  39343. rectCoordAxisHandleRemove(this);
  39344. };
  39345. CartesianAxisView.type = 'cartesianAxis';
  39346. return CartesianAxisView;
  39347. }(AxisView);
  39348. var axisElementBuilders = {
  39349. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  39350. var axis = axisModel.axis;
  39351. if (axis.scale.isBlank()) {
  39352. return;
  39353. }
  39354. var splitLineModel = axisModel.getModel('splitLine');
  39355. var lineStyleModel = splitLineModel.getModel('lineStyle');
  39356. var lineColors = lineStyleModel.get('color');
  39357. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  39358. var gridRect = gridModel.coordinateSystem.getRect();
  39359. var isHorizontal = axis.isHorizontal();
  39360. var lineCount = 0;
  39361. var ticksCoords = axis.getTicksCoords({
  39362. tickModel: splitLineModel
  39363. });
  39364. var p1 = [];
  39365. var p2 = [];
  39366. var lineStyle = lineStyleModel.getLineStyle();
  39367. for (var i = 0; i < ticksCoords.length; i++) {
  39368. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  39369. if (isHorizontal) {
  39370. p1[0] = tickCoord;
  39371. p1[1] = gridRect.y;
  39372. p2[0] = tickCoord;
  39373. p2[1] = gridRect.y + gridRect.height;
  39374. } else {
  39375. p1[0] = gridRect.x;
  39376. p1[1] = tickCoord;
  39377. p2[0] = gridRect.x + gridRect.width;
  39378. p2[1] = tickCoord;
  39379. }
  39380. var colorIndex = lineCount++ % lineColors.length;
  39381. var tickValue = ticksCoords[i].tickValue;
  39382. axisGroup.add(new Line({
  39383. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  39384. subPixelOptimize: true,
  39385. autoBatch: true,
  39386. shape: {
  39387. x1: p1[0],
  39388. y1: p1[1],
  39389. x2: p2[0],
  39390. y2: p2[1]
  39391. },
  39392. style: defaults({
  39393. stroke: lineColors[colorIndex]
  39394. }, lineStyle),
  39395. silent: true
  39396. }));
  39397. }
  39398. },
  39399. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  39400. var axis = axisModel.axis;
  39401. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  39402. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  39403. var gridRect = gridModel.coordinateSystem.getRect();
  39404. var isHorizontal = axis.isHorizontal();
  39405. var minorTicksCoords = axis.getMinorTicksCoords();
  39406. if (!minorTicksCoords.length) {
  39407. return;
  39408. }
  39409. var p1 = [];
  39410. var p2 = [];
  39411. var lineStyle = lineStyleModel.getLineStyle();
  39412. for (var i = 0; i < minorTicksCoords.length; i++) {
  39413. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  39414. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  39415. if (isHorizontal) {
  39416. p1[0] = tickCoord;
  39417. p1[1] = gridRect.y;
  39418. p2[0] = tickCoord;
  39419. p2[1] = gridRect.y + gridRect.height;
  39420. } else {
  39421. p1[0] = gridRect.x;
  39422. p1[1] = tickCoord;
  39423. p2[0] = gridRect.x + gridRect.width;
  39424. p2[1] = tickCoord;
  39425. }
  39426. axisGroup.add(new Line({
  39427. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  39428. subPixelOptimize: true,
  39429. autoBatch: true,
  39430. shape: {
  39431. x1: p1[0],
  39432. y1: p1[1],
  39433. x2: p2[0],
  39434. y2: p2[1]
  39435. },
  39436. style: lineStyle,
  39437. silent: true
  39438. }));
  39439. }
  39440. }
  39441. },
  39442. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  39443. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  39444. }
  39445. };
  39446. var CartesianXAxisView =
  39447. /** @class */
  39448. function (_super) {
  39449. __extends(CartesianXAxisView, _super);
  39450. function CartesianXAxisView() {
  39451. var _this = _super !== null && _super.apply(this, arguments) || this;
  39452. _this.type = CartesianXAxisView.type;
  39453. return _this;
  39454. }
  39455. CartesianXAxisView.type = 'xAxis';
  39456. return CartesianXAxisView;
  39457. }(CartesianAxisView);
  39458. var CartesianYAxisView =
  39459. /** @class */
  39460. function (_super) {
  39461. __extends(CartesianYAxisView, _super);
  39462. function CartesianYAxisView() {
  39463. var _this = _super !== null && _super.apply(this, arguments) || this;
  39464. _this.type = CartesianXAxisView.type;
  39465. return _this;
  39466. }
  39467. CartesianYAxisView.type = 'yAxis';
  39468. return CartesianYAxisView;
  39469. }(CartesianAxisView);
  39470. var GridView =
  39471. /** @class */
  39472. function (_super) {
  39473. __extends(GridView, _super);
  39474. function GridView() {
  39475. var _this = _super !== null && _super.apply(this, arguments) || this;
  39476. _this.type = 'grid';
  39477. return _this;
  39478. }
  39479. GridView.prototype.render = function (gridModel, ecModel) {
  39480. this.group.removeAll();
  39481. if (gridModel.get('show')) {
  39482. this.group.add(new Rect({
  39483. shape: gridModel.coordinateSystem.getRect(),
  39484. style: defaults({
  39485. fill: gridModel.get('backgroundColor')
  39486. }, gridModel.getItemStyle()),
  39487. silent: true,
  39488. z2: -1
  39489. }));
  39490. }
  39491. };
  39492. GridView.type = 'grid';
  39493. return GridView;
  39494. }(ComponentView);
  39495. var extraOption = {
  39496. // gridIndex: 0,
  39497. // gridId: '',
  39498. offset: 0
  39499. };
  39500. function install$4(registers) {
  39501. registers.registerComponentView(GridView);
  39502. registers.registerComponentModel(GridModel);
  39503. registers.registerCoordinateSystem('cartesian2d', Grid);
  39504. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  39505. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  39506. registers.registerComponentView(CartesianXAxisView);
  39507. registers.registerComponentView(CartesianYAxisView);
  39508. registers.registerPreprocessor(function (option) {
  39509. // Only create grid when need
  39510. if (option.xAxis && option.yAxis && !option.grid) {
  39511. option.grid = {};
  39512. }
  39513. });
  39514. }
  39515. var DEFAULT_OPTION = {
  39516. label: {
  39517. enabled: true
  39518. },
  39519. decal: {
  39520. show: false
  39521. }
  39522. };
  39523. var inner$7 = makeInner();
  39524. var decalPaletteScope = {};
  39525. function ariaVisual(ecModel, api) {
  39526. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  39527. if (!ariaModel.get('enabled')) {
  39528. return;
  39529. }
  39530. var defaultOption = clone(DEFAULT_OPTION);
  39531. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  39532. merge(ariaModel.option, defaultOption, false);
  39533. setDecal();
  39534. setLabel();
  39535. function setDecal() {
  39536. var decalModel = ariaModel.getModel('decal');
  39537. var useDecal = decalModel.get('show');
  39538. if (useDecal) {
  39539. // Each type of series use one scope.
  39540. // Pie and funnel are using diferrent scopes
  39541. var paletteScopeGroupByType_1 = createHashMap();
  39542. ecModel.eachSeries(function (seriesModel) {
  39543. if (seriesModel.isColorBySeries()) {
  39544. return;
  39545. }
  39546. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  39547. if (!decalScope) {
  39548. decalScope = {};
  39549. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  39550. }
  39551. inner$7(seriesModel).scope = decalScope;
  39552. });
  39553. ecModel.eachRawSeries(function (seriesModel) {
  39554. if (ecModel.isSeriesFiltered(seriesModel)) {
  39555. return;
  39556. }
  39557. if (isFunction(seriesModel.enableAriaDecal)) {
  39558. // Let series define how to use decal palette on data
  39559. seriesModel.enableAriaDecal();
  39560. return;
  39561. }
  39562. var data = seriesModel.getData();
  39563. if (!seriesModel.isColorBySeries()) {
  39564. var dataAll_1 = seriesModel.getRawData();
  39565. var idxMap_1 = {};
  39566. var decalScope_1 = inner$7(seriesModel).scope;
  39567. data.each(function (idx) {
  39568. var rawIdx = data.getRawIndex(idx);
  39569. idxMap_1[rawIdx] = idx;
  39570. });
  39571. var dataCount_1 = dataAll_1.count();
  39572. dataAll_1.each(function (rawIdx) {
  39573. var idx = idxMap_1[rawIdx];
  39574. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  39575. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  39576. var specifiedDecal = data.getItemVisual(idx, 'decal');
  39577. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  39578. });
  39579. } else {
  39580. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  39581. var specifiedDecal = data.getVisual('decal');
  39582. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  39583. }
  39584. function mergeDecal(specifiedDecal, paletteDecal) {
  39585. // Merge decal from palette to decal from itemStyle.
  39586. // User do not need to specify all of the decal props.
  39587. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  39588. resultDecal.dirty = true;
  39589. return resultDecal;
  39590. }
  39591. });
  39592. }
  39593. }
  39594. function setLabel() {
  39595. var labelLocale = ecModel.getLocaleModel().get('aria');
  39596. var labelModel = ariaModel.getModel('label');
  39597. labelModel.option = defaults(labelModel.option, labelLocale);
  39598. if (!labelModel.get('enabled')) {
  39599. return;
  39600. }
  39601. var dom = api.getZr().dom;
  39602. if (labelModel.get('description')) {
  39603. dom.setAttribute('aria-label', labelModel.get('description'));
  39604. return;
  39605. }
  39606. var seriesCnt = ecModel.getSeriesCount();
  39607. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  39608. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  39609. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  39610. var ariaLabel;
  39611. if (seriesCnt < 1) {
  39612. // No series, no aria label
  39613. return;
  39614. } else {
  39615. var title = getTitle();
  39616. if (title) {
  39617. var withTitle = labelModel.get(['general', 'withTitle']);
  39618. ariaLabel = replace(withTitle, {
  39619. title: title
  39620. });
  39621. } else {
  39622. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  39623. }
  39624. var seriesLabels_1 = [];
  39625. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  39626. ariaLabel += replace(prefix, {
  39627. seriesCount: seriesCnt
  39628. });
  39629. ecModel.eachSeries(function (seriesModel, idx) {
  39630. if (idx < displaySeriesCnt) {
  39631. var seriesLabel = void 0;
  39632. var seriesName = seriesModel.get('name');
  39633. var withName = seriesName ? 'withName' : 'withoutName';
  39634. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  39635. seriesLabel = replace(seriesLabel, {
  39636. seriesId: seriesModel.seriesIndex,
  39637. seriesName: seriesModel.get('name'),
  39638. seriesType: getSeriesTypeName(seriesModel.subType)
  39639. });
  39640. var data = seriesModel.getData();
  39641. if (data.count() > maxDataCnt) {
  39642. // Show part of data
  39643. var partialLabel = labelModel.get(['data', 'partialData']);
  39644. seriesLabel += replace(partialLabel, {
  39645. displayCnt: maxDataCnt
  39646. });
  39647. } else {
  39648. seriesLabel += labelModel.get(['data', 'allData']);
  39649. }
  39650. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  39651. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  39652. var dataLabels = [];
  39653. for (var i = 0; i < data.count(); i++) {
  39654. if (i < maxDataCnt) {
  39655. var name_1 = data.getName(i);
  39656. var value = data.getValues(i);
  39657. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  39658. dataLabels.push(replace(dataLabel, {
  39659. name: name_1,
  39660. value: value.join(middleSeparator_1)
  39661. }));
  39662. }
  39663. }
  39664. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  39665. seriesLabels_1.push(seriesLabel);
  39666. }
  39667. });
  39668. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  39669. var middleSeparator = separatorModel.get('middle');
  39670. var endSeparator = separatorModel.get('end');
  39671. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  39672. dom.setAttribute('aria-label', ariaLabel);
  39673. }
  39674. }
  39675. function replace(str, keyValues) {
  39676. if (!isString(str)) {
  39677. return str;
  39678. }
  39679. var result = str;
  39680. each(keyValues, function (value, key) {
  39681. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  39682. });
  39683. return result;
  39684. }
  39685. function getTitle() {
  39686. var title = ecModel.get('title');
  39687. if (title && title.length) {
  39688. title = title[0];
  39689. }
  39690. return title && title.text;
  39691. }
  39692. function getSeriesTypeName(type) {
  39693. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  39694. }
  39695. }
  39696. function ariaPreprocessor(option) {
  39697. if (!option || !option.aria) {
  39698. return;
  39699. }
  39700. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  39701. if (aria.show != null) {
  39702. aria.enabled = aria.show;
  39703. }
  39704. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  39705. each(['description', 'general', 'series', 'data'], function (name) {
  39706. if (aria[name] != null) {
  39707. aria.label[name] = aria[name];
  39708. }
  39709. });
  39710. }
  39711. function install$5(registers) {
  39712. registers.registerPreprocessor(ariaPreprocessor);
  39713. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  39714. }
  39715. var DatasetModel =
  39716. /** @class */
  39717. function (_super) {
  39718. __extends(DatasetModel, _super);
  39719. function DatasetModel() {
  39720. var _this = _super !== null && _super.apply(this, arguments) || this;
  39721. _this.type = 'dataset';
  39722. return _this;
  39723. }
  39724. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  39725. _super.prototype.init.call(this, option, parentModel, ecModel);
  39726. this._sourceManager = new SourceManager(this);
  39727. disableTransformOptionMerge(this);
  39728. };
  39729. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  39730. _super.prototype.mergeOption.call(this, newOption, ecModel);
  39731. disableTransformOptionMerge(this);
  39732. };
  39733. DatasetModel.prototype.optionUpdated = function () {
  39734. this._sourceManager.dirty();
  39735. };
  39736. DatasetModel.prototype.getSourceManager = function () {
  39737. return this._sourceManager;
  39738. };
  39739. DatasetModel.type = 'dataset';
  39740. DatasetModel.defaultOption = {
  39741. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  39742. };
  39743. return DatasetModel;
  39744. }(ComponentModel);
  39745. var DatasetView =
  39746. /** @class */
  39747. function (_super) {
  39748. __extends(DatasetView, _super);
  39749. function DatasetView() {
  39750. var _this = _super !== null && _super.apply(this, arguments) || this;
  39751. _this.type = 'dataset';
  39752. return _this;
  39753. }
  39754. DatasetView.type = 'dataset';
  39755. return DatasetView;
  39756. }(ComponentView);
  39757. function install$6(registers) {
  39758. registers.registerComponentModel(DatasetModel);
  39759. registers.registerComponentView(DatasetView);
  39760. }
  39761. use([install]);
  39762. use([install$1, install$2, install$3]);
  39763. use([install$4, install$5, install$6]);
  39764. exports.Axis = Axis;
  39765. exports.ChartView = ChartView;
  39766. exports.ComponentModel = ComponentModel;
  39767. exports.ComponentView = ComponentView;
  39768. exports.List = SeriesData;
  39769. exports.Model = Model;
  39770. exports.PRIORITY = PRIORITY;
  39771. exports.SeriesModel = SeriesModel;
  39772. exports.color = color;
  39773. exports.connect = connect;
  39774. exports.dataTool = dataTool;
  39775. exports.dependencies = dependencies;
  39776. exports.disConnect = disConnect;
  39777. exports.disconnect = disconnect;
  39778. exports.dispose = dispose$1;
  39779. exports.env = env;
  39780. exports.extendChartView = extendChartView;
  39781. exports.extendComponentModel = extendComponentModel;
  39782. exports.extendComponentView = extendComponentView;
  39783. exports.extendSeriesModel = extendSeriesModel;
  39784. exports.format = format$1;
  39785. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  39786. exports.getInstanceByDom = getInstanceByDom;
  39787. exports.getInstanceById = getInstanceById;
  39788. exports.getMap = getMap;
  39789. exports.graphic = graphic;
  39790. exports.helper = helper;
  39791. exports.init = init$1;
  39792. exports.innerDrawElementOnCanvas = brushSingle;
  39793. exports.matrix = matrix;
  39794. exports.number = number;
  39795. exports.parseGeoJSON = parseGeoJSON;
  39796. exports.parseGeoJson = parseGeoJSON;
  39797. exports.registerAction = registerAction;
  39798. exports.registerCoordinateSystem = registerCoordinateSystem;
  39799. exports.registerLayout = registerLayout;
  39800. exports.registerLoading = registerLoading;
  39801. exports.registerLocale = registerLocale;
  39802. exports.registerMap = registerMap;
  39803. exports.registerPostInit = registerPostInit;
  39804. exports.registerPostUpdate = registerPostUpdate;
  39805. exports.registerPreprocessor = registerPreprocessor;
  39806. exports.registerProcessor = registerProcessor;
  39807. exports.registerTheme = registerTheme;
  39808. exports.registerTransform = registerTransform;
  39809. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  39810. exports.registerVisual = registerVisual;
  39811. exports.setCanvasCreator = setCanvasCreator;
  39812. exports.setPlatformAPI = setPlatformAPI;
  39813. exports.throttle = throttle;
  39814. exports.time = time;
  39815. exports.use = use;
  39816. exports.util = util$1;
  39817. exports.vector = vector;
  39818. exports.version = version$1;
  39819. exports.zrUtil = util;
  39820. exports.zrender = zrender;
  39821. Object.defineProperty(exports, '__esModule', { value: true });
  39822. })));
  39823. //# sourceMappingURL=echarts.simple.js.map