echarts.simple.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. (function (global, factory) {
  20. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  21. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  22. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  23. }(this, (function (exports) { 'use strict';
  24. /*! *****************************************************************************
  25. Copyright (c) Microsoft Corporation.
  26. Permission to use, copy, modify, and/or distribute this software for any
  27. purpose with or without fee is hereby granted.
  28. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  30. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  31. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  33. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34. PERFORMANCE OF THIS SOFTWARE.
  35. ***************************************************************************** */
  36. /* global Reflect, Promise */
  37. var extendStatics = function(d, b) {
  38. extendStatics = Object.setPrototypeOf ||
  39. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  40. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  41. return extendStatics(d, b);
  42. };
  43. function __extends(d, b) {
  44. extendStatics(d, b);
  45. function __() { this.constructor = d; }
  46. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  47. }
  48. var __assign = function() {
  49. __assign = Object.assign || function __assign(t) {
  50. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51. s = arguments[i];
  52. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  53. }
  54. return t;
  55. };
  56. return __assign.apply(this, arguments);
  57. };
  58. function __spreadArrays() {
  59. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  60. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  61. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  62. r[k] = a[j];
  63. return r;
  64. }
  65. var Browser = (function () {
  66. function Browser() {
  67. this.firefox = false;
  68. this.ie = false;
  69. this.edge = false;
  70. this.newEdge = false;
  71. this.weChat = false;
  72. }
  73. return Browser;
  74. }());
  75. var Env = (function () {
  76. function Env() {
  77. this.browser = new Browser();
  78. this.node = false;
  79. this.wxa = false;
  80. this.worker = false;
  81. this.canvasSupported = false;
  82. this.svgSupported = false;
  83. this.touchEventsSupported = false;
  84. this.pointerEventsSupported = false;
  85. this.domSupported = false;
  86. }
  87. return Env;
  88. }());
  89. var env = new Env();
  90. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  91. env.wxa = true;
  92. env.canvasSupported = true;
  93. env.touchEventsSupported = true;
  94. }
  95. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  96. env.worker = true;
  97. env.canvasSupported = true;
  98. }
  99. else if (typeof navigator === 'undefined') {
  100. env.node = true;
  101. env.canvasSupported = true;
  102. env.svgSupported = true;
  103. }
  104. else {
  105. detect(navigator.userAgent, env);
  106. }
  107. function detect(ua, env) {
  108. var browser = env.browser;
  109. var firefox = ua.match(/Firefox\/([\d.]+)/);
  110. var ie = ua.match(/MSIE\s([\d.]+)/)
  111. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  112. var edge = ua.match(/Edge?\/([\d.]+)/);
  113. var weChat = (/micromessenger/i).test(ua);
  114. if (firefox) {
  115. browser.firefox = true;
  116. browser.version = firefox[1];
  117. }
  118. if (ie) {
  119. browser.ie = true;
  120. browser.version = ie[1];
  121. }
  122. if (edge) {
  123. browser.edge = true;
  124. browser.version = edge[1];
  125. browser.newEdge = +edge[1].split('.')[0] > 18;
  126. }
  127. if (weChat) {
  128. browser.weChat = true;
  129. }
  130. env.canvasSupported = !!document.createElement('canvas').getContext;
  131. env.svgSupported = typeof SVGRect !== 'undefined';
  132. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  133. env.pointerEventsSupported = 'onpointerdown' in window
  134. && (browser.edge || (browser.ie && +browser.version >= 11));
  135. env.domSupported = typeof document !== 'undefined';
  136. }
  137. var BUILTIN_OBJECT = {
  138. '[object Function]': true,
  139. '[object RegExp]': true,
  140. '[object Date]': true,
  141. '[object Error]': true,
  142. '[object CanvasGradient]': true,
  143. '[object CanvasPattern]': true,
  144. '[object Image]': true,
  145. '[object Canvas]': true
  146. };
  147. var TYPED_ARRAY = {
  148. '[object Int8Array]': true,
  149. '[object Uint8Array]': true,
  150. '[object Uint8ClampedArray]': true,
  151. '[object Int16Array]': true,
  152. '[object Uint16Array]': true,
  153. '[object Int32Array]': true,
  154. '[object Uint32Array]': true,
  155. '[object Float32Array]': true,
  156. '[object Float64Array]': true
  157. };
  158. var objToString = Object.prototype.toString;
  159. var arrayProto = Array.prototype;
  160. var nativeForEach = arrayProto.forEach;
  161. var nativeFilter = arrayProto.filter;
  162. var nativeSlice = arrayProto.slice;
  163. var nativeMap = arrayProto.map;
  164. var ctorFunction = function () { }.constructor;
  165. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  166. var methods = {};
  167. function $override(name, fn) {
  168. methods[name] = fn;
  169. }
  170. var idStart = 0x0907;
  171. function guid() {
  172. return idStart++;
  173. }
  174. function logError() {
  175. var args = [];
  176. for (var _i = 0; _i < arguments.length; _i++) {
  177. args[_i] = arguments[_i];
  178. }
  179. if (typeof console !== 'undefined') {
  180. console.error.apply(console, args);
  181. }
  182. }
  183. function clone(source) {
  184. if (source == null || typeof source !== 'object') {
  185. return source;
  186. }
  187. var result = source;
  188. var typeStr = objToString.call(source);
  189. if (typeStr === '[object Array]') {
  190. if (!isPrimitive(source)) {
  191. result = [];
  192. for (var i = 0, len = source.length; i < len; i++) {
  193. result[i] = clone(source[i]);
  194. }
  195. }
  196. }
  197. else if (TYPED_ARRAY[typeStr]) {
  198. if (!isPrimitive(source)) {
  199. var Ctor = source.constructor;
  200. if (Ctor.from) {
  201. result = Ctor.from(source);
  202. }
  203. else {
  204. result = new Ctor(source.length);
  205. for (var i = 0, len = source.length; i < len; i++) {
  206. result[i] = clone(source[i]);
  207. }
  208. }
  209. }
  210. }
  211. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  212. result = {};
  213. for (var key in source) {
  214. if (source.hasOwnProperty(key)) {
  215. result[key] = clone(source[key]);
  216. }
  217. }
  218. }
  219. return result;
  220. }
  221. function merge(target, source, overwrite) {
  222. if (!isObject(source) || !isObject(target)) {
  223. return overwrite ? clone(source) : target;
  224. }
  225. for (var key in source) {
  226. if (source.hasOwnProperty(key)) {
  227. var targetProp = target[key];
  228. var sourceProp = source[key];
  229. if (isObject(sourceProp)
  230. && isObject(targetProp)
  231. && !isArray(sourceProp)
  232. && !isArray(targetProp)
  233. && !isDom(sourceProp)
  234. && !isDom(targetProp)
  235. && !isBuiltInObject(sourceProp)
  236. && !isBuiltInObject(targetProp)
  237. && !isPrimitive(sourceProp)
  238. && !isPrimitive(targetProp)) {
  239. merge(targetProp, sourceProp, overwrite);
  240. }
  241. else if (overwrite || !(key in target)) {
  242. target[key] = clone(source[key]);
  243. }
  244. }
  245. }
  246. return target;
  247. }
  248. function mergeAll(targetAndSources, overwrite) {
  249. var result = targetAndSources[0];
  250. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  251. result = merge(result, targetAndSources[i], overwrite);
  252. }
  253. return result;
  254. }
  255. function extend(target, source) {
  256. if (Object.assign) {
  257. Object.assign(target, source);
  258. }
  259. else {
  260. for (var key in source) {
  261. if (source.hasOwnProperty(key)) {
  262. target[key] = source[key];
  263. }
  264. }
  265. }
  266. return target;
  267. }
  268. function defaults(target, source, overlay) {
  269. var keysArr = keys(source);
  270. for (var i = 0; i < keysArr.length; i++) {
  271. var key = keysArr[i];
  272. if ((overlay ? source[key] != null : target[key] == null)) {
  273. target[key] = source[key];
  274. }
  275. }
  276. return target;
  277. }
  278. var createCanvas = function () {
  279. return methods.createCanvas();
  280. };
  281. methods.createCanvas = function () {
  282. return document.createElement('canvas');
  283. };
  284. function indexOf(array, value) {
  285. if (array) {
  286. if (array.indexOf) {
  287. return array.indexOf(value);
  288. }
  289. for (var i = 0, len = array.length; i < len; i++) {
  290. if (array[i] === value) {
  291. return i;
  292. }
  293. }
  294. }
  295. return -1;
  296. }
  297. function inherits(clazz, baseClazz) {
  298. var clazzPrototype = clazz.prototype;
  299. function F() { }
  300. F.prototype = baseClazz.prototype;
  301. clazz.prototype = new F();
  302. for (var prop in clazzPrototype) {
  303. if (clazzPrototype.hasOwnProperty(prop)) {
  304. clazz.prototype[prop] = clazzPrototype[prop];
  305. }
  306. }
  307. clazz.prototype.constructor = clazz;
  308. clazz.superClass = baseClazz;
  309. }
  310. function mixin(target, source, override) {
  311. target = 'prototype' in target ? target.prototype : target;
  312. source = 'prototype' in source ? source.prototype : source;
  313. if (Object.getOwnPropertyNames) {
  314. var keyList = Object.getOwnPropertyNames(source);
  315. for (var i = 0; i < keyList.length; i++) {
  316. var key = keyList[i];
  317. if (key !== 'constructor') {
  318. if ((override ? source[key] != null : target[key] == null)) {
  319. target[key] = source[key];
  320. }
  321. }
  322. }
  323. }
  324. else {
  325. defaults(target, source, override);
  326. }
  327. }
  328. function isArrayLike(data) {
  329. if (!data) {
  330. return false;
  331. }
  332. if (typeof data === 'string') {
  333. return false;
  334. }
  335. return typeof data.length === 'number';
  336. }
  337. function each(arr, cb, context) {
  338. if (!(arr && cb)) {
  339. return;
  340. }
  341. if (arr.forEach && arr.forEach === nativeForEach) {
  342. arr.forEach(cb, context);
  343. }
  344. else if (arr.length === +arr.length) {
  345. for (var i = 0, len = arr.length; i < len; i++) {
  346. cb.call(context, arr[i], i, arr);
  347. }
  348. }
  349. else {
  350. for (var key in arr) {
  351. if (arr.hasOwnProperty(key)) {
  352. cb.call(context, arr[key], key, arr);
  353. }
  354. }
  355. }
  356. }
  357. function map(arr, cb, context) {
  358. if (!arr) {
  359. return [];
  360. }
  361. if (!cb) {
  362. return slice(arr);
  363. }
  364. if (arr.map && arr.map === nativeMap) {
  365. return arr.map(cb, context);
  366. }
  367. else {
  368. var result = [];
  369. for (var i = 0, len = arr.length; i < len; i++) {
  370. result.push(cb.call(context, arr[i], i, arr));
  371. }
  372. return result;
  373. }
  374. }
  375. function reduce(arr, cb, memo, context) {
  376. if (!(arr && cb)) {
  377. return;
  378. }
  379. for (var i = 0, len = arr.length; i < len; i++) {
  380. memo = cb.call(context, memo, arr[i], i, arr);
  381. }
  382. return memo;
  383. }
  384. function filter(arr, cb, context) {
  385. if (!arr) {
  386. return [];
  387. }
  388. if (!cb) {
  389. return slice(arr);
  390. }
  391. if (arr.filter && arr.filter === nativeFilter) {
  392. return arr.filter(cb, context);
  393. }
  394. else {
  395. var result = [];
  396. for (var i = 0, len = arr.length; i < len; i++) {
  397. if (cb.call(context, arr[i], i, arr)) {
  398. result.push(arr[i]);
  399. }
  400. }
  401. return result;
  402. }
  403. }
  404. function find(arr, cb, context) {
  405. if (!(arr && cb)) {
  406. return;
  407. }
  408. for (var i = 0, len = arr.length; i < len; i++) {
  409. if (cb.call(context, arr[i], i, arr)) {
  410. return arr[i];
  411. }
  412. }
  413. }
  414. function keys(obj) {
  415. if (!obj) {
  416. return [];
  417. }
  418. if (Object.keys) {
  419. return Object.keys(obj);
  420. }
  421. var keyList = [];
  422. for (var key in obj) {
  423. if (obj.hasOwnProperty(key)) {
  424. keyList.push(key);
  425. }
  426. }
  427. return keyList;
  428. }
  429. function bindPolyfill(func, context) {
  430. var args = [];
  431. for (var _i = 2; _i < arguments.length; _i++) {
  432. args[_i - 2] = arguments[_i];
  433. }
  434. return function () {
  435. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  436. };
  437. }
  438. var bind = (protoFunction && isFunction(protoFunction.bind))
  439. ? protoFunction.call.bind(protoFunction.bind)
  440. : bindPolyfill;
  441. function curry(func) {
  442. var args = [];
  443. for (var _i = 1; _i < arguments.length; _i++) {
  444. args[_i - 1] = arguments[_i];
  445. }
  446. return function () {
  447. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  448. };
  449. }
  450. function isArray(value) {
  451. if (Array.isArray) {
  452. return Array.isArray(value);
  453. }
  454. return objToString.call(value) === '[object Array]';
  455. }
  456. function isFunction(value) {
  457. return typeof value === 'function';
  458. }
  459. function isString(value) {
  460. return typeof value === 'string';
  461. }
  462. function isStringSafe(value) {
  463. return objToString.call(value) === '[object String]';
  464. }
  465. function isNumber(value) {
  466. return typeof value === 'number';
  467. }
  468. function isObject(value) {
  469. var type = typeof value;
  470. return type === 'function' || (!!value && type === 'object');
  471. }
  472. function isBuiltInObject(value) {
  473. return !!BUILTIN_OBJECT[objToString.call(value)];
  474. }
  475. function isTypedArray(value) {
  476. return !!TYPED_ARRAY[objToString.call(value)];
  477. }
  478. function isDom(value) {
  479. return typeof value === 'object'
  480. && typeof value.nodeType === 'number'
  481. && typeof value.ownerDocument === 'object';
  482. }
  483. function isGradientObject(value) {
  484. return value.colorStops != null;
  485. }
  486. function isPatternObject(value) {
  487. return value.image != null;
  488. }
  489. function isRegExp(value) {
  490. return objToString.call(value) === '[object RegExp]';
  491. }
  492. function eqNaN(value) {
  493. return value !== value;
  494. }
  495. function retrieve() {
  496. var args = [];
  497. for (var _i = 0; _i < arguments.length; _i++) {
  498. args[_i] = arguments[_i];
  499. }
  500. for (var i = 0, len = args.length; i < len; i++) {
  501. if (args[i] != null) {
  502. return args[i];
  503. }
  504. }
  505. }
  506. function retrieve2(value0, value1) {
  507. return value0 != null
  508. ? value0
  509. : value1;
  510. }
  511. function retrieve3(value0, value1, value2) {
  512. return value0 != null
  513. ? value0
  514. : value1 != null
  515. ? value1
  516. : value2;
  517. }
  518. function slice(arr) {
  519. var args = [];
  520. for (var _i = 1; _i < arguments.length; _i++) {
  521. args[_i - 1] = arguments[_i];
  522. }
  523. return nativeSlice.apply(arr, args);
  524. }
  525. function normalizeCssArray(val) {
  526. if (typeof (val) === 'number') {
  527. return [val, val, val, val];
  528. }
  529. var len = val.length;
  530. if (len === 2) {
  531. return [val[0], val[1], val[0], val[1]];
  532. }
  533. else if (len === 3) {
  534. return [val[0], val[1], val[2], val[1]];
  535. }
  536. return val;
  537. }
  538. function assert(condition, message) {
  539. if (!condition) {
  540. throw new Error(message);
  541. }
  542. }
  543. function trim(str) {
  544. if (str == null) {
  545. return null;
  546. }
  547. else if (typeof str.trim === 'function') {
  548. return str.trim();
  549. }
  550. else {
  551. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  552. }
  553. }
  554. var primitiveKey = '__ec_primitive__';
  555. function setAsPrimitive(obj) {
  556. obj[primitiveKey] = true;
  557. }
  558. function isPrimitive(obj) {
  559. return obj[primitiveKey];
  560. }
  561. var HashMap = (function () {
  562. function HashMap(obj) {
  563. this.data = {};
  564. var isArr = isArray(obj);
  565. this.data = {};
  566. var thisMap = this;
  567. (obj instanceof HashMap)
  568. ? obj.each(visit)
  569. : (obj && each(obj, visit));
  570. function visit(value, key) {
  571. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  572. }
  573. }
  574. HashMap.prototype.get = function (key) {
  575. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  576. };
  577. HashMap.prototype.set = function (key, value) {
  578. return (this.data[key] = value);
  579. };
  580. HashMap.prototype.each = function (cb, context) {
  581. for (var key in this.data) {
  582. if (this.data.hasOwnProperty(key)) {
  583. cb.call(context, this.data[key], key);
  584. }
  585. }
  586. };
  587. HashMap.prototype.keys = function () {
  588. return keys(this.data);
  589. };
  590. HashMap.prototype.removeKey = function (key) {
  591. delete this.data[key];
  592. };
  593. return HashMap;
  594. }());
  595. function createHashMap(obj) {
  596. return new HashMap(obj);
  597. }
  598. function concatArray(a, b) {
  599. var newArray = new a.constructor(a.length + b.length);
  600. for (var i = 0; i < a.length; i++) {
  601. newArray[i] = a[i];
  602. }
  603. var offset = a.length;
  604. for (var i = 0; i < b.length; i++) {
  605. newArray[i + offset] = b[i];
  606. }
  607. return newArray;
  608. }
  609. function createObject(proto, properties) {
  610. var obj;
  611. if (Object.create) {
  612. obj = Object.create(proto);
  613. }
  614. else {
  615. var StyleCtor = function () { };
  616. StyleCtor.prototype = proto;
  617. obj = new StyleCtor();
  618. }
  619. if (properties) {
  620. extend(obj, properties);
  621. }
  622. return obj;
  623. }
  624. function hasOwn(own, prop) {
  625. return own.hasOwnProperty(prop);
  626. }
  627. function noop() { }
  628. var util = /*#__PURE__*/Object.freeze({
  629. __proto__: null,
  630. $override: $override,
  631. guid: guid,
  632. logError: logError,
  633. clone: clone,
  634. merge: merge,
  635. mergeAll: mergeAll,
  636. extend: extend,
  637. defaults: defaults,
  638. createCanvas: createCanvas,
  639. indexOf: indexOf,
  640. inherits: inherits,
  641. mixin: mixin,
  642. isArrayLike: isArrayLike,
  643. each: each,
  644. map: map,
  645. reduce: reduce,
  646. filter: filter,
  647. find: find,
  648. keys: keys,
  649. bind: bind,
  650. curry: curry,
  651. isArray: isArray,
  652. isFunction: isFunction,
  653. isString: isString,
  654. isStringSafe: isStringSafe,
  655. isNumber: isNumber,
  656. isObject: isObject,
  657. isBuiltInObject: isBuiltInObject,
  658. isTypedArray: isTypedArray,
  659. isDom: isDom,
  660. isGradientObject: isGradientObject,
  661. isPatternObject: isPatternObject,
  662. isRegExp: isRegExp,
  663. eqNaN: eqNaN,
  664. retrieve: retrieve,
  665. retrieve2: retrieve2,
  666. retrieve3: retrieve3,
  667. slice: slice,
  668. normalizeCssArray: normalizeCssArray,
  669. assert: assert,
  670. trim: trim,
  671. setAsPrimitive: setAsPrimitive,
  672. isPrimitive: isPrimitive,
  673. HashMap: HashMap,
  674. createHashMap: createHashMap,
  675. concatArray: concatArray,
  676. createObject: createObject,
  677. hasOwn: hasOwn,
  678. noop: noop
  679. });
  680. function create(x, y) {
  681. if (x == null) {
  682. x = 0;
  683. }
  684. if (y == null) {
  685. y = 0;
  686. }
  687. return [x, y];
  688. }
  689. function copy(out, v) {
  690. out[0] = v[0];
  691. out[1] = v[1];
  692. return out;
  693. }
  694. function clone$1(v) {
  695. return [v[0], v[1]];
  696. }
  697. function set(out, a, b) {
  698. out[0] = a;
  699. out[1] = b;
  700. return out;
  701. }
  702. function add(out, v1, v2) {
  703. out[0] = v1[0] + v2[0];
  704. out[1] = v1[1] + v2[1];
  705. return out;
  706. }
  707. function scaleAndAdd(out, v1, v2, a) {
  708. out[0] = v1[0] + v2[0] * a;
  709. out[1] = v1[1] + v2[1] * a;
  710. return out;
  711. }
  712. function sub(out, v1, v2) {
  713. out[0] = v1[0] - v2[0];
  714. out[1] = v1[1] - v2[1];
  715. return out;
  716. }
  717. function len(v) {
  718. return Math.sqrt(lenSquare(v));
  719. }
  720. var length = len;
  721. function lenSquare(v) {
  722. return v[0] * v[0] + v[1] * v[1];
  723. }
  724. var lengthSquare = lenSquare;
  725. function mul(out, v1, v2) {
  726. out[0] = v1[0] * v2[0];
  727. out[1] = v1[1] * v2[1];
  728. return out;
  729. }
  730. function div(out, v1, v2) {
  731. out[0] = v1[0] / v2[0];
  732. out[1] = v1[1] / v2[1];
  733. return out;
  734. }
  735. function dot(v1, v2) {
  736. return v1[0] * v2[0] + v1[1] * v2[1];
  737. }
  738. function scale(out, v, s) {
  739. out[0] = v[0] * s;
  740. out[1] = v[1] * s;
  741. return out;
  742. }
  743. function normalize(out, v) {
  744. var d = len(v);
  745. if (d === 0) {
  746. out[0] = 0;
  747. out[1] = 0;
  748. }
  749. else {
  750. out[0] = v[0] / d;
  751. out[1] = v[1] / d;
  752. }
  753. return out;
  754. }
  755. function distance(v1, v2) {
  756. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  757. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  758. }
  759. var dist = distance;
  760. function distanceSquare(v1, v2) {
  761. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  762. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  763. }
  764. var distSquare = distanceSquare;
  765. function negate(out, v) {
  766. out[0] = -v[0];
  767. out[1] = -v[1];
  768. return out;
  769. }
  770. function lerp(out, v1, v2, t) {
  771. out[0] = v1[0] + t * (v2[0] - v1[0]);
  772. out[1] = v1[1] + t * (v2[1] - v1[1]);
  773. return out;
  774. }
  775. function applyTransform(out, v, m) {
  776. var x = v[0];
  777. var y = v[1];
  778. out[0] = m[0] * x + m[2] * y + m[4];
  779. out[1] = m[1] * x + m[3] * y + m[5];
  780. return out;
  781. }
  782. function min(out, v1, v2) {
  783. out[0] = Math.min(v1[0], v2[0]);
  784. out[1] = Math.min(v1[1], v2[1]);
  785. return out;
  786. }
  787. function max(out, v1, v2) {
  788. out[0] = Math.max(v1[0], v2[0]);
  789. out[1] = Math.max(v1[1], v2[1]);
  790. return out;
  791. }
  792. var vector = /*#__PURE__*/Object.freeze({
  793. __proto__: null,
  794. create: create,
  795. copy: copy,
  796. clone: clone$1,
  797. set: set,
  798. add: add,
  799. scaleAndAdd: scaleAndAdd,
  800. sub: sub,
  801. len: len,
  802. length: length,
  803. lenSquare: lenSquare,
  804. lengthSquare: lengthSquare,
  805. mul: mul,
  806. div: div,
  807. dot: dot,
  808. scale: scale,
  809. normalize: normalize,
  810. distance: distance,
  811. dist: dist,
  812. distanceSquare: distanceSquare,
  813. distSquare: distSquare,
  814. negate: negate,
  815. lerp: lerp,
  816. applyTransform: applyTransform,
  817. min: min,
  818. max: max
  819. });
  820. var Param = (function () {
  821. function Param(target, e) {
  822. this.target = target;
  823. this.topTarget = e && e.topTarget;
  824. }
  825. return Param;
  826. }());
  827. var Draggable = (function () {
  828. function Draggable(handler) {
  829. this.handler = handler;
  830. handler.on('mousedown', this._dragStart, this);
  831. handler.on('mousemove', this._drag, this);
  832. handler.on('mouseup', this._dragEnd, this);
  833. }
  834. Draggable.prototype._dragStart = function (e) {
  835. var draggingTarget = e.target;
  836. while (draggingTarget && !draggingTarget.draggable) {
  837. draggingTarget = draggingTarget.parent;
  838. }
  839. if (draggingTarget) {
  840. this._draggingTarget = draggingTarget;
  841. draggingTarget.dragging = true;
  842. this._x = e.offsetX;
  843. this._y = e.offsetY;
  844. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  845. }
  846. };
  847. Draggable.prototype._drag = function (e) {
  848. var draggingTarget = this._draggingTarget;
  849. if (draggingTarget) {
  850. var x = e.offsetX;
  851. var y = e.offsetY;
  852. var dx = x - this._x;
  853. var dy = y - this._y;
  854. this._x = x;
  855. this._y = y;
  856. draggingTarget.drift(dx, dy, e);
  857. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  858. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  859. var lastDropTarget = this._dropTarget;
  860. this._dropTarget = dropTarget;
  861. if (draggingTarget !== dropTarget) {
  862. if (lastDropTarget && dropTarget !== lastDropTarget) {
  863. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  864. }
  865. if (dropTarget && dropTarget !== lastDropTarget) {
  866. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  867. }
  868. }
  869. }
  870. };
  871. Draggable.prototype._dragEnd = function (e) {
  872. var draggingTarget = this._draggingTarget;
  873. if (draggingTarget) {
  874. draggingTarget.dragging = false;
  875. }
  876. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  877. if (this._dropTarget) {
  878. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  879. }
  880. this._draggingTarget = null;
  881. this._dropTarget = null;
  882. };
  883. return Draggable;
  884. }());
  885. var Eventful = (function () {
  886. function Eventful(eventProcessors) {
  887. if (eventProcessors) {
  888. this._$eventProcessor = eventProcessors;
  889. }
  890. }
  891. Eventful.prototype.on = function (event, query, handler, context) {
  892. if (!this._$handlers) {
  893. this._$handlers = {};
  894. }
  895. var _h = this._$handlers;
  896. if (typeof query === 'function') {
  897. context = handler;
  898. handler = query;
  899. query = null;
  900. }
  901. if (!handler || !event) {
  902. return this;
  903. }
  904. var eventProcessor = this._$eventProcessor;
  905. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  906. query = eventProcessor.normalizeQuery(query);
  907. }
  908. if (!_h[event]) {
  909. _h[event] = [];
  910. }
  911. for (var i = 0; i < _h[event].length; i++) {
  912. if (_h[event][i].h === handler) {
  913. return this;
  914. }
  915. }
  916. var wrap = {
  917. h: handler,
  918. query: query,
  919. ctx: (context || this),
  920. callAtLast: handler.zrEventfulCallAtLast
  921. };
  922. var lastIndex = _h[event].length - 1;
  923. var lastWrap = _h[event][lastIndex];
  924. (lastWrap && lastWrap.callAtLast)
  925. ? _h[event].splice(lastIndex, 0, wrap)
  926. : _h[event].push(wrap);
  927. return this;
  928. };
  929. Eventful.prototype.isSilent = function (eventName) {
  930. var _h = this._$handlers;
  931. return !_h || !_h[eventName] || !_h[eventName].length;
  932. };
  933. Eventful.prototype.off = function (eventType, handler) {
  934. var _h = this._$handlers;
  935. if (!_h) {
  936. return this;
  937. }
  938. if (!eventType) {
  939. this._$handlers = {};
  940. return this;
  941. }
  942. if (handler) {
  943. if (_h[eventType]) {
  944. var newList = [];
  945. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  946. if (_h[eventType][i].h !== handler) {
  947. newList.push(_h[eventType][i]);
  948. }
  949. }
  950. _h[eventType] = newList;
  951. }
  952. if (_h[eventType] && _h[eventType].length === 0) {
  953. delete _h[eventType];
  954. }
  955. }
  956. else {
  957. delete _h[eventType];
  958. }
  959. return this;
  960. };
  961. Eventful.prototype.trigger = function (eventType) {
  962. var args = [];
  963. for (var _i = 1; _i < arguments.length; _i++) {
  964. args[_i - 1] = arguments[_i];
  965. }
  966. if (!this._$handlers) {
  967. return this;
  968. }
  969. var _h = this._$handlers[eventType];
  970. var eventProcessor = this._$eventProcessor;
  971. if (_h) {
  972. var argLen = args.length;
  973. var len = _h.length;
  974. for (var i = 0; i < len; i++) {
  975. var hItem = _h[i];
  976. if (eventProcessor
  977. && eventProcessor.filter
  978. && hItem.query != null
  979. && !eventProcessor.filter(eventType, hItem.query)) {
  980. continue;
  981. }
  982. switch (argLen) {
  983. case 0:
  984. hItem.h.call(hItem.ctx);
  985. break;
  986. case 1:
  987. hItem.h.call(hItem.ctx, args[0]);
  988. break;
  989. case 2:
  990. hItem.h.call(hItem.ctx, args[0], args[1]);
  991. break;
  992. default:
  993. hItem.h.apply(hItem.ctx, args);
  994. break;
  995. }
  996. }
  997. }
  998. eventProcessor && eventProcessor.afterTrigger
  999. && eventProcessor.afterTrigger(eventType);
  1000. return this;
  1001. };
  1002. Eventful.prototype.triggerWithContext = function (type) {
  1003. if (!this._$handlers) {
  1004. return this;
  1005. }
  1006. var _h = this._$handlers[type];
  1007. var eventProcessor = this._$eventProcessor;
  1008. if (_h) {
  1009. var args = arguments;
  1010. var argLen = args.length;
  1011. var ctx = args[argLen - 1];
  1012. var len = _h.length;
  1013. for (var i = 0; i < len; i++) {
  1014. var hItem = _h[i];
  1015. if (eventProcessor
  1016. && eventProcessor.filter
  1017. && hItem.query != null
  1018. && !eventProcessor.filter(type, hItem.query)) {
  1019. continue;
  1020. }
  1021. switch (argLen) {
  1022. case 0:
  1023. hItem.h.call(ctx);
  1024. break;
  1025. case 1:
  1026. hItem.h.call(ctx, args[0]);
  1027. break;
  1028. case 2:
  1029. hItem.h.call(ctx, args[0], args[1]);
  1030. break;
  1031. default:
  1032. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. eventProcessor && eventProcessor.afterTrigger
  1038. && eventProcessor.afterTrigger(type);
  1039. return this;
  1040. };
  1041. return Eventful;
  1042. }());
  1043. var LN2 = Math.log(2);
  1044. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1045. var cacheKey = rowMask + '-' + colMask;
  1046. var fullRank = rows.length;
  1047. if (detCache.hasOwnProperty(cacheKey)) {
  1048. return detCache[cacheKey];
  1049. }
  1050. if (rank === 1) {
  1051. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1052. return rows[rowStart][colStart];
  1053. }
  1054. var subRowMask = rowMask | (1 << rowStart);
  1055. var subRowStart = rowStart + 1;
  1056. while (rowMask & (1 << subRowStart)) {
  1057. subRowStart++;
  1058. }
  1059. var sum = 0;
  1060. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1061. var colTag = 1 << j;
  1062. if (!(colTag & colMask)) {
  1063. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1064. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1065. colLocalIdx++;
  1066. }
  1067. }
  1068. detCache[cacheKey] = sum;
  1069. return sum;
  1070. }
  1071. function buildTransformer(src, dest) {
  1072. var mA = [
  1073. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1074. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1075. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1076. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1077. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1078. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1079. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1080. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1081. ];
  1082. var detCache = {};
  1083. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1084. if (det === 0) {
  1085. return;
  1086. }
  1087. var vh = [];
  1088. for (var i = 0; i < 8; i++) {
  1089. for (var j = 0; j < 8; j++) {
  1090. vh[j] == null && (vh[j] = 0);
  1091. vh[j] += ((i + j) % 2 ? -1 : 1)
  1092. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1093. / det * dest[i];
  1094. }
  1095. }
  1096. return function (out, srcPointX, srcPointY) {
  1097. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1098. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1099. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1100. };
  1101. }
  1102. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1103. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1104. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1105. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1106. var markers = prepareCoordMarkers(el, saved);
  1107. var transformer = preparePointerTransformer(markers, saved, inverse);
  1108. if (transformer) {
  1109. transformer(out, inX, inY);
  1110. return true;
  1111. }
  1112. }
  1113. return false;
  1114. }
  1115. function prepareCoordMarkers(el, saved) {
  1116. var markers = saved.markers;
  1117. if (markers) {
  1118. return markers;
  1119. }
  1120. markers = saved.markers = [];
  1121. var propLR = ['left', 'right'];
  1122. var propTB = ['top', 'bottom'];
  1123. for (var i = 0; i < 4; i++) {
  1124. var marker = document.createElement('div');
  1125. var stl = marker.style;
  1126. var idxLR = i % 2;
  1127. var idxTB = (i >> 1) % 2;
  1128. stl.cssText = [
  1129. 'position: absolute',
  1130. 'visibility: hidden',
  1131. 'padding: 0',
  1132. 'margin: 0',
  1133. 'border-width: 0',
  1134. 'user-select: none',
  1135. 'width:0',
  1136. 'height:0',
  1137. propLR[idxLR] + ':0',
  1138. propTB[idxTB] + ':0',
  1139. propLR[1 - idxLR] + ':auto',
  1140. propTB[1 - idxTB] + ':auto',
  1141. ''
  1142. ].join('!important;');
  1143. el.appendChild(marker);
  1144. markers.push(marker);
  1145. }
  1146. return markers;
  1147. }
  1148. function preparePointerTransformer(markers, saved, inverse) {
  1149. var transformerName = inverse ? 'invTrans' : 'trans';
  1150. var transformer = saved[transformerName];
  1151. var oldSrcCoords = saved.srcCoords;
  1152. var srcCoords = [];
  1153. var destCoords = [];
  1154. var oldCoordTheSame = true;
  1155. for (var i = 0; i < 4; i++) {
  1156. var rect = markers[i].getBoundingClientRect();
  1157. var ii = 2 * i;
  1158. var x = rect.left;
  1159. var y = rect.top;
  1160. srcCoords.push(x, y);
  1161. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1162. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1163. }
  1164. return (oldCoordTheSame && transformer)
  1165. ? transformer
  1166. : (saved.srcCoords = srcCoords,
  1167. saved[transformerName] = inverse
  1168. ? buildTransformer(destCoords, srcCoords)
  1169. : buildTransformer(srcCoords, destCoords));
  1170. }
  1171. function isCanvasEl(el) {
  1172. return el.nodeName.toUpperCase() === 'CANVAS';
  1173. }
  1174. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1175. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1176. var _calcOut = [];
  1177. function clientToLocal(el, e, out, calculate) {
  1178. out = out || {};
  1179. if (calculate || !env.canvasSupported) {
  1180. calculateZrXY(el, e, out);
  1181. }
  1182. else if (env.browser.firefox
  1183. && e.layerX != null
  1184. && e.layerX !== e.offsetX) {
  1185. out.zrX = e.layerX;
  1186. out.zrY = e.layerY;
  1187. }
  1188. else if (e.offsetX != null) {
  1189. out.zrX = e.offsetX;
  1190. out.zrY = e.offsetY;
  1191. }
  1192. else {
  1193. calculateZrXY(el, e, out);
  1194. }
  1195. return out;
  1196. }
  1197. function calculateZrXY(el, e, out) {
  1198. if (env.domSupported && el.getBoundingClientRect) {
  1199. var ex = e.clientX;
  1200. var ey = e.clientY;
  1201. if (isCanvasEl(el)) {
  1202. var box = el.getBoundingClientRect();
  1203. out.zrX = ex - box.left;
  1204. out.zrY = ey - box.top;
  1205. return;
  1206. }
  1207. else {
  1208. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1209. out.zrX = _calcOut[0];
  1210. out.zrY = _calcOut[1];
  1211. return;
  1212. }
  1213. }
  1214. }
  1215. out.zrX = out.zrY = 0;
  1216. }
  1217. function getNativeEvent(e) {
  1218. return e
  1219. || window.event;
  1220. }
  1221. function normalizeEvent(el, e, calculate) {
  1222. e = getNativeEvent(e);
  1223. if (e.zrX != null) {
  1224. return e;
  1225. }
  1226. var eventType = e.type;
  1227. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1228. if (!isTouch) {
  1229. clientToLocal(el, e, e, calculate);
  1230. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1231. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1232. }
  1233. else {
  1234. var touch = eventType !== 'touchend'
  1235. ? e.targetTouches[0]
  1236. : e.changedTouches[0];
  1237. touch && clientToLocal(el, touch, e, calculate);
  1238. }
  1239. var button = e.button;
  1240. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1241. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1242. }
  1243. return e;
  1244. }
  1245. function getWheelDeltaMayPolyfill(e) {
  1246. var rawWheelDelta = e.wheelDelta;
  1247. if (rawWheelDelta) {
  1248. return rawWheelDelta;
  1249. }
  1250. var deltaX = e.deltaX;
  1251. var deltaY = e.deltaY;
  1252. if (deltaX == null || deltaY == null) {
  1253. return rawWheelDelta;
  1254. }
  1255. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1256. var sign = deltaY > 0 ? -1
  1257. : deltaY < 0 ? 1
  1258. : deltaX > 0 ? -1
  1259. : 1;
  1260. return 3 * delta * sign;
  1261. }
  1262. function addEventListener(el, name, handler, opt) {
  1263. if (isDomLevel2) {
  1264. el.addEventListener(name, handler, opt);
  1265. }
  1266. else {
  1267. el.attachEvent('on' + name, handler);
  1268. }
  1269. }
  1270. function removeEventListener(el, name, handler, opt) {
  1271. if (isDomLevel2) {
  1272. el.removeEventListener(name, handler, opt);
  1273. }
  1274. else {
  1275. el.detachEvent('on' + name, handler);
  1276. }
  1277. }
  1278. var stop = isDomLevel2
  1279. ? function (e) {
  1280. e.preventDefault();
  1281. e.stopPropagation();
  1282. e.cancelBubble = true;
  1283. }
  1284. : function (e) {
  1285. e.returnValue = false;
  1286. e.cancelBubble = true;
  1287. };
  1288. var GestureMgr = (function () {
  1289. function GestureMgr() {
  1290. this._track = [];
  1291. }
  1292. GestureMgr.prototype.recognize = function (event, target, root) {
  1293. this._doTrack(event, target, root);
  1294. return this._recognize(event);
  1295. };
  1296. GestureMgr.prototype.clear = function () {
  1297. this._track.length = 0;
  1298. return this;
  1299. };
  1300. GestureMgr.prototype._doTrack = function (event, target, root) {
  1301. var touches = event.touches;
  1302. if (!touches) {
  1303. return;
  1304. }
  1305. var trackItem = {
  1306. points: [],
  1307. touches: [],
  1308. target: target,
  1309. event: event
  1310. };
  1311. for (var i = 0, len = touches.length; i < len; i++) {
  1312. var touch = touches[i];
  1313. var pos = clientToLocal(root, touch, {});
  1314. trackItem.points.push([pos.zrX, pos.zrY]);
  1315. trackItem.touches.push(touch);
  1316. }
  1317. this._track.push(trackItem);
  1318. };
  1319. GestureMgr.prototype._recognize = function (event) {
  1320. for (var eventName in recognizers) {
  1321. if (recognizers.hasOwnProperty(eventName)) {
  1322. var gestureInfo = recognizers[eventName](this._track, event);
  1323. if (gestureInfo) {
  1324. return gestureInfo;
  1325. }
  1326. }
  1327. }
  1328. };
  1329. return GestureMgr;
  1330. }());
  1331. function dist$1(pointPair) {
  1332. var dx = pointPair[1][0] - pointPair[0][0];
  1333. var dy = pointPair[1][1] - pointPair[0][1];
  1334. return Math.sqrt(dx * dx + dy * dy);
  1335. }
  1336. function center(pointPair) {
  1337. return [
  1338. (pointPair[0][0] + pointPair[1][0]) / 2,
  1339. (pointPair[0][1] + pointPair[1][1]) / 2
  1340. ];
  1341. }
  1342. var recognizers = {
  1343. pinch: function (tracks, event) {
  1344. var trackLen = tracks.length;
  1345. if (!trackLen) {
  1346. return;
  1347. }
  1348. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1349. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1350. if (pinchPre
  1351. && pinchPre.length > 1
  1352. && pinchEnd
  1353. && pinchEnd.length > 1) {
  1354. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1355. !isFinite(pinchScale) && (pinchScale = 1);
  1356. event.pinchScale = pinchScale;
  1357. var pinchCenter = center(pinchEnd);
  1358. event.pinchX = pinchCenter[0];
  1359. event.pinchY = pinchCenter[1];
  1360. return {
  1361. type: 'pinch',
  1362. target: tracks[0].target,
  1363. event: event
  1364. };
  1365. }
  1366. }
  1367. };
  1368. var SILENT = 'silent';
  1369. function makeEventPacket(eveType, targetInfo, event) {
  1370. return {
  1371. type: eveType,
  1372. event: event,
  1373. target: targetInfo.target,
  1374. topTarget: targetInfo.topTarget,
  1375. cancelBubble: false,
  1376. offsetX: event.zrX,
  1377. offsetY: event.zrY,
  1378. gestureEvent: event.gestureEvent,
  1379. pinchX: event.pinchX,
  1380. pinchY: event.pinchY,
  1381. pinchScale: event.pinchScale,
  1382. wheelDelta: event.zrDelta,
  1383. zrByTouch: event.zrByTouch,
  1384. which: event.which,
  1385. stop: stopEvent
  1386. };
  1387. }
  1388. function stopEvent() {
  1389. stop(this.event);
  1390. }
  1391. var EmptyProxy = (function (_super) {
  1392. __extends(EmptyProxy, _super);
  1393. function EmptyProxy() {
  1394. var _this = _super !== null && _super.apply(this, arguments) || this;
  1395. _this.handler = null;
  1396. return _this;
  1397. }
  1398. EmptyProxy.prototype.dispose = function () { };
  1399. EmptyProxy.prototype.setCursor = function () { };
  1400. return EmptyProxy;
  1401. }(Eventful));
  1402. var HoveredResult = (function () {
  1403. function HoveredResult(x, y) {
  1404. this.x = x;
  1405. this.y = y;
  1406. }
  1407. return HoveredResult;
  1408. }());
  1409. var handlerNames = [
  1410. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1411. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1412. ];
  1413. var Handler = (function (_super) {
  1414. __extends(Handler, _super);
  1415. function Handler(storage, painter, proxy, painterRoot) {
  1416. var _this = _super.call(this) || this;
  1417. _this._hovered = new HoveredResult(0, 0);
  1418. _this.storage = storage;
  1419. _this.painter = painter;
  1420. _this.painterRoot = painterRoot;
  1421. proxy = proxy || new EmptyProxy();
  1422. _this.proxy = null;
  1423. _this.setHandlerProxy(proxy);
  1424. _this._draggingMgr = new Draggable(_this);
  1425. return _this;
  1426. }
  1427. Handler.prototype.setHandlerProxy = function (proxy) {
  1428. if (this.proxy) {
  1429. this.proxy.dispose();
  1430. }
  1431. if (proxy) {
  1432. each(handlerNames, function (name) {
  1433. proxy.on && proxy.on(name, this[name], this);
  1434. }, this);
  1435. proxy.handler = this;
  1436. }
  1437. this.proxy = proxy;
  1438. };
  1439. Handler.prototype.mousemove = function (event) {
  1440. var x = event.zrX;
  1441. var y = event.zrY;
  1442. var isOutside = isOutsideBoundary(this, x, y);
  1443. var lastHovered = this._hovered;
  1444. var lastHoveredTarget = lastHovered.target;
  1445. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1446. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1447. lastHoveredTarget = lastHovered.target;
  1448. }
  1449. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  1450. var hoveredTarget = hovered.target;
  1451. var proxy = this.proxy;
  1452. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1453. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1454. this.dispatchToElement(lastHovered, 'mouseout', event);
  1455. }
  1456. this.dispatchToElement(hovered, 'mousemove', event);
  1457. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1458. this.dispatchToElement(hovered, 'mouseover', event);
  1459. }
  1460. };
  1461. Handler.prototype.mouseout = function (event) {
  1462. var eventControl = event.zrEventControl;
  1463. if (eventControl !== 'only_globalout') {
  1464. this.dispatchToElement(this._hovered, 'mouseout', event);
  1465. }
  1466. if (eventControl !== 'no_globalout') {
  1467. this.trigger('globalout', { type: 'globalout', event: event });
  1468. }
  1469. };
  1470. Handler.prototype.resize = function () {
  1471. this._hovered = new HoveredResult(0, 0);
  1472. };
  1473. Handler.prototype.dispatch = function (eventName, eventArgs) {
  1474. var handler = this[eventName];
  1475. handler && handler.call(this, eventArgs);
  1476. };
  1477. Handler.prototype.dispose = function () {
  1478. this.proxy.dispose();
  1479. this.storage = null;
  1480. this.proxy = null;
  1481. this.painter = null;
  1482. };
  1483. Handler.prototype.setCursorStyle = function (cursorStyle) {
  1484. var proxy = this.proxy;
  1485. proxy.setCursor && proxy.setCursor(cursorStyle);
  1486. };
  1487. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  1488. targetInfo = targetInfo || {};
  1489. var el = targetInfo.target;
  1490. if (el && el.silent) {
  1491. return;
  1492. }
  1493. var eventKey = ('on' + eventName);
  1494. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1495. while (el) {
  1496. el[eventKey]
  1497. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  1498. el.trigger(eventName, eventPacket);
  1499. el = el.__hostTarget ? el.__hostTarget : el.parent;
  1500. if (eventPacket.cancelBubble) {
  1501. break;
  1502. }
  1503. }
  1504. if (!eventPacket.cancelBubble) {
  1505. this.trigger(eventName, eventPacket);
  1506. if (this.painter && this.painter.eachOtherLayer) {
  1507. this.painter.eachOtherLayer(function (layer) {
  1508. if (typeof (layer[eventKey]) === 'function') {
  1509. layer[eventKey].call(layer, eventPacket);
  1510. }
  1511. if (layer.trigger) {
  1512. layer.trigger(eventName, eventPacket);
  1513. }
  1514. });
  1515. }
  1516. }
  1517. };
  1518. Handler.prototype.findHover = function (x, y, exclude) {
  1519. var list = this.storage.getDisplayList();
  1520. var out = new HoveredResult(x, y);
  1521. for (var i = list.length - 1; i >= 0; i--) {
  1522. var hoverCheckResult = void 0;
  1523. if (list[i] !== exclude
  1524. && !list[i].ignore
  1525. && (hoverCheckResult = isHover(list[i], x, y))) {
  1526. !out.topTarget && (out.topTarget = list[i]);
  1527. if (hoverCheckResult !== SILENT) {
  1528. out.target = list[i];
  1529. break;
  1530. }
  1531. }
  1532. }
  1533. return out;
  1534. };
  1535. Handler.prototype.processGesture = function (event, stage) {
  1536. if (!this._gestureMgr) {
  1537. this._gestureMgr = new GestureMgr();
  1538. }
  1539. var gestureMgr = this._gestureMgr;
  1540. stage === 'start' && gestureMgr.clear();
  1541. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  1542. stage === 'end' && gestureMgr.clear();
  1543. if (gestureInfo) {
  1544. var type = gestureInfo.type;
  1545. event.gestureEvent = type;
  1546. var res = new HoveredResult();
  1547. res.target = gestureInfo.target;
  1548. this.dispatchToElement(res, type, gestureInfo.event);
  1549. }
  1550. };
  1551. return Handler;
  1552. }(Eventful));
  1553. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1554. Handler.prototype[name] = function (event) {
  1555. var x = event.zrX;
  1556. var y = event.zrY;
  1557. var isOutside = isOutsideBoundary(this, x, y);
  1558. var hovered;
  1559. var hoveredTarget;
  1560. if (name !== 'mouseup' || !isOutside) {
  1561. hovered = this.findHover(x, y);
  1562. hoveredTarget = hovered.target;
  1563. }
  1564. if (name === 'mousedown') {
  1565. this._downEl = hoveredTarget;
  1566. this._downPoint = [event.zrX, event.zrY];
  1567. this._upEl = hoveredTarget;
  1568. }
  1569. else if (name === 'mouseup') {
  1570. this._upEl = hoveredTarget;
  1571. }
  1572. else if (name === 'click') {
  1573. if (this._downEl !== this._upEl
  1574. || !this._downPoint
  1575. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  1576. return;
  1577. }
  1578. this._downPoint = null;
  1579. }
  1580. this.dispatchToElement(hovered, name, event);
  1581. };
  1582. });
  1583. function isHover(displayable, x, y) {
  1584. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1585. var el = displayable;
  1586. var isSilent = void 0;
  1587. var ignoreClip = false;
  1588. while (el) {
  1589. if (el.ignoreClip) {
  1590. ignoreClip = true;
  1591. }
  1592. if (!ignoreClip) {
  1593. var clipPath = el.getClipPath();
  1594. if (clipPath && !clipPath.contain(x, y)) {
  1595. return false;
  1596. }
  1597. if (el.silent) {
  1598. isSilent = true;
  1599. }
  1600. }
  1601. var hostEl = el.__hostTarget;
  1602. el = hostEl ? hostEl : el.parent;
  1603. }
  1604. return isSilent ? SILENT : true;
  1605. }
  1606. return false;
  1607. }
  1608. function isOutsideBoundary(handlerInstance, x, y) {
  1609. var painter = handlerInstance.painter;
  1610. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  1611. }
  1612. function create$1() {
  1613. return [1, 0, 0, 1, 0, 0];
  1614. }
  1615. function identity(out) {
  1616. out[0] = 1;
  1617. out[1] = 0;
  1618. out[2] = 0;
  1619. out[3] = 1;
  1620. out[4] = 0;
  1621. out[5] = 0;
  1622. return out;
  1623. }
  1624. function copy$1(out, m) {
  1625. out[0] = m[0];
  1626. out[1] = m[1];
  1627. out[2] = m[2];
  1628. out[3] = m[3];
  1629. out[4] = m[4];
  1630. out[5] = m[5];
  1631. return out;
  1632. }
  1633. function mul$1(out, m1, m2) {
  1634. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1635. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1636. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1637. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1638. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1639. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1640. out[0] = out0;
  1641. out[1] = out1;
  1642. out[2] = out2;
  1643. out[3] = out3;
  1644. out[4] = out4;
  1645. out[5] = out5;
  1646. return out;
  1647. }
  1648. function translate(out, a, v) {
  1649. out[0] = a[0];
  1650. out[1] = a[1];
  1651. out[2] = a[2];
  1652. out[3] = a[3];
  1653. out[4] = a[4] + v[0];
  1654. out[5] = a[5] + v[1];
  1655. return out;
  1656. }
  1657. function rotate(out, a, rad) {
  1658. var aa = a[0];
  1659. var ac = a[2];
  1660. var atx = a[4];
  1661. var ab = a[1];
  1662. var ad = a[3];
  1663. var aty = a[5];
  1664. var st = Math.sin(rad);
  1665. var ct = Math.cos(rad);
  1666. out[0] = aa * ct + ab * st;
  1667. out[1] = -aa * st + ab * ct;
  1668. out[2] = ac * ct + ad * st;
  1669. out[3] = -ac * st + ct * ad;
  1670. out[4] = ct * atx + st * aty;
  1671. out[5] = ct * aty - st * atx;
  1672. return out;
  1673. }
  1674. function scale$1(out, a, v) {
  1675. var vx = v[0];
  1676. var vy = v[1];
  1677. out[0] = a[0] * vx;
  1678. out[1] = a[1] * vy;
  1679. out[2] = a[2] * vx;
  1680. out[3] = a[3] * vy;
  1681. out[4] = a[4] * vx;
  1682. out[5] = a[5] * vy;
  1683. return out;
  1684. }
  1685. function invert(out, a) {
  1686. var aa = a[0];
  1687. var ac = a[2];
  1688. var atx = a[4];
  1689. var ab = a[1];
  1690. var ad = a[3];
  1691. var aty = a[5];
  1692. var det = aa * ad - ab * ac;
  1693. if (!det) {
  1694. return null;
  1695. }
  1696. det = 1.0 / det;
  1697. out[0] = ad * det;
  1698. out[1] = -ab * det;
  1699. out[2] = -ac * det;
  1700. out[3] = aa * det;
  1701. out[4] = (ac * aty - ad * atx) * det;
  1702. out[5] = (ab * atx - aa * aty) * det;
  1703. return out;
  1704. }
  1705. function clone$2(a) {
  1706. var b = create$1();
  1707. copy$1(b, a);
  1708. return b;
  1709. }
  1710. var matrix = /*#__PURE__*/Object.freeze({
  1711. __proto__: null,
  1712. create: create$1,
  1713. identity: identity,
  1714. copy: copy$1,
  1715. mul: mul$1,
  1716. translate: translate,
  1717. rotate: rotate,
  1718. scale: scale$1,
  1719. invert: invert,
  1720. clone: clone$2
  1721. });
  1722. var mIdentity = identity;
  1723. var EPSILON = 5e-5;
  1724. function isNotAroundZero(val) {
  1725. return val > EPSILON || val < -EPSILON;
  1726. }
  1727. var scaleTmp = [];
  1728. var tmpTransform = [];
  1729. var originTransform = create$1();
  1730. var abs = Math.abs;
  1731. var Transformable = (function () {
  1732. function Transformable() {
  1733. }
  1734. Transformable.prototype.setPosition = function (arr) {
  1735. this.x = arr[0];
  1736. this.y = arr[1];
  1737. };
  1738. Transformable.prototype.setScale = function (arr) {
  1739. this.scaleX = arr[0];
  1740. this.scaleY = arr[1];
  1741. };
  1742. Transformable.prototype.setOrigin = function (arr) {
  1743. this.originX = arr[0];
  1744. this.originY = arr[1];
  1745. };
  1746. Transformable.prototype.needLocalTransform = function () {
  1747. return isNotAroundZero(this.rotation)
  1748. || isNotAroundZero(this.x)
  1749. || isNotAroundZero(this.y)
  1750. || isNotAroundZero(this.scaleX - 1)
  1751. || isNotAroundZero(this.scaleY - 1);
  1752. };
  1753. Transformable.prototype.updateTransform = function () {
  1754. var parent = this.parent;
  1755. var parentHasTransform = parent && parent.transform;
  1756. var needLocalTransform = this.needLocalTransform();
  1757. var m = this.transform;
  1758. if (!(needLocalTransform || parentHasTransform)) {
  1759. m && mIdentity(m);
  1760. return;
  1761. }
  1762. m = m || create$1();
  1763. if (needLocalTransform) {
  1764. this.getLocalTransform(m);
  1765. }
  1766. else {
  1767. mIdentity(m);
  1768. }
  1769. if (parentHasTransform) {
  1770. if (needLocalTransform) {
  1771. mul$1(m, parent.transform, m);
  1772. }
  1773. else {
  1774. copy$1(m, parent.transform);
  1775. }
  1776. }
  1777. this.transform = m;
  1778. this._resolveGlobalScaleRatio(m);
  1779. };
  1780. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  1781. var globalScaleRatio = this.globalScaleRatio;
  1782. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  1783. this.getGlobalScale(scaleTmp);
  1784. var relX = scaleTmp[0] < 0 ? -1 : 1;
  1785. var relY = scaleTmp[1] < 0 ? -1 : 1;
  1786. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  1787. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  1788. m[0] *= sx;
  1789. m[1] *= sx;
  1790. m[2] *= sy;
  1791. m[3] *= sy;
  1792. }
  1793. this.invTransform = this.invTransform || create$1();
  1794. invert(this.invTransform, m);
  1795. };
  1796. Transformable.prototype.getLocalTransform = function (m) {
  1797. return Transformable.getLocalTransform(this, m);
  1798. };
  1799. Transformable.prototype.getComputedTransform = function () {
  1800. var transformNode = this;
  1801. var ancestors = [];
  1802. while (transformNode) {
  1803. ancestors.push(transformNode);
  1804. transformNode = transformNode.parent;
  1805. }
  1806. while (transformNode = ancestors.pop()) {
  1807. transformNode.updateTransform();
  1808. }
  1809. return this.transform;
  1810. };
  1811. Transformable.prototype.setLocalTransform = function (m) {
  1812. if (!m) {
  1813. return;
  1814. }
  1815. var sx = m[0] * m[0] + m[1] * m[1];
  1816. var sy = m[2] * m[2] + m[3] * m[3];
  1817. if (isNotAroundZero(sx - 1)) {
  1818. sx = Math.sqrt(sx);
  1819. }
  1820. if (isNotAroundZero(sy - 1)) {
  1821. sy = Math.sqrt(sy);
  1822. }
  1823. if (m[0] < 0) {
  1824. sx = -sx;
  1825. }
  1826. if (m[3] < 0) {
  1827. sy = -sy;
  1828. }
  1829. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1830. if (sx < 0 && sy < 0) {
  1831. this.rotation += Math.PI;
  1832. sx = -sx;
  1833. sy = -sy;
  1834. }
  1835. this.x = m[4];
  1836. this.y = m[5];
  1837. this.scaleX = sx;
  1838. this.scaleY = sy;
  1839. };
  1840. Transformable.prototype.decomposeTransform = function () {
  1841. if (!this.transform) {
  1842. return;
  1843. }
  1844. var parent = this.parent;
  1845. var m = this.transform;
  1846. if (parent && parent.transform) {
  1847. mul$1(tmpTransform, parent.invTransform, m);
  1848. m = tmpTransform;
  1849. }
  1850. var ox = this.originX;
  1851. var oy = this.originY;
  1852. if (ox || oy) {
  1853. originTransform[4] = ox;
  1854. originTransform[5] = oy;
  1855. mul$1(tmpTransform, m, originTransform);
  1856. tmpTransform[4] -= ox;
  1857. tmpTransform[5] -= oy;
  1858. m = tmpTransform;
  1859. }
  1860. this.setLocalTransform(m);
  1861. };
  1862. Transformable.prototype.getGlobalScale = function (out) {
  1863. var m = this.transform;
  1864. out = out || [];
  1865. if (!m) {
  1866. out[0] = 1;
  1867. out[1] = 1;
  1868. return out;
  1869. }
  1870. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1871. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1872. if (m[0] < 0) {
  1873. out[0] = -out[0];
  1874. }
  1875. if (m[3] < 0) {
  1876. out[1] = -out[1];
  1877. }
  1878. return out;
  1879. };
  1880. Transformable.prototype.transformCoordToLocal = function (x, y) {
  1881. var v2 = [x, y];
  1882. var invTransform = this.invTransform;
  1883. if (invTransform) {
  1884. applyTransform(v2, v2, invTransform);
  1885. }
  1886. return v2;
  1887. };
  1888. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  1889. var v2 = [x, y];
  1890. var transform = this.transform;
  1891. if (transform) {
  1892. applyTransform(v2, v2, transform);
  1893. }
  1894. return v2;
  1895. };
  1896. Transformable.prototype.getLineScale = function () {
  1897. var m = this.transform;
  1898. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  1899. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  1900. : 1;
  1901. };
  1902. Transformable.getLocalTransform = function (target, m) {
  1903. m = m || [];
  1904. mIdentity(m);
  1905. var ox = target.originX || 0;
  1906. var oy = target.originY || 0;
  1907. var sx = target.scaleX;
  1908. var sy = target.scaleY;
  1909. var rotation = target.rotation || 0;
  1910. var x = target.x;
  1911. var y = target.y;
  1912. m[4] -= ox;
  1913. m[5] -= oy;
  1914. m[0] *= sx;
  1915. m[1] *= sy;
  1916. m[2] *= sx;
  1917. m[3] *= sy;
  1918. m[4] *= sx;
  1919. m[5] *= sy;
  1920. if (rotation) {
  1921. rotate(m, m, rotation);
  1922. }
  1923. m[4] += ox;
  1924. m[5] += oy;
  1925. m[4] += x;
  1926. m[5] += y;
  1927. return m;
  1928. };
  1929. Transformable.initDefaultProps = (function () {
  1930. var proto = Transformable.prototype;
  1931. proto.x = 0;
  1932. proto.y = 0;
  1933. proto.scaleX = 1;
  1934. proto.scaleY = 1;
  1935. proto.originX = 0;
  1936. proto.originY = 0;
  1937. proto.rotation = 0;
  1938. proto.globalScaleRatio = 1;
  1939. })();
  1940. return Transformable;
  1941. }());
  1942. var easing = {
  1943. linear: function (k) {
  1944. return k;
  1945. },
  1946. quadraticIn: function (k) {
  1947. return k * k;
  1948. },
  1949. quadraticOut: function (k) {
  1950. return k * (2 - k);
  1951. },
  1952. quadraticInOut: function (k) {
  1953. if ((k *= 2) < 1) {
  1954. return 0.5 * k * k;
  1955. }
  1956. return -0.5 * (--k * (k - 2) - 1);
  1957. },
  1958. cubicIn: function (k) {
  1959. return k * k * k;
  1960. },
  1961. cubicOut: function (k) {
  1962. return --k * k * k + 1;
  1963. },
  1964. cubicInOut: function (k) {
  1965. if ((k *= 2) < 1) {
  1966. return 0.5 * k * k * k;
  1967. }
  1968. return 0.5 * ((k -= 2) * k * k + 2);
  1969. },
  1970. quarticIn: function (k) {
  1971. return k * k * k * k;
  1972. },
  1973. quarticOut: function (k) {
  1974. return 1 - (--k * k * k * k);
  1975. },
  1976. quarticInOut: function (k) {
  1977. if ((k *= 2) < 1) {
  1978. return 0.5 * k * k * k * k;
  1979. }
  1980. return -0.5 * ((k -= 2) * k * k * k - 2);
  1981. },
  1982. quinticIn: function (k) {
  1983. return k * k * k * k * k;
  1984. },
  1985. quinticOut: function (k) {
  1986. return --k * k * k * k * k + 1;
  1987. },
  1988. quinticInOut: function (k) {
  1989. if ((k *= 2) < 1) {
  1990. return 0.5 * k * k * k * k * k;
  1991. }
  1992. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  1993. },
  1994. sinusoidalIn: function (k) {
  1995. return 1 - Math.cos(k * Math.PI / 2);
  1996. },
  1997. sinusoidalOut: function (k) {
  1998. return Math.sin(k * Math.PI / 2);
  1999. },
  2000. sinusoidalInOut: function (k) {
  2001. return 0.5 * (1 - Math.cos(Math.PI * k));
  2002. },
  2003. exponentialIn: function (k) {
  2004. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2005. },
  2006. exponentialOut: function (k) {
  2007. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2008. },
  2009. exponentialInOut: function (k) {
  2010. if (k === 0) {
  2011. return 0;
  2012. }
  2013. if (k === 1) {
  2014. return 1;
  2015. }
  2016. if ((k *= 2) < 1) {
  2017. return 0.5 * Math.pow(1024, k - 1);
  2018. }
  2019. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2020. },
  2021. circularIn: function (k) {
  2022. return 1 - Math.sqrt(1 - k * k);
  2023. },
  2024. circularOut: function (k) {
  2025. return Math.sqrt(1 - (--k * k));
  2026. },
  2027. circularInOut: function (k) {
  2028. if ((k *= 2) < 1) {
  2029. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2030. }
  2031. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2032. },
  2033. elasticIn: function (k) {
  2034. var s;
  2035. var a = 0.1;
  2036. var p = 0.4;
  2037. if (k === 0) {
  2038. return 0;
  2039. }
  2040. if (k === 1) {
  2041. return 1;
  2042. }
  2043. if (!a || a < 1) {
  2044. a = 1;
  2045. s = p / 4;
  2046. }
  2047. else {
  2048. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2049. }
  2050. return -(a * Math.pow(2, 10 * (k -= 1))
  2051. * Math.sin((k - s) * (2 * Math.PI) / p));
  2052. },
  2053. elasticOut: function (k) {
  2054. var s;
  2055. var a = 0.1;
  2056. var p = 0.4;
  2057. if (k === 0) {
  2058. return 0;
  2059. }
  2060. if (k === 1) {
  2061. return 1;
  2062. }
  2063. if (!a || a < 1) {
  2064. a = 1;
  2065. s = p / 4;
  2066. }
  2067. else {
  2068. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2069. }
  2070. return (a * Math.pow(2, -10 * k)
  2071. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2072. },
  2073. elasticInOut: function (k) {
  2074. var s;
  2075. var a = 0.1;
  2076. var p = 0.4;
  2077. if (k === 0) {
  2078. return 0;
  2079. }
  2080. if (k === 1) {
  2081. return 1;
  2082. }
  2083. if (!a || a < 1) {
  2084. a = 1;
  2085. s = p / 4;
  2086. }
  2087. else {
  2088. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2089. }
  2090. if ((k *= 2) < 1) {
  2091. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2092. * Math.sin((k - s) * (2 * Math.PI) / p));
  2093. }
  2094. return a * Math.pow(2, -10 * (k -= 1))
  2095. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2096. },
  2097. backIn: function (k) {
  2098. var s = 1.70158;
  2099. return k * k * ((s + 1) * k - s);
  2100. },
  2101. backOut: function (k) {
  2102. var s = 1.70158;
  2103. return --k * k * ((s + 1) * k + s) + 1;
  2104. },
  2105. backInOut: function (k) {
  2106. var s = 1.70158 * 1.525;
  2107. if ((k *= 2) < 1) {
  2108. return 0.5 * (k * k * ((s + 1) * k - s));
  2109. }
  2110. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2111. },
  2112. bounceIn: function (k) {
  2113. return 1 - easing.bounceOut(1 - k);
  2114. },
  2115. bounceOut: function (k) {
  2116. if (k < (1 / 2.75)) {
  2117. return 7.5625 * k * k;
  2118. }
  2119. else if (k < (2 / 2.75)) {
  2120. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2121. }
  2122. else if (k < (2.5 / 2.75)) {
  2123. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2124. }
  2125. else {
  2126. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2127. }
  2128. },
  2129. bounceInOut: function (k) {
  2130. if (k < 0.5) {
  2131. return easing.bounceIn(k * 2) * 0.5;
  2132. }
  2133. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2134. }
  2135. };
  2136. var Clip = (function () {
  2137. function Clip(opts) {
  2138. this._initialized = false;
  2139. this._startTime = 0;
  2140. this._pausedTime = 0;
  2141. this._paused = false;
  2142. this._life = opts.life || 1000;
  2143. this._delay = opts.delay || 0;
  2144. this.loop = opts.loop == null ? false : opts.loop;
  2145. this.gap = opts.gap || 0;
  2146. this.easing = opts.easing || 'linear';
  2147. this.onframe = opts.onframe;
  2148. this.ondestroy = opts.ondestroy;
  2149. this.onrestart = opts.onrestart;
  2150. }
  2151. Clip.prototype.step = function (globalTime, deltaTime) {
  2152. if (!this._initialized) {
  2153. this._startTime = globalTime + this._delay;
  2154. this._initialized = true;
  2155. }
  2156. if (this._paused) {
  2157. this._pausedTime += deltaTime;
  2158. return;
  2159. }
  2160. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2161. if (percent < 0) {
  2162. percent = 0;
  2163. }
  2164. percent = Math.min(percent, 1);
  2165. var easing$1 = this.easing;
  2166. var easingFunc = typeof easing$1 === 'string'
  2167. ? easing[easing$1] : easing$1;
  2168. var schedule = typeof easingFunc === 'function'
  2169. ? easingFunc(percent)
  2170. : percent;
  2171. this.onframe && this.onframe(schedule);
  2172. if (percent === 1) {
  2173. if (this.loop) {
  2174. this._restart(globalTime);
  2175. this.onrestart && this.onrestart();
  2176. }
  2177. else {
  2178. return true;
  2179. }
  2180. }
  2181. return false;
  2182. };
  2183. Clip.prototype._restart = function (globalTime) {
  2184. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2185. this._startTime = globalTime - remainder + this.gap;
  2186. this._pausedTime = 0;
  2187. };
  2188. Clip.prototype.pause = function () {
  2189. this._paused = true;
  2190. };
  2191. Clip.prototype.resume = function () {
  2192. this._paused = false;
  2193. };
  2194. return Clip;
  2195. }());
  2196. var Entry = (function () {
  2197. function Entry(val) {
  2198. this.value = val;
  2199. }
  2200. return Entry;
  2201. }());
  2202. var LinkedList = (function () {
  2203. function LinkedList() {
  2204. this._len = 0;
  2205. }
  2206. LinkedList.prototype.insert = function (val) {
  2207. var entry = new Entry(val);
  2208. this.insertEntry(entry);
  2209. return entry;
  2210. };
  2211. LinkedList.prototype.insertEntry = function (entry) {
  2212. if (!this.head) {
  2213. this.head = this.tail = entry;
  2214. }
  2215. else {
  2216. this.tail.next = entry;
  2217. entry.prev = this.tail;
  2218. entry.next = null;
  2219. this.tail = entry;
  2220. }
  2221. this._len++;
  2222. };
  2223. LinkedList.prototype.remove = function (entry) {
  2224. var prev = entry.prev;
  2225. var next = entry.next;
  2226. if (prev) {
  2227. prev.next = next;
  2228. }
  2229. else {
  2230. this.head = next;
  2231. }
  2232. if (next) {
  2233. next.prev = prev;
  2234. }
  2235. else {
  2236. this.tail = prev;
  2237. }
  2238. entry.next = entry.prev = null;
  2239. this._len--;
  2240. };
  2241. LinkedList.prototype.len = function () {
  2242. return this._len;
  2243. };
  2244. LinkedList.prototype.clear = function () {
  2245. this.head = this.tail = null;
  2246. this._len = 0;
  2247. };
  2248. return LinkedList;
  2249. }());
  2250. var LRU = (function () {
  2251. function LRU(maxSize) {
  2252. this._list = new LinkedList();
  2253. this._maxSize = 10;
  2254. this._map = {};
  2255. this._maxSize = maxSize;
  2256. }
  2257. LRU.prototype.put = function (key, value) {
  2258. var list = this._list;
  2259. var map = this._map;
  2260. var removed = null;
  2261. if (map[key] == null) {
  2262. var len = list.len();
  2263. var entry = this._lastRemovedEntry;
  2264. if (len >= this._maxSize && len > 0) {
  2265. var leastUsedEntry = list.head;
  2266. list.remove(leastUsedEntry);
  2267. delete map[leastUsedEntry.key];
  2268. removed = leastUsedEntry.value;
  2269. this._lastRemovedEntry = leastUsedEntry;
  2270. }
  2271. if (entry) {
  2272. entry.value = value;
  2273. }
  2274. else {
  2275. entry = new Entry(value);
  2276. }
  2277. entry.key = key;
  2278. list.insertEntry(entry);
  2279. map[key] = entry;
  2280. }
  2281. return removed;
  2282. };
  2283. LRU.prototype.get = function (key) {
  2284. var entry = this._map[key];
  2285. var list = this._list;
  2286. if (entry != null) {
  2287. if (entry !== list.tail) {
  2288. list.remove(entry);
  2289. list.insertEntry(entry);
  2290. }
  2291. return entry.value;
  2292. }
  2293. };
  2294. LRU.prototype.clear = function () {
  2295. this._list.clear();
  2296. this._map = {};
  2297. };
  2298. LRU.prototype.len = function () {
  2299. return this._list.len();
  2300. };
  2301. return LRU;
  2302. }());
  2303. var kCSSColorTable = {
  2304. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  2305. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  2306. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  2307. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  2308. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  2309. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  2310. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  2311. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  2312. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  2313. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  2314. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  2315. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  2316. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  2317. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  2318. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  2319. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  2320. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  2321. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  2322. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  2323. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  2324. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  2325. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  2326. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  2327. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  2328. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  2329. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  2330. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  2331. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  2332. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  2333. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  2334. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  2335. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  2336. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  2337. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  2338. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  2339. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  2340. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  2341. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  2342. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  2343. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  2344. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  2345. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  2346. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  2347. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  2348. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  2349. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  2350. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  2351. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  2352. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  2353. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  2354. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  2355. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  2356. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  2357. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  2358. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  2359. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  2360. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  2361. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  2362. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  2363. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  2364. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  2365. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  2366. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  2367. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  2368. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  2369. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  2370. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  2371. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  2372. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  2373. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  2374. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  2375. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  2376. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  2377. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  2378. };
  2379. function clampCssByte(i) {
  2380. i = Math.round(i);
  2381. return i < 0 ? 0 : i > 255 ? 255 : i;
  2382. }
  2383. function clampCssAngle(i) {
  2384. i = Math.round(i);
  2385. return i < 0 ? 0 : i > 360 ? 360 : i;
  2386. }
  2387. function clampCssFloat(f) {
  2388. return f < 0 ? 0 : f > 1 ? 1 : f;
  2389. }
  2390. function parseCssInt(val) {
  2391. var str = val;
  2392. if (str.length && str.charAt(str.length - 1) === '%') {
  2393. return clampCssByte(parseFloat(str) / 100 * 255);
  2394. }
  2395. return clampCssByte(parseInt(str, 10));
  2396. }
  2397. function parseCssFloat(val) {
  2398. var str = val;
  2399. if (str.length && str.charAt(str.length - 1) === '%') {
  2400. return clampCssFloat(parseFloat(str) / 100);
  2401. }
  2402. return clampCssFloat(parseFloat(str));
  2403. }
  2404. function cssHueToRgb(m1, m2, h) {
  2405. if (h < 0) {
  2406. h += 1;
  2407. }
  2408. else if (h > 1) {
  2409. h -= 1;
  2410. }
  2411. if (h * 6 < 1) {
  2412. return m1 + (m2 - m1) * h * 6;
  2413. }
  2414. if (h * 2 < 1) {
  2415. return m2;
  2416. }
  2417. if (h * 3 < 2) {
  2418. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  2419. }
  2420. return m1;
  2421. }
  2422. function lerpNumber(a, b, p) {
  2423. return a + (b - a) * p;
  2424. }
  2425. function setRgba(out, r, g, b, a) {
  2426. out[0] = r;
  2427. out[1] = g;
  2428. out[2] = b;
  2429. out[3] = a;
  2430. return out;
  2431. }
  2432. function copyRgba(out, a) {
  2433. out[0] = a[0];
  2434. out[1] = a[1];
  2435. out[2] = a[2];
  2436. out[3] = a[3];
  2437. return out;
  2438. }
  2439. var colorCache = new LRU(20);
  2440. var lastRemovedArr = null;
  2441. function putToCache(colorStr, rgbaArr) {
  2442. if (lastRemovedArr) {
  2443. copyRgba(lastRemovedArr, rgbaArr);
  2444. }
  2445. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2446. }
  2447. function parse(colorStr, rgbaArr) {
  2448. if (!colorStr) {
  2449. return;
  2450. }
  2451. rgbaArr = rgbaArr || [];
  2452. var cached = colorCache.get(colorStr);
  2453. if (cached) {
  2454. return copyRgba(rgbaArr, cached);
  2455. }
  2456. colorStr = colorStr + '';
  2457. var str = colorStr.replace(/ /g, '').toLowerCase();
  2458. if (str in kCSSColorTable) {
  2459. copyRgba(rgbaArr, kCSSColorTable[str]);
  2460. putToCache(colorStr, rgbaArr);
  2461. return rgbaArr;
  2462. }
  2463. var strLen = str.length;
  2464. if (str.charAt(0) === '#') {
  2465. if (strLen === 4 || strLen === 5) {
  2466. var iv = parseInt(str.slice(1, 4), 16);
  2467. if (!(iv >= 0 && iv <= 0xfff)) {
  2468. setRgba(rgbaArr, 0, 0, 0, 1);
  2469. return;
  2470. }
  2471. 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);
  2472. putToCache(colorStr, rgbaArr);
  2473. return rgbaArr;
  2474. }
  2475. else if (strLen === 7 || strLen === 9) {
  2476. var iv = parseInt(str.slice(1, 7), 16);
  2477. if (!(iv >= 0 && iv <= 0xffffff)) {
  2478. setRgba(rgbaArr, 0, 0, 0, 1);
  2479. return;
  2480. }
  2481. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  2482. putToCache(colorStr, rgbaArr);
  2483. return rgbaArr;
  2484. }
  2485. return;
  2486. }
  2487. var op = str.indexOf('(');
  2488. var ep = str.indexOf(')');
  2489. if (op !== -1 && ep + 1 === strLen) {
  2490. var fname = str.substr(0, op);
  2491. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2492. var alpha = 1;
  2493. switch (fname) {
  2494. case 'rgba':
  2495. if (params.length !== 4) {
  2496. return params.length === 3
  2497. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  2498. : setRgba(rgbaArr, 0, 0, 0, 1);
  2499. }
  2500. alpha = parseCssFloat(params.pop());
  2501. case 'rgb':
  2502. if (params.length !== 3) {
  2503. setRgba(rgbaArr, 0, 0, 0, 1);
  2504. return;
  2505. }
  2506. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  2507. putToCache(colorStr, rgbaArr);
  2508. return rgbaArr;
  2509. case 'hsla':
  2510. if (params.length !== 4) {
  2511. setRgba(rgbaArr, 0, 0, 0, 1);
  2512. return;
  2513. }
  2514. params[3] = parseCssFloat(params[3]);
  2515. hsla2rgba(params, rgbaArr);
  2516. putToCache(colorStr, rgbaArr);
  2517. return rgbaArr;
  2518. case 'hsl':
  2519. if (params.length !== 3) {
  2520. setRgba(rgbaArr, 0, 0, 0, 1);
  2521. return;
  2522. }
  2523. hsla2rgba(params, rgbaArr);
  2524. putToCache(colorStr, rgbaArr);
  2525. return rgbaArr;
  2526. default:
  2527. return;
  2528. }
  2529. }
  2530. setRgba(rgbaArr, 0, 0, 0, 1);
  2531. return;
  2532. }
  2533. function hsla2rgba(hsla, rgba) {
  2534. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  2535. var s = parseCssFloat(hsla[1]);
  2536. var l = parseCssFloat(hsla[2]);
  2537. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2538. var m1 = l * 2 - m2;
  2539. rgba = rgba || [];
  2540. 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);
  2541. if (hsla.length === 4) {
  2542. rgba[3] = hsla[3];
  2543. }
  2544. return rgba;
  2545. }
  2546. function rgba2hsla(rgba) {
  2547. if (!rgba) {
  2548. return;
  2549. }
  2550. var R = rgba[0] / 255;
  2551. var G = rgba[1] / 255;
  2552. var B = rgba[2] / 255;
  2553. var vMin = Math.min(R, G, B);
  2554. var vMax = Math.max(R, G, B);
  2555. var delta = vMax - vMin;
  2556. var L = (vMax + vMin) / 2;
  2557. var H;
  2558. var S;
  2559. if (delta === 0) {
  2560. H = 0;
  2561. S = 0;
  2562. }
  2563. else {
  2564. if (L < 0.5) {
  2565. S = delta / (vMax + vMin);
  2566. }
  2567. else {
  2568. S = delta / (2 - vMax - vMin);
  2569. }
  2570. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2571. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2572. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2573. if (R === vMax) {
  2574. H = deltaB - deltaG;
  2575. }
  2576. else if (G === vMax) {
  2577. H = (1 / 3) + deltaR - deltaB;
  2578. }
  2579. else if (B === vMax) {
  2580. H = (2 / 3) + deltaG - deltaR;
  2581. }
  2582. if (H < 0) {
  2583. H += 1;
  2584. }
  2585. if (H > 1) {
  2586. H -= 1;
  2587. }
  2588. }
  2589. var hsla = [H * 360, S, L];
  2590. if (rgba[3] != null) {
  2591. hsla.push(rgba[3]);
  2592. }
  2593. return hsla;
  2594. }
  2595. function lift(color, level) {
  2596. var colorArr = parse(color);
  2597. if (colorArr) {
  2598. for (var i = 0; i < 3; i++) {
  2599. if (level < 0) {
  2600. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2601. }
  2602. else {
  2603. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2604. }
  2605. if (colorArr[i] > 255) {
  2606. colorArr[i] = 255;
  2607. }
  2608. else if (colorArr[i] < 0) {
  2609. colorArr[i] = 0;
  2610. }
  2611. }
  2612. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2613. }
  2614. }
  2615. function toHex(color) {
  2616. var colorArr = parse(color);
  2617. if (colorArr) {
  2618. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  2619. }
  2620. }
  2621. function fastLerp(normalizedValue, colors, out) {
  2622. if (!(colors && colors.length)
  2623. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  2624. return;
  2625. }
  2626. out = out || [];
  2627. var value = normalizedValue * (colors.length - 1);
  2628. var leftIndex = Math.floor(value);
  2629. var rightIndex = Math.ceil(value);
  2630. var leftColor = colors[leftIndex];
  2631. var rightColor = colors[rightIndex];
  2632. var dv = value - leftIndex;
  2633. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  2634. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  2635. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  2636. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  2637. return out;
  2638. }
  2639. var fastMapToColor = fastLerp;
  2640. function lerp$1(normalizedValue, colors, fullOutput) {
  2641. if (!(colors && colors.length)
  2642. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  2643. return;
  2644. }
  2645. var value = normalizedValue * (colors.length - 1);
  2646. var leftIndex = Math.floor(value);
  2647. var rightIndex = Math.ceil(value);
  2648. var leftColor = parse(colors[leftIndex]);
  2649. var rightColor = parse(colors[rightIndex]);
  2650. var dv = value - leftIndex;
  2651. var color = stringify([
  2652. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  2653. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  2654. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  2655. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  2656. ], 'rgba');
  2657. return fullOutput
  2658. ? {
  2659. color: color,
  2660. leftIndex: leftIndex,
  2661. rightIndex: rightIndex,
  2662. value: value
  2663. }
  2664. : color;
  2665. }
  2666. var mapToColor = lerp$1;
  2667. function modifyHSL(color, h, s, l) {
  2668. var colorArr = parse(color);
  2669. if (color) {
  2670. colorArr = rgba2hsla(colorArr);
  2671. h != null && (colorArr[0] = clampCssAngle(h));
  2672. s != null && (colorArr[1] = parseCssFloat(s));
  2673. l != null && (colorArr[2] = parseCssFloat(l));
  2674. return stringify(hsla2rgba(colorArr), 'rgba');
  2675. }
  2676. }
  2677. function modifyAlpha(color, alpha) {
  2678. var colorArr = parse(color);
  2679. if (colorArr && alpha != null) {
  2680. colorArr[3] = clampCssFloat(alpha);
  2681. return stringify(colorArr, 'rgba');
  2682. }
  2683. }
  2684. function stringify(arrColor, type) {
  2685. if (!arrColor || !arrColor.length) {
  2686. return;
  2687. }
  2688. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  2689. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  2690. colorStr += ',' + arrColor[3];
  2691. }
  2692. return type + '(' + colorStr + ')';
  2693. }
  2694. function lum(color, backgroundLum) {
  2695. var arr = parse(color);
  2696. return arr
  2697. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  2698. + (1 - arr[3]) * backgroundLum
  2699. : 0;
  2700. }
  2701. function random() {
  2702. var r = Math.round(Math.random() * 255);
  2703. var g = Math.round(Math.random() * 255);
  2704. var b = Math.round(Math.random() * 255);
  2705. return 'rgb(' + r + ',' + g + ',' + b + ')';
  2706. }
  2707. var color = /*#__PURE__*/Object.freeze({
  2708. __proto__: null,
  2709. parse: parse,
  2710. lift: lift,
  2711. toHex: toHex,
  2712. fastLerp: fastLerp,
  2713. fastMapToColor: fastMapToColor,
  2714. lerp: lerp$1,
  2715. mapToColor: mapToColor,
  2716. modifyHSL: modifyHSL,
  2717. modifyAlpha: modifyAlpha,
  2718. stringify: stringify,
  2719. lum: lum,
  2720. random: random
  2721. });
  2722. var arraySlice = Array.prototype.slice;
  2723. function interpolateNumber(p0, p1, percent) {
  2724. return (p1 - p0) * percent + p0;
  2725. }
  2726. function step(p0, p1, percent) {
  2727. return percent > 0.5 ? p1 : p0;
  2728. }
  2729. function interpolate1DArray(out, p0, p1, percent) {
  2730. var len = p0.length;
  2731. for (var i = 0; i < len; i++) {
  2732. out[i] = interpolateNumber(p0[i], p1[i], percent);
  2733. }
  2734. }
  2735. function interpolate2DArray(out, p0, p1, percent) {
  2736. var len = p0.length;
  2737. var len2 = len && p0[0].length;
  2738. for (var i = 0; i < len; i++) {
  2739. if (!out[i]) {
  2740. out[i] = [];
  2741. }
  2742. for (var j = 0; j < len2; j++) {
  2743. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  2744. }
  2745. }
  2746. }
  2747. function add1DArray(out, p0, p1, sign) {
  2748. var len = p0.length;
  2749. for (var i = 0; i < len; i++) {
  2750. out[i] = p0[i] + p1[i] * sign;
  2751. }
  2752. return out;
  2753. }
  2754. function add2DArray(out, p0, p1, sign) {
  2755. var len = p0.length;
  2756. var len2 = len && p0[0].length;
  2757. for (var i = 0; i < len; i++) {
  2758. if (!out[i]) {
  2759. out[i] = [];
  2760. }
  2761. for (var j = 0; j < len2; j++) {
  2762. out[i][j] = p0[i][j] + p1[i][j] * sign;
  2763. }
  2764. }
  2765. return out;
  2766. }
  2767. function fillArray(val0, val1, arrDim) {
  2768. var arr0 = val0;
  2769. var arr1 = val1;
  2770. if (!arr0.push || !arr1.push) {
  2771. return;
  2772. }
  2773. var arr0Len = arr0.length;
  2774. var arr1Len = arr1.length;
  2775. if (arr0Len !== arr1Len) {
  2776. var isPreviousLarger = arr0Len > arr1Len;
  2777. if (isPreviousLarger) {
  2778. arr0.length = arr1Len;
  2779. }
  2780. else {
  2781. for (var i = arr0Len; i < arr1Len; i++) {
  2782. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  2783. }
  2784. }
  2785. }
  2786. var len2 = arr0[0] && arr0[0].length;
  2787. for (var i = 0; i < arr0.length; i++) {
  2788. if (arrDim === 1) {
  2789. if (isNaN(arr0[i])) {
  2790. arr0[i] = arr1[i];
  2791. }
  2792. }
  2793. else {
  2794. for (var j = 0; j < len2; j++) {
  2795. if (isNaN(arr0[i][j])) {
  2796. arr0[i][j] = arr1[i][j];
  2797. }
  2798. }
  2799. }
  2800. }
  2801. }
  2802. function is1DArraySame(arr0, arr1) {
  2803. var len = arr0.length;
  2804. if (len !== arr1.length) {
  2805. return false;
  2806. }
  2807. for (var i = 0; i < len; i++) {
  2808. if (arr0[i] !== arr1[i]) {
  2809. return false;
  2810. }
  2811. }
  2812. return true;
  2813. }
  2814. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  2815. var v0 = (p2 - p0) * 0.5;
  2816. var v1 = (p3 - p1) * 0.5;
  2817. return (2 * (p1 - p2) + v0 + v1) * t3
  2818. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  2819. + v0 * t + p1;
  2820. }
  2821. function catmullRomInterpolate1DArray(out, p0, p1, p2, p3, t, t2, t3) {
  2822. var len = p0.length;
  2823. for (var i = 0; i < len; i++) {
  2824. out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3);
  2825. }
  2826. }
  2827. function catmullRomInterpolate2DArray(out, p0, p1, p2, p3, t, t2, t3) {
  2828. var len = p0.length;
  2829. var len2 = p0[0].length;
  2830. for (var i = 0; i < len; i++) {
  2831. if (!out[i]) {
  2832. out[1] = [];
  2833. }
  2834. for (var j = 0; j < len2; j++) {
  2835. out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3);
  2836. }
  2837. }
  2838. }
  2839. function cloneValue(value) {
  2840. if (isArrayLike(value)) {
  2841. var len = value.length;
  2842. if (isArrayLike(value[0])) {
  2843. var ret = [];
  2844. for (var i = 0; i < len; i++) {
  2845. ret.push(arraySlice.call(value[i]));
  2846. }
  2847. return ret;
  2848. }
  2849. return arraySlice.call(value);
  2850. }
  2851. return value;
  2852. }
  2853. function rgba2String(rgba) {
  2854. rgba[0] = Math.floor(rgba[0]);
  2855. rgba[1] = Math.floor(rgba[1]);
  2856. rgba[2] = Math.floor(rgba[2]);
  2857. return 'rgba(' + rgba.join(',') + ')';
  2858. }
  2859. function guessArrayDim(value) {
  2860. return isArrayLike(value && value[0]) ? 2 : 1;
  2861. }
  2862. var tmpRgba = [0, 0, 0, 0];
  2863. var Track = (function () {
  2864. function Track(propName) {
  2865. this.keyframes = [];
  2866. this.maxTime = 0;
  2867. this.arrDim = 0;
  2868. this.interpolable = true;
  2869. this._needsSort = false;
  2870. this._isAllValueEqual = true;
  2871. this._lastFrame = 0;
  2872. this._lastFramePercent = 0;
  2873. this.propName = propName;
  2874. }
  2875. Track.prototype.isFinished = function () {
  2876. return this._finished;
  2877. };
  2878. Track.prototype.setFinished = function () {
  2879. this._finished = true;
  2880. if (this._additiveTrack) {
  2881. this._additiveTrack.setFinished();
  2882. }
  2883. };
  2884. Track.prototype.needsAnimate = function () {
  2885. return !this._isAllValueEqual && this.keyframes.length >= 2 && this.interpolable;
  2886. };
  2887. Track.prototype.getAdditiveTrack = function () {
  2888. return this._additiveTrack;
  2889. };
  2890. Track.prototype.addKeyframe = function (time, value) {
  2891. if (time >= this.maxTime) {
  2892. this.maxTime = time;
  2893. }
  2894. else {
  2895. this._needsSort = true;
  2896. }
  2897. var keyframes = this.keyframes;
  2898. var len = keyframes.length;
  2899. if (this.interpolable) {
  2900. if (isArrayLike(value)) {
  2901. var arrayDim = guessArrayDim(value);
  2902. if (len > 0 && this.arrDim !== arrayDim) {
  2903. this.interpolable = false;
  2904. return;
  2905. }
  2906. if (arrayDim === 1 && typeof value[0] !== 'number'
  2907. || arrayDim === 2 && typeof value[0][0] !== 'number') {
  2908. this.interpolable = false;
  2909. return;
  2910. }
  2911. if (len > 0) {
  2912. var lastFrame = keyframes[len - 1];
  2913. if (this._isAllValueEqual) {
  2914. if (arrayDim === 1) {
  2915. if (!is1DArraySame(value, lastFrame.value)) {
  2916. this._isAllValueEqual = false;
  2917. }
  2918. }
  2919. else {
  2920. this._isAllValueEqual = false;
  2921. }
  2922. }
  2923. }
  2924. this.arrDim = arrayDim;
  2925. }
  2926. else {
  2927. if (this.arrDim > 0) {
  2928. this.interpolable = false;
  2929. return;
  2930. }
  2931. if (typeof value === 'string') {
  2932. var colorArray = parse(value);
  2933. if (colorArray) {
  2934. value = colorArray;
  2935. this.isValueColor = true;
  2936. }
  2937. else {
  2938. this.interpolable = false;
  2939. }
  2940. }
  2941. else if (typeof value !== 'number') {
  2942. this.interpolable = false;
  2943. return;
  2944. }
  2945. if (this._isAllValueEqual && len > 0) {
  2946. var lastFrame = keyframes[len - 1];
  2947. if (this.isValueColor && !is1DArraySame(lastFrame.value, value)) {
  2948. this._isAllValueEqual = false;
  2949. }
  2950. else if (lastFrame.value !== value) {
  2951. this._isAllValueEqual = false;
  2952. }
  2953. }
  2954. }
  2955. }
  2956. var kf = {
  2957. time: time,
  2958. value: value,
  2959. percent: 0
  2960. };
  2961. this.keyframes.push(kf);
  2962. return kf;
  2963. };
  2964. Track.prototype.prepare = function (additiveTrack) {
  2965. var kfs = this.keyframes;
  2966. if (this._needsSort) {
  2967. kfs.sort(function (a, b) {
  2968. return a.time - b.time;
  2969. });
  2970. }
  2971. var arrDim = this.arrDim;
  2972. var kfsLen = kfs.length;
  2973. var lastKf = kfs[kfsLen - 1];
  2974. for (var i = 0; i < kfsLen; i++) {
  2975. kfs[i].percent = kfs[i].time / this.maxTime;
  2976. if (arrDim > 0 && i !== kfsLen - 1) {
  2977. fillArray(kfs[i].value, lastKf.value, arrDim);
  2978. }
  2979. }
  2980. if (additiveTrack
  2981. && this.needsAnimate()
  2982. && additiveTrack.needsAnimate()
  2983. && arrDim === additiveTrack.arrDim
  2984. && this.isValueColor === additiveTrack.isValueColor
  2985. && !additiveTrack._finished) {
  2986. this._additiveTrack = additiveTrack;
  2987. var startValue = kfs[0].value;
  2988. for (var i = 0; i < kfsLen; i++) {
  2989. if (arrDim === 0) {
  2990. if (this.isValueColor) {
  2991. kfs[i].additiveValue
  2992. = add1DArray([], kfs[i].value, startValue, -1);
  2993. }
  2994. else {
  2995. kfs[i].additiveValue = kfs[i].value - startValue;
  2996. }
  2997. }
  2998. else if (arrDim === 1) {
  2999. kfs[i].additiveValue = add1DArray([], kfs[i].value, startValue, -1);
  3000. }
  3001. else if (arrDim === 2) {
  3002. kfs[i].additiveValue = add2DArray([], kfs[i].value, startValue, -1);
  3003. }
  3004. }
  3005. }
  3006. };
  3007. Track.prototype.step = function (target, percent) {
  3008. if (this._finished) {
  3009. return;
  3010. }
  3011. if (this._additiveTrack && this._additiveTrack._finished) {
  3012. this._additiveTrack = null;
  3013. }
  3014. var isAdditive = this._additiveTrack != null;
  3015. var valueKey = isAdditive ? 'additiveValue' : 'value';
  3016. var keyframes = this.keyframes;
  3017. var kfsNum = this.keyframes.length;
  3018. var propName = this.propName;
  3019. var arrDim = this.arrDim;
  3020. var isValueColor = this.isValueColor;
  3021. var frameIdx;
  3022. if (percent < 0) {
  3023. frameIdx = 0;
  3024. }
  3025. else if (percent < this._lastFramePercent) {
  3026. var start = Math.min(this._lastFrame + 1, kfsNum - 1);
  3027. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  3028. if (keyframes[frameIdx].percent <= percent) {
  3029. break;
  3030. }
  3031. }
  3032. frameIdx = Math.min(frameIdx, kfsNum - 2);
  3033. }
  3034. else {
  3035. for (frameIdx = this._lastFrame; frameIdx < kfsNum; frameIdx++) {
  3036. if (keyframes[frameIdx].percent > percent) {
  3037. break;
  3038. }
  3039. }
  3040. frameIdx = Math.min(frameIdx - 1, kfsNum - 2);
  3041. }
  3042. var nextFrame = keyframes[frameIdx + 1];
  3043. var frame = keyframes[frameIdx];
  3044. if (!(frame && nextFrame)) {
  3045. return;
  3046. }
  3047. this._lastFrame = frameIdx;
  3048. this._lastFramePercent = percent;
  3049. var range = (nextFrame.percent - frame.percent);
  3050. if (range === 0) {
  3051. return;
  3052. }
  3053. var w = (percent - frame.percent) / range;
  3054. var targetArr = isAdditive ? this._additiveValue
  3055. : (isValueColor ? tmpRgba : target[propName]);
  3056. if ((arrDim > 0 || isValueColor) && !targetArr) {
  3057. targetArr = this._additiveValue = [];
  3058. }
  3059. if (this.useSpline) {
  3060. var p1 = keyframes[frameIdx][valueKey];
  3061. var p0 = keyframes[frameIdx === 0 ? frameIdx : frameIdx - 1][valueKey];
  3062. var p2 = keyframes[frameIdx > kfsNum - 2 ? kfsNum - 1 : frameIdx + 1][valueKey];
  3063. var p3 = keyframes[frameIdx > kfsNum - 3 ? kfsNum - 1 : frameIdx + 2][valueKey];
  3064. if (arrDim > 0) {
  3065. arrDim === 1
  3066. ? catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w)
  3067. : catmullRomInterpolate2DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3068. }
  3069. else if (isValueColor) {
  3070. catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3071. if (!isAdditive) {
  3072. target[propName] = rgba2String(targetArr);
  3073. }
  3074. }
  3075. else {
  3076. var value = void 0;
  3077. if (!this.interpolable) {
  3078. value = p2;
  3079. }
  3080. else {
  3081. value = catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w);
  3082. }
  3083. if (isAdditive) {
  3084. this._additiveValue = value;
  3085. }
  3086. else {
  3087. target[propName] = value;
  3088. }
  3089. }
  3090. }
  3091. else {
  3092. if (arrDim > 0) {
  3093. arrDim === 1
  3094. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  3095. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3096. }
  3097. else if (isValueColor) {
  3098. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3099. if (!isAdditive) {
  3100. target[propName] = rgba2String(targetArr);
  3101. }
  3102. }
  3103. else {
  3104. var value = void 0;
  3105. if (!this.interpolable) {
  3106. value = step(frame[valueKey], nextFrame[valueKey], w);
  3107. }
  3108. else {
  3109. value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  3110. }
  3111. if (isAdditive) {
  3112. this._additiveValue = value;
  3113. }
  3114. else {
  3115. target[propName] = value;
  3116. }
  3117. }
  3118. }
  3119. if (isAdditive) {
  3120. this._addToTarget(target);
  3121. }
  3122. };
  3123. Track.prototype._addToTarget = function (target) {
  3124. var arrDim = this.arrDim;
  3125. var propName = this.propName;
  3126. var additiveValue = this._additiveValue;
  3127. if (arrDim === 0) {
  3128. if (this.isValueColor) {
  3129. parse(target[propName], tmpRgba);
  3130. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  3131. target[propName] = rgba2String(tmpRgba);
  3132. }
  3133. else {
  3134. target[propName] = target[propName] + additiveValue;
  3135. }
  3136. }
  3137. else if (arrDim === 1) {
  3138. add1DArray(target[propName], target[propName], additiveValue, 1);
  3139. }
  3140. else if (arrDim === 2) {
  3141. add2DArray(target[propName], target[propName], additiveValue, 1);
  3142. }
  3143. };
  3144. return Track;
  3145. }());
  3146. var Animator = (function () {
  3147. function Animator(target, loop, additiveTo) {
  3148. this._tracks = {};
  3149. this._trackKeys = [];
  3150. this._delay = 0;
  3151. this._maxTime = 0;
  3152. this._paused = false;
  3153. this._started = 0;
  3154. this._clip = null;
  3155. this._target = target;
  3156. this._loop = loop;
  3157. if (loop && additiveTo) {
  3158. logError('Can\' use additive animation on looped animation.');
  3159. return;
  3160. }
  3161. this._additiveAnimators = additiveTo;
  3162. }
  3163. Animator.prototype.getTarget = function () {
  3164. return this._target;
  3165. };
  3166. Animator.prototype.changeTarget = function (target) {
  3167. this._target = target;
  3168. };
  3169. Animator.prototype.when = function (time, props) {
  3170. return this.whenWithKeys(time, props, keys(props));
  3171. };
  3172. Animator.prototype.whenWithKeys = function (time, props, propNames) {
  3173. var tracks = this._tracks;
  3174. for (var i = 0; i < propNames.length; i++) {
  3175. var propName = propNames[i];
  3176. var track = tracks[propName];
  3177. if (!track) {
  3178. track = tracks[propName] = new Track(propName);
  3179. var initialValue = void 0;
  3180. var additiveTrack = this._getAdditiveTrack(propName);
  3181. if (additiveTrack) {
  3182. var lastFinalKf = additiveTrack.keyframes[additiveTrack.keyframes.length - 1];
  3183. initialValue = lastFinalKf && lastFinalKf.value;
  3184. if (additiveTrack.isValueColor && initialValue) {
  3185. initialValue = rgba2String(initialValue);
  3186. }
  3187. }
  3188. else {
  3189. initialValue = this._target[propName];
  3190. }
  3191. if (initialValue == null) {
  3192. continue;
  3193. }
  3194. if (time !== 0) {
  3195. track.addKeyframe(0, cloneValue(initialValue));
  3196. }
  3197. this._trackKeys.push(propName);
  3198. }
  3199. track.addKeyframe(time, cloneValue(props[propName]));
  3200. }
  3201. this._maxTime = Math.max(this._maxTime, time);
  3202. return this;
  3203. };
  3204. Animator.prototype.pause = function () {
  3205. this._clip.pause();
  3206. this._paused = true;
  3207. };
  3208. Animator.prototype.resume = function () {
  3209. this._clip.resume();
  3210. this._paused = false;
  3211. };
  3212. Animator.prototype.isPaused = function () {
  3213. return !!this._paused;
  3214. };
  3215. Animator.prototype._doneCallback = function () {
  3216. this._setTracksFinished();
  3217. this._clip = null;
  3218. var doneList = this._doneList;
  3219. if (doneList) {
  3220. var len = doneList.length;
  3221. for (var i = 0; i < len; i++) {
  3222. doneList[i].call(this);
  3223. }
  3224. }
  3225. };
  3226. Animator.prototype._abortedCallback = function () {
  3227. this._setTracksFinished();
  3228. var animation = this.animation;
  3229. var abortedList = this._abortedList;
  3230. if (animation) {
  3231. animation.removeClip(this._clip);
  3232. }
  3233. this._clip = null;
  3234. if (abortedList) {
  3235. for (var i = 0; i < abortedList.length; i++) {
  3236. abortedList[i].call(this);
  3237. }
  3238. }
  3239. };
  3240. Animator.prototype._setTracksFinished = function () {
  3241. var tracks = this._tracks;
  3242. var tracksKeys = this._trackKeys;
  3243. for (var i = 0; i < tracksKeys.length; i++) {
  3244. tracks[tracksKeys[i]].setFinished();
  3245. }
  3246. };
  3247. Animator.prototype._getAdditiveTrack = function (trackName) {
  3248. var additiveTrack;
  3249. var additiveAnimators = this._additiveAnimators;
  3250. if (additiveAnimators) {
  3251. for (var i = 0; i < additiveAnimators.length; i++) {
  3252. var track = additiveAnimators[i].getTrack(trackName);
  3253. if (track) {
  3254. additiveTrack = track;
  3255. }
  3256. }
  3257. }
  3258. return additiveTrack;
  3259. };
  3260. Animator.prototype.start = function (easing, forceAnimate) {
  3261. if (this._started > 0) {
  3262. return;
  3263. }
  3264. this._started = 1;
  3265. var self = this;
  3266. var tracks = [];
  3267. for (var i = 0; i < this._trackKeys.length; i++) {
  3268. var propName = this._trackKeys[i];
  3269. var track = this._tracks[propName];
  3270. var additiveTrack = this._getAdditiveTrack(propName);
  3271. var kfs = track.keyframes;
  3272. track.prepare(additiveTrack);
  3273. if (track.needsAnimate()) {
  3274. tracks.push(track);
  3275. }
  3276. else if (!track.interpolable) {
  3277. var lastKf = kfs[kfs.length - 1];
  3278. if (lastKf) {
  3279. self._target[track.propName] = lastKf.value;
  3280. }
  3281. }
  3282. }
  3283. if (tracks.length || forceAnimate) {
  3284. var clip = new Clip({
  3285. life: this._maxTime,
  3286. loop: this._loop,
  3287. delay: this._delay,
  3288. onframe: function (percent) {
  3289. self._started = 2;
  3290. var additiveAnimators = self._additiveAnimators;
  3291. if (additiveAnimators) {
  3292. var stillHasAdditiveAnimator = false;
  3293. for (var i = 0; i < additiveAnimators.length; i++) {
  3294. if (additiveAnimators[i]._clip) {
  3295. stillHasAdditiveAnimator = true;
  3296. break;
  3297. }
  3298. }
  3299. if (!stillHasAdditiveAnimator) {
  3300. self._additiveAnimators = null;
  3301. }
  3302. }
  3303. for (var i = 0; i < tracks.length; i++) {
  3304. tracks[i].step(self._target, percent);
  3305. }
  3306. var onframeList = self._onframeList;
  3307. if (onframeList) {
  3308. for (var i = 0; i < onframeList.length; i++) {
  3309. onframeList[i](self._target, percent);
  3310. }
  3311. }
  3312. },
  3313. ondestroy: function () {
  3314. self._doneCallback();
  3315. }
  3316. });
  3317. this._clip = clip;
  3318. if (this.animation) {
  3319. this.animation.addClip(clip);
  3320. }
  3321. if (easing && easing !== 'spline') {
  3322. clip.easing = easing;
  3323. }
  3324. }
  3325. else {
  3326. this._doneCallback();
  3327. }
  3328. return this;
  3329. };
  3330. Animator.prototype.stop = function (forwardToLast) {
  3331. if (!this._clip) {
  3332. return;
  3333. }
  3334. var clip = this._clip;
  3335. if (forwardToLast) {
  3336. clip.onframe(1);
  3337. }
  3338. this._abortedCallback();
  3339. };
  3340. Animator.prototype.delay = function (time) {
  3341. this._delay = time;
  3342. return this;
  3343. };
  3344. Animator.prototype.during = function (cb) {
  3345. if (cb) {
  3346. if (!this._onframeList) {
  3347. this._onframeList = [];
  3348. }
  3349. this._onframeList.push(cb);
  3350. }
  3351. return this;
  3352. };
  3353. Animator.prototype.done = function (cb) {
  3354. if (cb) {
  3355. if (!this._doneList) {
  3356. this._doneList = [];
  3357. }
  3358. this._doneList.push(cb);
  3359. }
  3360. return this;
  3361. };
  3362. Animator.prototype.aborted = function (cb) {
  3363. if (cb) {
  3364. if (!this._abortedList) {
  3365. this._abortedList = [];
  3366. }
  3367. this._abortedList.push(cb);
  3368. }
  3369. return this;
  3370. };
  3371. Animator.prototype.getClip = function () {
  3372. return this._clip;
  3373. };
  3374. Animator.prototype.getTrack = function (propName) {
  3375. return this._tracks[propName];
  3376. };
  3377. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  3378. if (!propNames.length || !this._clip) {
  3379. return true;
  3380. }
  3381. var tracks = this._tracks;
  3382. var tracksKeys = this._trackKeys;
  3383. for (var i = 0; i < propNames.length; i++) {
  3384. var track = tracks[propNames[i]];
  3385. if (track) {
  3386. if (forwardToLast) {
  3387. track.step(this._target, 1);
  3388. }
  3389. else if (this._started === 1) {
  3390. track.step(this._target, 0);
  3391. }
  3392. track.setFinished();
  3393. }
  3394. }
  3395. var allAborted = true;
  3396. for (var i = 0; i < tracksKeys.length; i++) {
  3397. if (!tracks[tracksKeys[i]].isFinished()) {
  3398. allAborted = false;
  3399. break;
  3400. }
  3401. }
  3402. if (allAborted) {
  3403. this._abortedCallback();
  3404. }
  3405. return allAborted;
  3406. };
  3407. Animator.prototype.saveFinalToTarget = function (target, trackKeys) {
  3408. if (!target) {
  3409. return;
  3410. }
  3411. trackKeys = trackKeys || this._trackKeys;
  3412. for (var i = 0; i < trackKeys.length; i++) {
  3413. var propName = trackKeys[i];
  3414. var track = this._tracks[propName];
  3415. if (!track || track.isFinished()) {
  3416. continue;
  3417. }
  3418. var kfs = track.keyframes;
  3419. var lastKf = kfs[kfs.length - 1];
  3420. if (lastKf) {
  3421. var val = cloneValue(lastKf.value);
  3422. if (track.isValueColor) {
  3423. val = rgba2String(val);
  3424. }
  3425. target[propName] = val;
  3426. }
  3427. }
  3428. };
  3429. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  3430. trackKeys = trackKeys || keys(finalProps);
  3431. for (var i = 0; i < trackKeys.length; i++) {
  3432. var propName = trackKeys[i];
  3433. var track = this._tracks[propName];
  3434. if (!track) {
  3435. continue;
  3436. }
  3437. var kfs = track.keyframes;
  3438. if (kfs.length > 1) {
  3439. var lastKf = kfs.pop();
  3440. track.addKeyframe(lastKf.time, finalProps[propName]);
  3441. track.prepare(track.getAdditiveTrack());
  3442. }
  3443. }
  3444. };
  3445. return Animator;
  3446. }());
  3447. var Point = (function () {
  3448. function Point(x, y) {
  3449. this.x = x || 0;
  3450. this.y = y || 0;
  3451. }
  3452. Point.prototype.copy = function (other) {
  3453. this.x = other.x;
  3454. this.y = other.y;
  3455. return this;
  3456. };
  3457. Point.prototype.clone = function () {
  3458. return new Point(this.x, this.y);
  3459. };
  3460. Point.prototype.set = function (x, y) {
  3461. this.x = x;
  3462. this.y = y;
  3463. return this;
  3464. };
  3465. Point.prototype.equal = function (other) {
  3466. return other.x === this.x && other.y === this.y;
  3467. };
  3468. Point.prototype.add = function (other) {
  3469. this.x += other.x;
  3470. this.y += other.y;
  3471. return this;
  3472. };
  3473. Point.prototype.scale = function (scalar) {
  3474. this.x *= scalar;
  3475. this.y *= scalar;
  3476. };
  3477. Point.prototype.scaleAndAdd = function (other, scalar) {
  3478. this.x += other.x * scalar;
  3479. this.y += other.y * scalar;
  3480. };
  3481. Point.prototype.sub = function (other) {
  3482. this.x -= other.x;
  3483. this.y -= other.y;
  3484. return this;
  3485. };
  3486. Point.prototype.dot = function (other) {
  3487. return this.x * other.x + this.y * other.y;
  3488. };
  3489. Point.prototype.len = function () {
  3490. return Math.sqrt(this.x * this.x + this.y * this.y);
  3491. };
  3492. Point.prototype.lenSquare = function () {
  3493. return this.x * this.x + this.y * this.y;
  3494. };
  3495. Point.prototype.normalize = function () {
  3496. var len = this.len();
  3497. this.x /= len;
  3498. this.y /= len;
  3499. return this;
  3500. };
  3501. Point.prototype.distance = function (other) {
  3502. var dx = this.x - other.x;
  3503. var dy = this.y - other.y;
  3504. return Math.sqrt(dx * dx + dy * dy);
  3505. };
  3506. Point.prototype.distanceSquare = function (other) {
  3507. var dx = this.x - other.x;
  3508. var dy = this.y - other.y;
  3509. return dx * dx + dy * dy;
  3510. };
  3511. Point.prototype.negate = function () {
  3512. this.x = -this.x;
  3513. this.y = -this.y;
  3514. return this;
  3515. };
  3516. Point.prototype.transform = function (m) {
  3517. if (!m) {
  3518. return;
  3519. }
  3520. var x = this.x;
  3521. var y = this.y;
  3522. this.x = m[0] * x + m[2] * y + m[4];
  3523. this.y = m[1] * x + m[3] * y + m[5];
  3524. return this;
  3525. };
  3526. Point.prototype.toArray = function (out) {
  3527. out[0] = this.x;
  3528. out[1] = this.y;
  3529. return out;
  3530. };
  3531. Point.prototype.fromArray = function (input) {
  3532. this.x = input[0];
  3533. this.y = input[1];
  3534. };
  3535. Point.set = function (p, x, y) {
  3536. p.x = x;
  3537. p.y = y;
  3538. };
  3539. Point.copy = function (p, p2) {
  3540. p.x = p2.x;
  3541. p.y = p2.y;
  3542. };
  3543. Point.len = function (p) {
  3544. return Math.sqrt(p.x * p.x + p.y * p.y);
  3545. };
  3546. Point.lenSquare = function (p) {
  3547. return p.x * p.x + p.y * p.y;
  3548. };
  3549. Point.dot = function (p0, p1) {
  3550. return p0.x * p1.x + p0.y * p1.y;
  3551. };
  3552. Point.add = function (out, p0, p1) {
  3553. out.x = p0.x + p1.x;
  3554. out.y = p0.y + p1.y;
  3555. };
  3556. Point.sub = function (out, p0, p1) {
  3557. out.x = p0.x - p1.x;
  3558. out.y = p0.y - p1.y;
  3559. };
  3560. Point.scale = function (out, p0, scalar) {
  3561. out.x = p0.x * scalar;
  3562. out.y = p0.y * scalar;
  3563. };
  3564. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  3565. out.x = p0.x + p1.x * scalar;
  3566. out.y = p0.y + p1.y * scalar;
  3567. };
  3568. Point.lerp = function (out, p0, p1, t) {
  3569. var onet = 1 - t;
  3570. out.x = onet * p0.x + t * p1.x;
  3571. out.y = onet * p0.y + t * p1.y;
  3572. };
  3573. return Point;
  3574. }());
  3575. var mathMin = Math.min;
  3576. var mathMax = Math.max;
  3577. var lt = new Point();
  3578. var rb = new Point();
  3579. var lb = new Point();
  3580. var rt = new Point();
  3581. var minTv = new Point();
  3582. var maxTv = new Point();
  3583. var BoundingRect = (function () {
  3584. function BoundingRect(x, y, width, height) {
  3585. if (width < 0 && isFinite(width)) {
  3586. x = x + width;
  3587. width = -width;
  3588. }
  3589. if (height < 0 && isFinite(height)) {
  3590. y = y + height;
  3591. height = -height;
  3592. }
  3593. this.x = x;
  3594. this.y = y;
  3595. this.width = width;
  3596. this.height = height;
  3597. }
  3598. BoundingRect.prototype.union = function (other) {
  3599. var x = mathMin(other.x, this.x);
  3600. var y = mathMin(other.y, this.y);
  3601. if (isFinite(this.x) && isFinite(this.width)) {
  3602. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  3603. }
  3604. else {
  3605. this.width = other.width;
  3606. }
  3607. if (isFinite(this.y) && isFinite(this.height)) {
  3608. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  3609. }
  3610. else {
  3611. this.height = other.height;
  3612. }
  3613. this.x = x;
  3614. this.y = y;
  3615. };
  3616. BoundingRect.prototype.applyTransform = function (m) {
  3617. BoundingRect.applyTransform(this, this, m);
  3618. };
  3619. BoundingRect.prototype.calculateTransform = function (b) {
  3620. var a = this;
  3621. var sx = b.width / a.width;
  3622. var sy = b.height / a.height;
  3623. var m = create$1();
  3624. translate(m, m, [-a.x, -a.y]);
  3625. scale$1(m, m, [sx, sy]);
  3626. translate(m, m, [b.x, b.y]);
  3627. return m;
  3628. };
  3629. BoundingRect.prototype.intersect = function (b, mtv) {
  3630. if (!b) {
  3631. return false;
  3632. }
  3633. if (!(b instanceof BoundingRect)) {
  3634. b = BoundingRect.create(b);
  3635. }
  3636. var a = this;
  3637. var ax0 = a.x;
  3638. var ax1 = a.x + a.width;
  3639. var ay0 = a.y;
  3640. var ay1 = a.y + a.height;
  3641. var bx0 = b.x;
  3642. var bx1 = b.x + b.width;
  3643. var by0 = b.y;
  3644. var by1 = b.y + b.height;
  3645. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  3646. if (mtv) {
  3647. var dMin = Infinity;
  3648. var dMax = 0;
  3649. var d0 = Math.abs(ax1 - bx0);
  3650. var d1 = Math.abs(bx1 - ax0);
  3651. var d2 = Math.abs(ay1 - by0);
  3652. var d3 = Math.abs(by1 - ay0);
  3653. var dx = Math.min(d0, d1);
  3654. var dy = Math.min(d2, d3);
  3655. if (ax1 < bx0 || bx1 < ax0) {
  3656. if (dx > dMax) {
  3657. dMax = dx;
  3658. if (d0 < d1) {
  3659. Point.set(maxTv, -d0, 0);
  3660. }
  3661. else {
  3662. Point.set(maxTv, d1, 0);
  3663. }
  3664. }
  3665. }
  3666. else {
  3667. if (dx < dMin) {
  3668. dMin = dx;
  3669. if (d0 < d1) {
  3670. Point.set(minTv, d0, 0);
  3671. }
  3672. else {
  3673. Point.set(minTv, -d1, 0);
  3674. }
  3675. }
  3676. }
  3677. if (ay1 < by0 || by1 < ay0) {
  3678. if (dy > dMax) {
  3679. dMax = dy;
  3680. if (d2 < d3) {
  3681. Point.set(maxTv, 0, -d2);
  3682. }
  3683. else {
  3684. Point.set(maxTv, 0, d3);
  3685. }
  3686. }
  3687. }
  3688. else {
  3689. if (dx < dMin) {
  3690. dMin = dx;
  3691. if (d2 < d3) {
  3692. Point.set(minTv, 0, d2);
  3693. }
  3694. else {
  3695. Point.set(minTv, 0, -d3);
  3696. }
  3697. }
  3698. }
  3699. }
  3700. if (mtv) {
  3701. Point.copy(mtv, overlap ? minTv : maxTv);
  3702. }
  3703. return overlap;
  3704. };
  3705. BoundingRect.prototype.contain = function (x, y) {
  3706. var rect = this;
  3707. return x >= rect.x
  3708. && x <= (rect.x + rect.width)
  3709. && y >= rect.y
  3710. && y <= (rect.y + rect.height);
  3711. };
  3712. BoundingRect.prototype.clone = function () {
  3713. return new BoundingRect(this.x, this.y, this.width, this.height);
  3714. };
  3715. BoundingRect.prototype.copy = function (other) {
  3716. BoundingRect.copy(this, other);
  3717. };
  3718. BoundingRect.prototype.plain = function () {
  3719. return {
  3720. x: this.x,
  3721. y: this.y,
  3722. width: this.width,
  3723. height: this.height
  3724. };
  3725. };
  3726. BoundingRect.prototype.isFinite = function () {
  3727. return isFinite(this.x)
  3728. && isFinite(this.y)
  3729. && isFinite(this.width)
  3730. && isFinite(this.height);
  3731. };
  3732. BoundingRect.prototype.isZero = function () {
  3733. return this.width === 0 || this.height === 0;
  3734. };
  3735. BoundingRect.create = function (rect) {
  3736. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  3737. };
  3738. BoundingRect.copy = function (target, source) {
  3739. target.x = source.x;
  3740. target.y = source.y;
  3741. target.width = source.width;
  3742. target.height = source.height;
  3743. };
  3744. BoundingRect.applyTransform = function (target, source, m) {
  3745. if (!m) {
  3746. if (target !== source) {
  3747. BoundingRect.copy(target, source);
  3748. }
  3749. return;
  3750. }
  3751. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  3752. var sx = m[0];
  3753. var sy = m[3];
  3754. var tx = m[4];
  3755. var ty = m[5];
  3756. target.x = source.x * sx + tx;
  3757. target.y = source.y * sy + ty;
  3758. target.width = source.width * sx;
  3759. target.height = source.height * sy;
  3760. if (target.width < 0) {
  3761. target.x += target.width;
  3762. target.width = -target.width;
  3763. }
  3764. if (target.height < 0) {
  3765. target.y += target.height;
  3766. target.height = -target.height;
  3767. }
  3768. return;
  3769. }
  3770. lt.x = lb.x = source.x;
  3771. lt.y = rt.y = source.y;
  3772. rb.x = rt.x = source.x + source.width;
  3773. rb.y = lb.y = source.y + source.height;
  3774. lt.transform(m);
  3775. rt.transform(m);
  3776. rb.transform(m);
  3777. lb.transform(m);
  3778. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  3779. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  3780. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  3781. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  3782. target.width = maxX - target.x;
  3783. target.height = maxY - target.y;
  3784. };
  3785. return BoundingRect;
  3786. }());
  3787. var textWidthCache = {};
  3788. var DEFAULT_FONT = '12px sans-serif';
  3789. var _ctx;
  3790. var _cachedFont;
  3791. function defaultMeasureText(text, font) {
  3792. if (!_ctx) {
  3793. _ctx = createCanvas().getContext('2d');
  3794. }
  3795. if (_cachedFont !== font) {
  3796. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  3797. }
  3798. return _ctx.measureText(text);
  3799. }
  3800. var methods$1 = {
  3801. measureText: defaultMeasureText
  3802. };
  3803. function getWidth(text, font) {
  3804. font = font || DEFAULT_FONT;
  3805. var cacheOfFont = textWidthCache[font];
  3806. if (!cacheOfFont) {
  3807. cacheOfFont = textWidthCache[font] = new LRU(500);
  3808. }
  3809. var width = cacheOfFont.get(text);
  3810. if (width == null) {
  3811. width = methods$1.measureText(text, font).width;
  3812. cacheOfFont.put(text, width);
  3813. }
  3814. return width;
  3815. }
  3816. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  3817. var width = getWidth(text, font);
  3818. var height = getLineHeight(font);
  3819. var x = adjustTextX(0, width, textAlign);
  3820. var y = adjustTextY(0, height, textBaseline);
  3821. var rect = new BoundingRect(x, y, width, height);
  3822. return rect;
  3823. }
  3824. function getBoundingRect(text, font, textAlign, textBaseline) {
  3825. var textLines = ((text || '') + '').split('\n');
  3826. var len = textLines.length;
  3827. if (len === 1) {
  3828. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  3829. }
  3830. else {
  3831. var uniondRect = new BoundingRect(0, 0, 0, 0);
  3832. for (var i = 0; i < textLines.length; i++) {
  3833. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  3834. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  3835. }
  3836. return uniondRect;
  3837. }
  3838. }
  3839. function adjustTextX(x, width, textAlign) {
  3840. if (textAlign === 'right') {
  3841. x -= width;
  3842. }
  3843. else if (textAlign === 'center') {
  3844. x -= width / 2;
  3845. }
  3846. return x;
  3847. }
  3848. function adjustTextY(y, height, verticalAlign) {
  3849. if (verticalAlign === 'middle') {
  3850. y -= height / 2;
  3851. }
  3852. else if (verticalAlign === 'bottom') {
  3853. y -= height;
  3854. }
  3855. return y;
  3856. }
  3857. function getLineHeight(font) {
  3858. return getWidth('国', font);
  3859. }
  3860. function parsePercent(value, maxValue) {
  3861. if (typeof value === 'string') {
  3862. if (value.lastIndexOf('%') >= 0) {
  3863. return parseFloat(value) / 100 * maxValue;
  3864. }
  3865. return parseFloat(value);
  3866. }
  3867. return value;
  3868. }
  3869. function calculateTextPosition(out, opts, rect) {
  3870. var textPosition = opts.position || 'inside';
  3871. var distance = opts.distance != null ? opts.distance : 5;
  3872. var height = rect.height;
  3873. var width = rect.width;
  3874. var halfHeight = height / 2;
  3875. var x = rect.x;
  3876. var y = rect.y;
  3877. var textAlign = 'left';
  3878. var textVerticalAlign = 'top';
  3879. if (textPosition instanceof Array) {
  3880. x += parsePercent(textPosition[0], rect.width);
  3881. y += parsePercent(textPosition[1], rect.height);
  3882. textAlign = null;
  3883. textVerticalAlign = null;
  3884. }
  3885. else {
  3886. switch (textPosition) {
  3887. case 'left':
  3888. x -= distance;
  3889. y += halfHeight;
  3890. textAlign = 'right';
  3891. textVerticalAlign = 'middle';
  3892. break;
  3893. case 'right':
  3894. x += distance + width;
  3895. y += halfHeight;
  3896. textVerticalAlign = 'middle';
  3897. break;
  3898. case 'top':
  3899. x += width / 2;
  3900. y -= distance;
  3901. textAlign = 'center';
  3902. textVerticalAlign = 'bottom';
  3903. break;
  3904. case 'bottom':
  3905. x += width / 2;
  3906. y += height + distance;
  3907. textAlign = 'center';
  3908. break;
  3909. case 'inside':
  3910. x += width / 2;
  3911. y += halfHeight;
  3912. textAlign = 'center';
  3913. textVerticalAlign = 'middle';
  3914. break;
  3915. case 'insideLeft':
  3916. x += distance;
  3917. y += halfHeight;
  3918. textVerticalAlign = 'middle';
  3919. break;
  3920. case 'insideRight':
  3921. x += width - distance;
  3922. y += halfHeight;
  3923. textAlign = 'right';
  3924. textVerticalAlign = 'middle';
  3925. break;
  3926. case 'insideTop':
  3927. x += width / 2;
  3928. y += distance;
  3929. textAlign = 'center';
  3930. break;
  3931. case 'insideBottom':
  3932. x += width / 2;
  3933. y += height - distance;
  3934. textAlign = 'center';
  3935. textVerticalAlign = 'bottom';
  3936. break;
  3937. case 'insideTopLeft':
  3938. x += distance;
  3939. y += distance;
  3940. break;
  3941. case 'insideTopRight':
  3942. x += width - distance;
  3943. y += distance;
  3944. textAlign = 'right';
  3945. break;
  3946. case 'insideBottomLeft':
  3947. x += distance;
  3948. y += height - distance;
  3949. textVerticalAlign = 'bottom';
  3950. break;
  3951. case 'insideBottomRight':
  3952. x += width - distance;
  3953. y += height - distance;
  3954. textAlign = 'right';
  3955. textVerticalAlign = 'bottom';
  3956. break;
  3957. }
  3958. }
  3959. out = out || {};
  3960. out.x = x;
  3961. out.y = y;
  3962. out.align = textAlign;
  3963. out.verticalAlign = textVerticalAlign;
  3964. return out;
  3965. }
  3966. var dpr = 1;
  3967. if (typeof window !== 'undefined') {
  3968. dpr = Math.max(window.devicePixelRatio
  3969. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  3970. || 1, 1);
  3971. }
  3972. var devicePixelRatio = dpr;
  3973. var DARK_MODE_THRESHOLD = 0.4;
  3974. var DARK_LABEL_COLOR = '#333';
  3975. var LIGHT_LABEL_COLOR = '#ccc';
  3976. var LIGHTER_LABEL_COLOR = '#eee';
  3977. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  3978. var PRIMARY_STATES_KEYS = ['x', 'y', 'scaleX', 'scaleY', 'originX', 'originY', 'rotation', 'ignore'];
  3979. var DEFAULT_ANIMATABLE_MAP = {
  3980. x: true,
  3981. y: true,
  3982. scaleX: true,
  3983. scaleY: true,
  3984. originX: true,
  3985. originY: true,
  3986. rotation: true,
  3987. ignore: false
  3988. };
  3989. var tmpTextPosCalcRes = {};
  3990. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  3991. var Element = (function () {
  3992. function Element(props) {
  3993. this.id = guid();
  3994. this.animators = [];
  3995. this.currentStates = [];
  3996. this.states = {};
  3997. this._init(props);
  3998. }
  3999. Element.prototype._init = function (props) {
  4000. this.attr(props);
  4001. };
  4002. Element.prototype.drift = function (dx, dy, e) {
  4003. switch (this.draggable) {
  4004. case 'horizontal':
  4005. dy = 0;
  4006. break;
  4007. case 'vertical':
  4008. dx = 0;
  4009. break;
  4010. }
  4011. var m = this.transform;
  4012. if (!m) {
  4013. m = this.transform = [1, 0, 0, 1, 0, 0];
  4014. }
  4015. m[4] += dx;
  4016. m[5] += dy;
  4017. this.decomposeTransform();
  4018. this.markRedraw();
  4019. };
  4020. Element.prototype.beforeUpdate = function () { };
  4021. Element.prototype.afterUpdate = function () { };
  4022. Element.prototype.update = function () {
  4023. this.updateTransform();
  4024. if (this.__dirty) {
  4025. this.updateInnerText();
  4026. }
  4027. };
  4028. Element.prototype.updateInnerText = function (forceUpdate) {
  4029. var textEl = this._textContent;
  4030. if (textEl && (!textEl.ignore || forceUpdate)) {
  4031. if (!this.textConfig) {
  4032. this.textConfig = {};
  4033. }
  4034. var textConfig = this.textConfig;
  4035. var isLocal = textConfig.local;
  4036. var attachedTransform = textEl.attachedTransform;
  4037. var textAlign = void 0;
  4038. var textVerticalAlign = void 0;
  4039. var textStyleChanged = false;
  4040. if (isLocal) {
  4041. attachedTransform.parent = this;
  4042. }
  4043. else {
  4044. attachedTransform.parent = null;
  4045. }
  4046. var innerOrigin = false;
  4047. attachedTransform.x = textEl.x;
  4048. attachedTransform.y = textEl.y;
  4049. attachedTransform.originX = textEl.originX;
  4050. attachedTransform.originY = textEl.originY;
  4051. attachedTransform.rotation = textEl.rotation;
  4052. attachedTransform.scaleX = textEl.scaleX;
  4053. attachedTransform.scaleY = textEl.scaleY;
  4054. if (textConfig.position != null) {
  4055. var layoutRect = tmpBoundingRect;
  4056. if (textConfig.layoutRect) {
  4057. layoutRect.copy(textConfig.layoutRect);
  4058. }
  4059. else {
  4060. layoutRect.copy(this.getBoundingRect());
  4061. }
  4062. if (!isLocal) {
  4063. layoutRect.applyTransform(this.transform);
  4064. }
  4065. if (this.calculateTextPosition) {
  4066. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  4067. }
  4068. else {
  4069. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  4070. }
  4071. attachedTransform.x = tmpTextPosCalcRes.x;
  4072. attachedTransform.y = tmpTextPosCalcRes.y;
  4073. textAlign = tmpTextPosCalcRes.align;
  4074. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  4075. var textOrigin = textConfig.origin;
  4076. if (textOrigin && textConfig.rotation != null) {
  4077. var relOriginX = void 0;
  4078. var relOriginY = void 0;
  4079. if (textOrigin === 'center') {
  4080. relOriginX = layoutRect.width * 0.5;
  4081. relOriginY = layoutRect.height * 0.5;
  4082. }
  4083. else {
  4084. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  4085. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  4086. }
  4087. innerOrigin = true;
  4088. attachedTransform.originX = -attachedTransform.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  4089. attachedTransform.originY = -attachedTransform.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  4090. }
  4091. }
  4092. if (textConfig.rotation != null) {
  4093. attachedTransform.rotation = textConfig.rotation;
  4094. }
  4095. var textOffset = textConfig.offset;
  4096. if (textOffset) {
  4097. attachedTransform.x += textOffset[0];
  4098. attachedTransform.y += textOffset[1];
  4099. if (!innerOrigin) {
  4100. attachedTransform.originX = -textOffset[0];
  4101. attachedTransform.originY = -textOffset[1];
  4102. }
  4103. }
  4104. var isInside = textConfig.inside == null
  4105. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  4106. : textConfig.inside;
  4107. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  4108. var textFill = void 0;
  4109. var textStroke = void 0;
  4110. var autoStroke = void 0;
  4111. if (isInside && this.canBeInsideText()) {
  4112. textFill = textConfig.insideFill;
  4113. textStroke = textConfig.insideStroke;
  4114. if (textFill == null || textFill === 'auto') {
  4115. textFill = this.getInsideTextFill();
  4116. }
  4117. if (textStroke == null || textStroke === 'auto') {
  4118. textStroke = this.getInsideTextStroke(textFill);
  4119. autoStroke = true;
  4120. }
  4121. }
  4122. else {
  4123. textFill = textConfig.outsideFill;
  4124. textStroke = textConfig.outsideStroke;
  4125. if (textFill == null || textFill === 'auto') {
  4126. textFill = this.getOutsideFill();
  4127. }
  4128. if (textStroke == null || textStroke === 'auto') {
  4129. textStroke = this.getOutsideStroke(textFill);
  4130. autoStroke = true;
  4131. }
  4132. }
  4133. textFill = textFill || '#000';
  4134. if (textFill !== innerTextDefaultStyle.fill
  4135. || textStroke !== innerTextDefaultStyle.stroke
  4136. || autoStroke !== innerTextDefaultStyle.autoStroke
  4137. || textAlign !== innerTextDefaultStyle.align
  4138. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  4139. textStyleChanged = true;
  4140. innerTextDefaultStyle.fill = textFill;
  4141. innerTextDefaultStyle.stroke = textStroke;
  4142. innerTextDefaultStyle.autoStroke = autoStroke;
  4143. innerTextDefaultStyle.align = textAlign;
  4144. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  4145. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  4146. }
  4147. if (textStyleChanged) {
  4148. textEl.dirtyStyle();
  4149. }
  4150. textEl.markRedraw();
  4151. }
  4152. };
  4153. Element.prototype.canBeInsideText = function () {
  4154. return true;
  4155. };
  4156. Element.prototype.getInsideTextFill = function () {
  4157. return '#fff';
  4158. };
  4159. Element.prototype.getInsideTextStroke = function (textFill) {
  4160. return '#000';
  4161. };
  4162. Element.prototype.getOutsideFill = function () {
  4163. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  4164. };
  4165. Element.prototype.getOutsideStroke = function (textFill) {
  4166. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  4167. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  4168. if (!colorArr) {
  4169. colorArr = [255, 255, 255, 1];
  4170. }
  4171. var alpha = colorArr[3];
  4172. var isDark = this.__zr.isDarkMode();
  4173. for (var i = 0; i < 3; i++) {
  4174. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  4175. }
  4176. colorArr[3] = 1;
  4177. return stringify(colorArr, 'rgba');
  4178. };
  4179. Element.prototype.traverse = function (cb, context) { };
  4180. Element.prototype.attrKV = function (key, value) {
  4181. if (key === 'textConfig') {
  4182. this.setTextConfig(value);
  4183. }
  4184. else if (key === 'textContent') {
  4185. this.setTextContent(value);
  4186. }
  4187. else if (key === 'clipPath') {
  4188. this.setClipPath(value);
  4189. }
  4190. else if (key === 'extra') {
  4191. this.extra = this.extra || {};
  4192. extend(this.extra, value);
  4193. }
  4194. else {
  4195. this[key] = value;
  4196. }
  4197. };
  4198. Element.prototype.hide = function () {
  4199. this.ignore = true;
  4200. this.markRedraw();
  4201. };
  4202. Element.prototype.show = function () {
  4203. this.ignore = false;
  4204. this.markRedraw();
  4205. };
  4206. Element.prototype.attr = function (keyOrObj, value) {
  4207. if (typeof keyOrObj === 'string') {
  4208. this.attrKV(keyOrObj, value);
  4209. }
  4210. else if (isObject(keyOrObj)) {
  4211. var obj = keyOrObj;
  4212. var keysArr = keys(obj);
  4213. for (var i = 0; i < keysArr.length; i++) {
  4214. var key = keysArr[i];
  4215. this.attrKV(key, keyOrObj[key]);
  4216. }
  4217. }
  4218. this.markRedraw();
  4219. return this;
  4220. };
  4221. Element.prototype.saveCurrentToNormalState = function (toState) {
  4222. this._innerSaveToNormal(toState);
  4223. var normalState = this._normalState;
  4224. for (var i = 0; i < this.animators.length; i++) {
  4225. var animator = this.animators[i];
  4226. var fromStateTransition = animator.__fromStateTransition;
  4227. if (fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  4228. continue;
  4229. }
  4230. var targetName = animator.targetName;
  4231. var target = targetName
  4232. ? normalState[targetName] : normalState;
  4233. animator.saveFinalToTarget(target);
  4234. }
  4235. };
  4236. Element.prototype._innerSaveToNormal = function (toState) {
  4237. var normalState = this._normalState;
  4238. if (!normalState) {
  4239. normalState = this._normalState = {};
  4240. }
  4241. if (toState.textConfig && !normalState.textConfig) {
  4242. normalState.textConfig = this.textConfig;
  4243. }
  4244. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  4245. };
  4246. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  4247. for (var i = 0; i < primaryKeys.length; i++) {
  4248. var key = primaryKeys[i];
  4249. if (toState[key] != null && !(key in normalState)) {
  4250. normalState[key] = this[key];
  4251. }
  4252. }
  4253. };
  4254. Element.prototype.hasState = function () {
  4255. return this.currentStates.length > 0;
  4256. };
  4257. Element.prototype.getState = function (name) {
  4258. return this.states[name];
  4259. };
  4260. Element.prototype.ensureState = function (name) {
  4261. var states = this.states;
  4262. if (!states[name]) {
  4263. states[name] = {};
  4264. }
  4265. return states[name];
  4266. };
  4267. Element.prototype.clearStates = function (noAnimation) {
  4268. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  4269. };
  4270. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation) {
  4271. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  4272. var hasStates = this.hasState();
  4273. if (!hasStates && toNormalState) {
  4274. return;
  4275. }
  4276. var currentStates = this.currentStates;
  4277. var animationCfg = this.stateTransition;
  4278. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  4279. return;
  4280. }
  4281. var state;
  4282. if (this.stateProxy && !toNormalState) {
  4283. state = this.stateProxy(stateName);
  4284. }
  4285. if (!state) {
  4286. state = (this.states && this.states[stateName]);
  4287. }
  4288. if (!state && !toNormalState) {
  4289. logError("State " + stateName + " not exists.");
  4290. return;
  4291. }
  4292. if (!toNormalState) {
  4293. this.saveCurrentToNormalState(state);
  4294. }
  4295. var useHoverLayer = !!(state && state.hoverLayer);
  4296. if (useHoverLayer) {
  4297. this._toggleHoverLayerFlag(true);
  4298. }
  4299. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  4300. if (this._textContent) {
  4301. this._textContent.useState(stateName, keepCurrentStates);
  4302. }
  4303. if (this._textGuide) {
  4304. this._textGuide.useState(stateName, keepCurrentStates);
  4305. }
  4306. if (toNormalState) {
  4307. this.currentStates = [];
  4308. this._normalState = {};
  4309. }
  4310. else {
  4311. if (!keepCurrentStates) {
  4312. this.currentStates = [stateName];
  4313. }
  4314. else {
  4315. this.currentStates.push(stateName);
  4316. }
  4317. }
  4318. this._updateAnimationTargets();
  4319. this.markRedraw();
  4320. if (!useHoverLayer && this.__inHover) {
  4321. this._toggleHoverLayerFlag(false);
  4322. this.__dirty &= ~Element.REDARAW_BIT;
  4323. }
  4324. return state;
  4325. };
  4326. Element.prototype.useStates = function (states, noAnimation) {
  4327. if (!states.length) {
  4328. this.clearStates();
  4329. }
  4330. else {
  4331. var stateObjects = [];
  4332. var currentStates = this.currentStates;
  4333. var len = states.length;
  4334. var notChange = len === currentStates.length;
  4335. if (notChange) {
  4336. for (var i = 0; i < len; i++) {
  4337. if (states[i] !== currentStates[i]) {
  4338. notChange = false;
  4339. break;
  4340. }
  4341. }
  4342. }
  4343. if (notChange) {
  4344. return;
  4345. }
  4346. for (var i = 0; i < len; i++) {
  4347. var stateName = states[i];
  4348. var stateObj = void 0;
  4349. if (this.stateProxy) {
  4350. stateObj = this.stateProxy(stateName, states);
  4351. }
  4352. if (!stateObj) {
  4353. stateObj = this.states[stateName];
  4354. }
  4355. if (stateObj) {
  4356. stateObjects.push(stateObj);
  4357. }
  4358. }
  4359. var useHoverLayer = !!(stateObjects[len - 1] && stateObjects[len - 1].hoverLayer);
  4360. if (useHoverLayer) {
  4361. this._toggleHoverLayerFlag(true);
  4362. }
  4363. var mergedState = this._mergeStates(stateObjects);
  4364. var animationCfg = this.stateTransition;
  4365. this.saveCurrentToNormalState(mergedState);
  4366. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  4367. if (this._textContent) {
  4368. this._textContent.useStates(states);
  4369. }
  4370. if (this._textGuide) {
  4371. this._textGuide.useStates(states);
  4372. }
  4373. this._updateAnimationTargets();
  4374. this.currentStates = states.slice();
  4375. this.markRedraw();
  4376. if (!useHoverLayer && this.__inHover) {
  4377. this._toggleHoverLayerFlag(false);
  4378. this.__dirty &= ~Element.REDARAW_BIT;
  4379. }
  4380. }
  4381. };
  4382. Element.prototype._updateAnimationTargets = function () {
  4383. for (var i = 0; i < this.animators.length; i++) {
  4384. var animator = this.animators[i];
  4385. if (animator.targetName) {
  4386. animator.changeTarget(this[animator.targetName]);
  4387. }
  4388. }
  4389. };
  4390. Element.prototype.removeState = function (state) {
  4391. var idx = indexOf(this.currentStates, state);
  4392. if (idx >= 0) {
  4393. var currentStates = this.currentStates.slice();
  4394. currentStates.splice(idx, 1);
  4395. this.useStates(currentStates);
  4396. }
  4397. };
  4398. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  4399. var currentStates = this.currentStates.slice();
  4400. var idx = indexOf(currentStates, oldState);
  4401. var newStateExists = indexOf(currentStates, newState) >= 0;
  4402. if (idx >= 0) {
  4403. if (!newStateExists) {
  4404. currentStates[idx] = newState;
  4405. }
  4406. else {
  4407. currentStates.splice(idx, 1);
  4408. }
  4409. }
  4410. else if (forceAdd && !newStateExists) {
  4411. currentStates.push(newState);
  4412. }
  4413. this.useStates(currentStates);
  4414. };
  4415. Element.prototype.toggleState = function (state, enable) {
  4416. if (enable) {
  4417. this.useState(state, true);
  4418. }
  4419. else {
  4420. this.removeState(state);
  4421. }
  4422. };
  4423. Element.prototype._mergeStates = function (states) {
  4424. var mergedState = {};
  4425. var mergedTextConfig;
  4426. for (var i = 0; i < states.length; i++) {
  4427. var state = states[i];
  4428. extend(mergedState, state);
  4429. if (state.textConfig) {
  4430. mergedTextConfig = mergedTextConfig || {};
  4431. extend(mergedTextConfig, state.textConfig);
  4432. }
  4433. }
  4434. if (mergedTextConfig) {
  4435. mergedState.textConfig = mergedTextConfig;
  4436. }
  4437. return mergedState;
  4438. };
  4439. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  4440. var needsRestoreToNormal = !(state && keepCurrentStates);
  4441. if (state && state.textConfig) {
  4442. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  4443. extend(this.textConfig, state.textConfig);
  4444. }
  4445. else if (needsRestoreToNormal) {
  4446. if (normalState.textConfig) {
  4447. this.textConfig = normalState.textConfig;
  4448. }
  4449. }
  4450. var transitionTarget = {};
  4451. var hasTransition = false;
  4452. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  4453. var key = PRIMARY_STATES_KEYS[i];
  4454. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  4455. if (state && state[key] != null) {
  4456. if (propNeedsTransition) {
  4457. hasTransition = true;
  4458. transitionTarget[key] = state[key];
  4459. }
  4460. else {
  4461. this[key] = state[key];
  4462. }
  4463. }
  4464. else if (needsRestoreToNormal) {
  4465. if (normalState[key] != null) {
  4466. if (propNeedsTransition) {
  4467. hasTransition = true;
  4468. transitionTarget[key] = normalState[key];
  4469. }
  4470. else {
  4471. this[key] = normalState[key];
  4472. }
  4473. }
  4474. }
  4475. }
  4476. if (!transition) {
  4477. for (var i = 0; i < this.animators.length; i++) {
  4478. var animator = this.animators[i];
  4479. var targetName = animator.targetName;
  4480. animator.__changeFinalValue(targetName
  4481. ? (state || normalState)[targetName]
  4482. : (state || normalState));
  4483. }
  4484. }
  4485. if (hasTransition) {
  4486. this._transitionState(stateName, transitionTarget, animationCfg);
  4487. }
  4488. };
  4489. Element.prototype._attachComponent = function (componentEl) {
  4490. if (componentEl.__zr && !componentEl.__hostTarget) {
  4491. throw new Error('Text element has been added to zrender.');
  4492. }
  4493. if (componentEl === this) {
  4494. throw new Error('Recursive component attachment.');
  4495. }
  4496. var zr = this.__zr;
  4497. if (zr) {
  4498. componentEl.addSelfToZr(zr);
  4499. }
  4500. componentEl.__zr = zr;
  4501. componentEl.__hostTarget = this;
  4502. };
  4503. Element.prototype._detachComponent = function (componentEl) {
  4504. if (componentEl.__zr) {
  4505. componentEl.removeSelfFromZr(componentEl.__zr);
  4506. }
  4507. componentEl.__zr = null;
  4508. componentEl.__hostTarget = null;
  4509. };
  4510. Element.prototype.getClipPath = function () {
  4511. return this._clipPath;
  4512. };
  4513. Element.prototype.setClipPath = function (clipPath) {
  4514. if (this._clipPath && this._clipPath !== clipPath) {
  4515. this.removeClipPath();
  4516. }
  4517. this._attachComponent(clipPath);
  4518. this._clipPath = clipPath;
  4519. this.markRedraw();
  4520. };
  4521. Element.prototype.removeClipPath = function () {
  4522. var clipPath = this._clipPath;
  4523. if (clipPath) {
  4524. this._detachComponent(clipPath);
  4525. this._clipPath = null;
  4526. this.markRedraw();
  4527. }
  4528. };
  4529. Element.prototype.getTextContent = function () {
  4530. return this._textContent;
  4531. };
  4532. Element.prototype.setTextContent = function (textEl) {
  4533. var previousTextContent = this._textContent;
  4534. if (previousTextContent === textEl) {
  4535. return;
  4536. }
  4537. if (previousTextContent && previousTextContent !== textEl) {
  4538. this.removeTextContent();
  4539. }
  4540. if (textEl.__zr && !textEl.__hostTarget) {
  4541. throw new Error('Text element has been added to zrender.');
  4542. }
  4543. textEl.attachedTransform = new Transformable();
  4544. this._attachComponent(textEl);
  4545. this._textContent = textEl;
  4546. this.markRedraw();
  4547. };
  4548. Element.prototype.setTextConfig = function (cfg) {
  4549. if (!this.textConfig) {
  4550. this.textConfig = {};
  4551. }
  4552. extend(this.textConfig, cfg);
  4553. this.markRedraw();
  4554. };
  4555. Element.prototype.removeTextContent = function () {
  4556. var textEl = this._textContent;
  4557. if (textEl) {
  4558. textEl.attachedTransform = null;
  4559. this._detachComponent(textEl);
  4560. this._textContent = null;
  4561. this._innerTextDefaultStyle = null;
  4562. this.markRedraw();
  4563. }
  4564. };
  4565. Element.prototype.getTextGuideLine = function () {
  4566. return this._textGuide;
  4567. };
  4568. Element.prototype.setTextGuideLine = function (guideLine) {
  4569. if (this._textGuide && this._textGuide !== guideLine) {
  4570. this.removeTextGuideLine();
  4571. }
  4572. this._attachComponent(guideLine);
  4573. this._textGuide = guideLine;
  4574. this.markRedraw();
  4575. };
  4576. Element.prototype.removeTextGuideLine = function () {
  4577. var textGuide = this._textGuide;
  4578. if (textGuide) {
  4579. this._detachComponent(textGuide);
  4580. this._textGuide = null;
  4581. this.markRedraw();
  4582. }
  4583. };
  4584. Element.prototype.markRedraw = function () {
  4585. this.__dirty |= Element.REDARAW_BIT;
  4586. var zr = this.__zr;
  4587. if (zr) {
  4588. if (this.__inHover) {
  4589. zr.refreshHover();
  4590. }
  4591. else {
  4592. zr.refresh();
  4593. }
  4594. }
  4595. if (this.__hostTarget) {
  4596. this.__hostTarget.markRedraw();
  4597. }
  4598. };
  4599. Element.prototype.dirty = function () {
  4600. this.markRedraw();
  4601. };
  4602. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  4603. this.__inHover = inHover;
  4604. var textContent = this._textContent;
  4605. var textGuide = this._textGuide;
  4606. if (textContent) {
  4607. textContent.__inHover = inHover;
  4608. }
  4609. if (textGuide) {
  4610. textGuide.__inHover = inHover;
  4611. }
  4612. };
  4613. Element.prototype.addSelfToZr = function (zr) {
  4614. this.__zr = zr;
  4615. var animators = this.animators;
  4616. if (animators) {
  4617. for (var i = 0; i < animators.length; i++) {
  4618. zr.animation.addAnimator(animators[i]);
  4619. }
  4620. }
  4621. if (this._clipPath) {
  4622. this._clipPath.addSelfToZr(zr);
  4623. }
  4624. if (this._textContent) {
  4625. this._textContent.addSelfToZr(zr);
  4626. }
  4627. if (this._textGuide) {
  4628. this._textGuide.addSelfToZr(zr);
  4629. }
  4630. };
  4631. Element.prototype.removeSelfFromZr = function (zr) {
  4632. this.__zr = null;
  4633. var animators = this.animators;
  4634. if (animators) {
  4635. for (var i = 0; i < animators.length; i++) {
  4636. zr.animation.removeAnimator(animators[i]);
  4637. }
  4638. }
  4639. if (this._clipPath) {
  4640. this._clipPath.removeSelfFromZr(zr);
  4641. }
  4642. if (this._textContent) {
  4643. this._textContent.removeSelfFromZr(zr);
  4644. }
  4645. if (this._textGuide) {
  4646. this._textGuide.removeSelfFromZr(zr);
  4647. }
  4648. };
  4649. Element.prototype.animate = function (key, loop) {
  4650. var target = key ? this[key] : this;
  4651. if (!target) {
  4652. logError('Property "'
  4653. + key
  4654. + '" is not existed in element '
  4655. + this.id);
  4656. return;
  4657. }
  4658. var animator = new Animator(target, loop);
  4659. this.addAnimator(animator, key);
  4660. return animator;
  4661. };
  4662. Element.prototype.addAnimator = function (animator, key) {
  4663. var zr = this.__zr;
  4664. var el = this;
  4665. animator.during(function () {
  4666. el.updateDuringAnimation(key);
  4667. }).done(function () {
  4668. var animators = el.animators;
  4669. var idx = indexOf(animators, animator);
  4670. if (idx >= 0) {
  4671. animators.splice(idx, 1);
  4672. }
  4673. });
  4674. this.animators.push(animator);
  4675. if (zr) {
  4676. zr.animation.addAnimator(animator);
  4677. }
  4678. zr && zr.wakeUp();
  4679. };
  4680. Element.prototype.updateDuringAnimation = function (key) {
  4681. this.markRedraw();
  4682. };
  4683. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  4684. var animators = this.animators;
  4685. var len = animators.length;
  4686. var leftAnimators = [];
  4687. for (var i = 0; i < len; i++) {
  4688. var animator = animators[i];
  4689. if (!scope || scope === animator.scope) {
  4690. animator.stop(forwardToLast);
  4691. }
  4692. else {
  4693. leftAnimators.push(animator);
  4694. }
  4695. }
  4696. this.animators = leftAnimators;
  4697. return this;
  4698. };
  4699. Element.prototype.animateTo = function (target, cfg, animationProps) {
  4700. animateTo(this, target, cfg, animationProps);
  4701. };
  4702. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  4703. animateTo(this, target, cfg, animationProps, true);
  4704. };
  4705. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  4706. var animators = animateTo(this, target, cfg, animationProps);
  4707. for (var i = 0; i < animators.length; i++) {
  4708. animators[i].__fromStateTransition = stateName;
  4709. }
  4710. };
  4711. Element.prototype.getBoundingRect = function () {
  4712. return null;
  4713. };
  4714. Element.prototype.getPaintRect = function () {
  4715. return null;
  4716. };
  4717. Element.REDARAW_BIT = 1;
  4718. Element.initDefaultProps = (function () {
  4719. var elProto = Element.prototype;
  4720. elProto.type = 'element';
  4721. elProto.name = '';
  4722. elProto.ignore = false;
  4723. elProto.silent = false;
  4724. elProto.isGroup = false;
  4725. elProto.draggable = false;
  4726. elProto.dragging = false;
  4727. elProto.ignoreClip = false;
  4728. elProto.__inHover = false;
  4729. elProto.__dirty = Element.REDARAW_BIT;
  4730. var logs = {};
  4731. function logDeprecatedError(key, xKey, yKey) {
  4732. if (!logs[key + xKey + yKey]) {
  4733. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  4734. logs[key + xKey + yKey] = true;
  4735. }
  4736. }
  4737. function createLegacyProperty(key, privateKey, xKey, yKey) {
  4738. Object.defineProperty(elProto, key, {
  4739. get: function () {
  4740. logDeprecatedError(key, xKey, yKey);
  4741. if (!this[privateKey]) {
  4742. var pos = this[privateKey] = [];
  4743. enhanceArray(this, pos);
  4744. }
  4745. return this[privateKey];
  4746. },
  4747. set: function (pos) {
  4748. logDeprecatedError(key, xKey, yKey);
  4749. this[xKey] = pos[0];
  4750. this[yKey] = pos[1];
  4751. this[privateKey] = pos;
  4752. enhanceArray(this, pos);
  4753. }
  4754. });
  4755. function enhanceArray(self, pos) {
  4756. Object.defineProperty(pos, 0, {
  4757. get: function () {
  4758. return self[xKey];
  4759. },
  4760. set: function (val) {
  4761. self[xKey] = val;
  4762. }
  4763. });
  4764. Object.defineProperty(pos, 1, {
  4765. get: function () {
  4766. return self[yKey];
  4767. },
  4768. set: function (val) {
  4769. self[yKey] = val;
  4770. }
  4771. });
  4772. }
  4773. }
  4774. if (Object.defineProperty && (!env.browser.ie || env.browser.version > 8)) {
  4775. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  4776. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  4777. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  4778. }
  4779. })();
  4780. return Element;
  4781. }());
  4782. mixin(Element, Eventful);
  4783. mixin(Element, Transformable);
  4784. function animateTo(animatable, target, cfg, animationProps, reverse) {
  4785. cfg = cfg || {};
  4786. var animators = [];
  4787. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  4788. var finishCount = animators.length;
  4789. var doneHappened = false;
  4790. var cfgDone = cfg.done;
  4791. var cfgAborted = cfg.aborted;
  4792. var doneCb = function () {
  4793. doneHappened = true;
  4794. finishCount--;
  4795. if (finishCount <= 0) {
  4796. doneHappened
  4797. ? (cfgDone && cfgDone())
  4798. : (cfgAborted && cfgAborted());
  4799. }
  4800. };
  4801. var abortedCb = function () {
  4802. finishCount--;
  4803. if (finishCount <= 0) {
  4804. doneHappened
  4805. ? (cfgDone && cfgDone())
  4806. : (cfgAborted && cfgAborted());
  4807. }
  4808. };
  4809. if (!finishCount) {
  4810. cfgDone && cfgDone();
  4811. }
  4812. if (animators.length > 0 && cfg.during) {
  4813. animators[0].during(function (target, percent) {
  4814. cfg.during(percent);
  4815. });
  4816. }
  4817. for (var i = 0; i < animators.length; i++) {
  4818. var animator = animators[i];
  4819. if (doneCb) {
  4820. animator.done(doneCb);
  4821. }
  4822. if (abortedCb) {
  4823. animator.aborted(abortedCb);
  4824. }
  4825. animator.start(cfg.easing, cfg.force);
  4826. }
  4827. return animators;
  4828. }
  4829. function copyArrShallow(source, target, len) {
  4830. for (var i = 0; i < len; i++) {
  4831. source[i] = target[i];
  4832. }
  4833. }
  4834. function is2DArray(value) {
  4835. return isArrayLike(value[0]);
  4836. }
  4837. function copyValue(target, source, key) {
  4838. if (isArrayLike(source[key])) {
  4839. if (!isArrayLike(target[key])) {
  4840. target[key] = [];
  4841. }
  4842. if (isTypedArray(source[key])) {
  4843. var len = source[key].length;
  4844. if (target[key].length !== len) {
  4845. target[key] = new (source[key].constructor)(len);
  4846. copyArrShallow(target[key], source[key], len);
  4847. }
  4848. }
  4849. else {
  4850. var sourceArr = source[key];
  4851. var targetArr = target[key];
  4852. var len0 = sourceArr.length;
  4853. if (is2DArray(sourceArr)) {
  4854. var len1 = sourceArr[0].length;
  4855. for (var i = 0; i < len0; i++) {
  4856. if (!targetArr[i]) {
  4857. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  4858. }
  4859. else {
  4860. copyArrShallow(targetArr[i], sourceArr[i], len1);
  4861. }
  4862. }
  4863. }
  4864. else {
  4865. copyArrShallow(targetArr, sourceArr, len0);
  4866. }
  4867. targetArr.length = sourceArr.length;
  4868. }
  4869. }
  4870. else {
  4871. target[key] = source[key];
  4872. }
  4873. }
  4874. function animateToShallow(animatable, topKey, source, target, cfg, animationProps, animators, reverse) {
  4875. var animatableKeys = [];
  4876. var changedKeys = [];
  4877. var targetKeys = keys(target);
  4878. var duration = cfg.duration;
  4879. var delay = cfg.delay;
  4880. var additive = cfg.additive;
  4881. var setToFinal = cfg.setToFinal;
  4882. var animateAll = !isObject(animationProps);
  4883. for (var k = 0; k < targetKeys.length; k++) {
  4884. var innerKey = targetKeys[k];
  4885. if (source[innerKey] != null
  4886. && target[innerKey] != null
  4887. && (animateAll || animationProps[innerKey])) {
  4888. if (isObject(target[innerKey]) && !isArrayLike(target[innerKey])) {
  4889. if (topKey) {
  4890. if (!reverse) {
  4891. source[innerKey] = target[innerKey];
  4892. animatable.updateDuringAnimation(topKey);
  4893. }
  4894. continue;
  4895. }
  4896. animateToShallow(animatable, innerKey, source[innerKey], target[innerKey], cfg, animationProps && animationProps[innerKey], animators, reverse);
  4897. }
  4898. else {
  4899. animatableKeys.push(innerKey);
  4900. changedKeys.push(innerKey);
  4901. }
  4902. }
  4903. else if (!reverse) {
  4904. source[innerKey] = target[innerKey];
  4905. animatable.updateDuringAnimation(topKey);
  4906. changedKeys.push(innerKey);
  4907. }
  4908. }
  4909. var keyLen = animatableKeys.length;
  4910. if (keyLen > 0
  4911. || (cfg.force && !animators.length)) {
  4912. var existsAnimators = animatable.animators;
  4913. var existsAnimatorsOnSameTarget = [];
  4914. for (var i = 0; i < existsAnimators.length; i++) {
  4915. if (existsAnimators[i].targetName === topKey) {
  4916. existsAnimatorsOnSameTarget.push(existsAnimators[i]);
  4917. }
  4918. }
  4919. if (!additive && existsAnimatorsOnSameTarget.length) {
  4920. for (var i = 0; i < existsAnimatorsOnSameTarget.length; i++) {
  4921. var allAborted = existsAnimatorsOnSameTarget[i].stopTracks(changedKeys);
  4922. if (allAborted) {
  4923. var idx = indexOf(existsAnimators, existsAnimatorsOnSameTarget[i]);
  4924. existsAnimators.splice(idx, 1);
  4925. }
  4926. }
  4927. }
  4928. var revertedSource = void 0;
  4929. var reversedTarget = void 0;
  4930. var sourceClone = void 0;
  4931. if (reverse) {
  4932. reversedTarget = {};
  4933. if (setToFinal) {
  4934. revertedSource = {};
  4935. }
  4936. for (var i = 0; i < keyLen; i++) {
  4937. var innerKey = animatableKeys[i];
  4938. reversedTarget[innerKey] = source[innerKey];
  4939. if (setToFinal) {
  4940. revertedSource[innerKey] = target[innerKey];
  4941. }
  4942. else {
  4943. source[innerKey] = target[innerKey];
  4944. }
  4945. }
  4946. }
  4947. else if (setToFinal) {
  4948. sourceClone = {};
  4949. for (var i = 0; i < keyLen; i++) {
  4950. var innerKey = animatableKeys[i];
  4951. sourceClone[innerKey] = cloneValue(source[innerKey]);
  4952. copyValue(source, target, innerKey);
  4953. }
  4954. }
  4955. var animator = new Animator(source, false, additive ? existsAnimatorsOnSameTarget : null);
  4956. animator.targetName = topKey;
  4957. if (cfg.scope) {
  4958. animator.scope = cfg.scope;
  4959. }
  4960. if (setToFinal && revertedSource) {
  4961. animator.whenWithKeys(0, revertedSource, animatableKeys);
  4962. }
  4963. if (sourceClone) {
  4964. animator.whenWithKeys(0, sourceClone, animatableKeys);
  4965. }
  4966. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animatableKeys).delay(delay || 0);
  4967. animatable.addAnimator(animator, topKey);
  4968. animators.push(animator);
  4969. }
  4970. }
  4971. var DEFAULT_MIN_MERGE = 32;
  4972. var DEFAULT_MIN_GALLOPING = 7;
  4973. function minRunLength(n) {
  4974. var r = 0;
  4975. while (n >= DEFAULT_MIN_MERGE) {
  4976. r |= n & 1;
  4977. n >>= 1;
  4978. }
  4979. return n + r;
  4980. }
  4981. function makeAscendingRun(array, lo, hi, compare) {
  4982. var runHi = lo + 1;
  4983. if (runHi === hi) {
  4984. return 1;
  4985. }
  4986. if (compare(array[runHi++], array[lo]) < 0) {
  4987. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4988. runHi++;
  4989. }
  4990. reverseRun(array, lo, runHi);
  4991. }
  4992. else {
  4993. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4994. runHi++;
  4995. }
  4996. }
  4997. return runHi - lo;
  4998. }
  4999. function reverseRun(array, lo, hi) {
  5000. hi--;
  5001. while (lo < hi) {
  5002. var t = array[lo];
  5003. array[lo++] = array[hi];
  5004. array[hi--] = t;
  5005. }
  5006. }
  5007. function binaryInsertionSort(array, lo, hi, start, compare) {
  5008. if (start === lo) {
  5009. start++;
  5010. }
  5011. for (; start < hi; start++) {
  5012. var pivot = array[start];
  5013. var left = lo;
  5014. var right = start;
  5015. var mid;
  5016. while (left < right) {
  5017. mid = left + right >>> 1;
  5018. if (compare(pivot, array[mid]) < 0) {
  5019. right = mid;
  5020. }
  5021. else {
  5022. left = mid + 1;
  5023. }
  5024. }
  5025. var n = start - left;
  5026. switch (n) {
  5027. case 3:
  5028. array[left + 3] = array[left + 2];
  5029. case 2:
  5030. array[left + 2] = array[left + 1];
  5031. case 1:
  5032. array[left + 1] = array[left];
  5033. break;
  5034. default:
  5035. while (n > 0) {
  5036. array[left + n] = array[left + n - 1];
  5037. n--;
  5038. }
  5039. }
  5040. array[left] = pivot;
  5041. }
  5042. }
  5043. function gallopLeft(value, array, start, length, hint, compare) {
  5044. var lastOffset = 0;
  5045. var maxOffset = 0;
  5046. var offset = 1;
  5047. if (compare(value, array[start + hint]) > 0) {
  5048. maxOffset = length - hint;
  5049. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5050. lastOffset = offset;
  5051. offset = (offset << 1) + 1;
  5052. if (offset <= 0) {
  5053. offset = maxOffset;
  5054. }
  5055. }
  5056. if (offset > maxOffset) {
  5057. offset = maxOffset;
  5058. }
  5059. lastOffset += hint;
  5060. offset += hint;
  5061. }
  5062. else {
  5063. maxOffset = hint + 1;
  5064. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5065. lastOffset = offset;
  5066. offset = (offset << 1) + 1;
  5067. if (offset <= 0) {
  5068. offset = maxOffset;
  5069. }
  5070. }
  5071. if (offset > maxOffset) {
  5072. offset = maxOffset;
  5073. }
  5074. var tmp = lastOffset;
  5075. lastOffset = hint - offset;
  5076. offset = hint - tmp;
  5077. }
  5078. lastOffset++;
  5079. while (lastOffset < offset) {
  5080. var m = lastOffset + (offset - lastOffset >>> 1);
  5081. if (compare(value, array[start + m]) > 0) {
  5082. lastOffset = m + 1;
  5083. }
  5084. else {
  5085. offset = m;
  5086. }
  5087. }
  5088. return offset;
  5089. }
  5090. function gallopRight(value, array, start, length, hint, compare) {
  5091. var lastOffset = 0;
  5092. var maxOffset = 0;
  5093. var offset = 1;
  5094. if (compare(value, array[start + hint]) < 0) {
  5095. maxOffset = hint + 1;
  5096. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5097. lastOffset = offset;
  5098. offset = (offset << 1) + 1;
  5099. if (offset <= 0) {
  5100. offset = maxOffset;
  5101. }
  5102. }
  5103. if (offset > maxOffset) {
  5104. offset = maxOffset;
  5105. }
  5106. var tmp = lastOffset;
  5107. lastOffset = hint - offset;
  5108. offset = hint - tmp;
  5109. }
  5110. else {
  5111. maxOffset = length - hint;
  5112. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5113. lastOffset = offset;
  5114. offset = (offset << 1) + 1;
  5115. if (offset <= 0) {
  5116. offset = maxOffset;
  5117. }
  5118. }
  5119. if (offset > maxOffset) {
  5120. offset = maxOffset;
  5121. }
  5122. lastOffset += hint;
  5123. offset += hint;
  5124. }
  5125. lastOffset++;
  5126. while (lastOffset < offset) {
  5127. var m = lastOffset + (offset - lastOffset >>> 1);
  5128. if (compare(value, array[start + m]) < 0) {
  5129. offset = m;
  5130. }
  5131. else {
  5132. lastOffset = m + 1;
  5133. }
  5134. }
  5135. return offset;
  5136. }
  5137. function TimSort(array, compare) {
  5138. var minGallop = DEFAULT_MIN_GALLOPING;
  5139. var length = 0;
  5140. var runStart;
  5141. var runLength;
  5142. var stackSize = 0;
  5143. length = array.length;
  5144. var tmp = [];
  5145. runStart = [];
  5146. runLength = [];
  5147. function pushRun(_runStart, _runLength) {
  5148. runStart[stackSize] = _runStart;
  5149. runLength[stackSize] = _runLength;
  5150. stackSize += 1;
  5151. }
  5152. function mergeRuns() {
  5153. while (stackSize > 1) {
  5154. var n = stackSize - 2;
  5155. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5156. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  5157. if (runLength[n - 1] < runLength[n + 1]) {
  5158. n--;
  5159. }
  5160. }
  5161. else if (runLength[n] > runLength[n + 1]) {
  5162. break;
  5163. }
  5164. mergeAt(n);
  5165. }
  5166. }
  5167. function forceMergeRuns() {
  5168. while (stackSize > 1) {
  5169. var n = stackSize - 2;
  5170. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5171. n--;
  5172. }
  5173. mergeAt(n);
  5174. }
  5175. }
  5176. function mergeAt(i) {
  5177. var start1 = runStart[i];
  5178. var length1 = runLength[i];
  5179. var start2 = runStart[i + 1];
  5180. var length2 = runLength[i + 1];
  5181. runLength[i] = length1 + length2;
  5182. if (i === stackSize - 3) {
  5183. runStart[i + 1] = runStart[i + 2];
  5184. runLength[i + 1] = runLength[i + 2];
  5185. }
  5186. stackSize--;
  5187. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5188. start1 += k;
  5189. length1 -= k;
  5190. if (length1 === 0) {
  5191. return;
  5192. }
  5193. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5194. if (length2 === 0) {
  5195. return;
  5196. }
  5197. if (length1 <= length2) {
  5198. mergeLow(start1, length1, start2, length2);
  5199. }
  5200. else {
  5201. mergeHigh(start1, length1, start2, length2);
  5202. }
  5203. }
  5204. function mergeLow(start1, length1, start2, length2) {
  5205. var i = 0;
  5206. for (i = 0; i < length1; i++) {
  5207. tmp[i] = array[start1 + i];
  5208. }
  5209. var cursor1 = 0;
  5210. var cursor2 = start2;
  5211. var dest = start1;
  5212. array[dest++] = array[cursor2++];
  5213. if (--length2 === 0) {
  5214. for (i = 0; i < length1; i++) {
  5215. array[dest + i] = tmp[cursor1 + i];
  5216. }
  5217. return;
  5218. }
  5219. if (length1 === 1) {
  5220. for (i = 0; i < length2; i++) {
  5221. array[dest + i] = array[cursor2 + i];
  5222. }
  5223. array[dest + length2] = tmp[cursor1];
  5224. return;
  5225. }
  5226. var _minGallop = minGallop;
  5227. var count1;
  5228. var count2;
  5229. var exit;
  5230. while (1) {
  5231. count1 = 0;
  5232. count2 = 0;
  5233. exit = false;
  5234. do {
  5235. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5236. array[dest++] = array[cursor2++];
  5237. count2++;
  5238. count1 = 0;
  5239. if (--length2 === 0) {
  5240. exit = true;
  5241. break;
  5242. }
  5243. }
  5244. else {
  5245. array[dest++] = tmp[cursor1++];
  5246. count1++;
  5247. count2 = 0;
  5248. if (--length1 === 1) {
  5249. exit = true;
  5250. break;
  5251. }
  5252. }
  5253. } while ((count1 | count2) < _minGallop);
  5254. if (exit) {
  5255. break;
  5256. }
  5257. do {
  5258. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5259. if (count1 !== 0) {
  5260. for (i = 0; i < count1; i++) {
  5261. array[dest + i] = tmp[cursor1 + i];
  5262. }
  5263. dest += count1;
  5264. cursor1 += count1;
  5265. length1 -= count1;
  5266. if (length1 <= 1) {
  5267. exit = true;
  5268. break;
  5269. }
  5270. }
  5271. array[dest++] = array[cursor2++];
  5272. if (--length2 === 0) {
  5273. exit = true;
  5274. break;
  5275. }
  5276. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5277. if (count2 !== 0) {
  5278. for (i = 0; i < count2; i++) {
  5279. array[dest + i] = array[cursor2 + i];
  5280. }
  5281. dest += count2;
  5282. cursor2 += count2;
  5283. length2 -= count2;
  5284. if (length2 === 0) {
  5285. exit = true;
  5286. break;
  5287. }
  5288. }
  5289. array[dest++] = tmp[cursor1++];
  5290. if (--length1 === 1) {
  5291. exit = true;
  5292. break;
  5293. }
  5294. _minGallop--;
  5295. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5296. if (exit) {
  5297. break;
  5298. }
  5299. if (_minGallop < 0) {
  5300. _minGallop = 0;
  5301. }
  5302. _minGallop += 2;
  5303. }
  5304. minGallop = _minGallop;
  5305. minGallop < 1 && (minGallop = 1);
  5306. if (length1 === 1) {
  5307. for (i = 0; i < length2; i++) {
  5308. array[dest + i] = array[cursor2 + i];
  5309. }
  5310. array[dest + length2] = tmp[cursor1];
  5311. }
  5312. else if (length1 === 0) {
  5313. throw new Error();
  5314. }
  5315. else {
  5316. for (i = 0; i < length1; i++) {
  5317. array[dest + i] = tmp[cursor1 + i];
  5318. }
  5319. }
  5320. }
  5321. function mergeHigh(start1, length1, start2, length2) {
  5322. var i = 0;
  5323. for (i = 0; i < length2; i++) {
  5324. tmp[i] = array[start2 + i];
  5325. }
  5326. var cursor1 = start1 + length1 - 1;
  5327. var cursor2 = length2 - 1;
  5328. var dest = start2 + length2 - 1;
  5329. var customCursor = 0;
  5330. var customDest = 0;
  5331. array[dest--] = array[cursor1--];
  5332. if (--length1 === 0) {
  5333. customCursor = dest - (length2 - 1);
  5334. for (i = 0; i < length2; i++) {
  5335. array[customCursor + i] = tmp[i];
  5336. }
  5337. return;
  5338. }
  5339. if (length2 === 1) {
  5340. dest -= length1;
  5341. cursor1 -= length1;
  5342. customDest = dest + 1;
  5343. customCursor = cursor1 + 1;
  5344. for (i = length1 - 1; i >= 0; i--) {
  5345. array[customDest + i] = array[customCursor + i];
  5346. }
  5347. array[dest] = tmp[cursor2];
  5348. return;
  5349. }
  5350. var _minGallop = minGallop;
  5351. while (true) {
  5352. var count1 = 0;
  5353. var count2 = 0;
  5354. var exit = false;
  5355. do {
  5356. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5357. array[dest--] = array[cursor1--];
  5358. count1++;
  5359. count2 = 0;
  5360. if (--length1 === 0) {
  5361. exit = true;
  5362. break;
  5363. }
  5364. }
  5365. else {
  5366. array[dest--] = tmp[cursor2--];
  5367. count2++;
  5368. count1 = 0;
  5369. if (--length2 === 1) {
  5370. exit = true;
  5371. break;
  5372. }
  5373. }
  5374. } while ((count1 | count2) < _minGallop);
  5375. if (exit) {
  5376. break;
  5377. }
  5378. do {
  5379. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5380. if (count1 !== 0) {
  5381. dest -= count1;
  5382. cursor1 -= count1;
  5383. length1 -= count1;
  5384. customDest = dest + 1;
  5385. customCursor = cursor1 + 1;
  5386. for (i = count1 - 1; i >= 0; i--) {
  5387. array[customDest + i] = array[customCursor + i];
  5388. }
  5389. if (length1 === 0) {
  5390. exit = true;
  5391. break;
  5392. }
  5393. }
  5394. array[dest--] = tmp[cursor2--];
  5395. if (--length2 === 1) {
  5396. exit = true;
  5397. break;
  5398. }
  5399. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5400. if (count2 !== 0) {
  5401. dest -= count2;
  5402. cursor2 -= count2;
  5403. length2 -= count2;
  5404. customDest = dest + 1;
  5405. customCursor = cursor2 + 1;
  5406. for (i = 0; i < count2; i++) {
  5407. array[customDest + i] = tmp[customCursor + i];
  5408. }
  5409. if (length2 <= 1) {
  5410. exit = true;
  5411. break;
  5412. }
  5413. }
  5414. array[dest--] = array[cursor1--];
  5415. if (--length1 === 0) {
  5416. exit = true;
  5417. break;
  5418. }
  5419. _minGallop--;
  5420. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5421. if (exit) {
  5422. break;
  5423. }
  5424. if (_minGallop < 0) {
  5425. _minGallop = 0;
  5426. }
  5427. _minGallop += 2;
  5428. }
  5429. minGallop = _minGallop;
  5430. if (minGallop < 1) {
  5431. minGallop = 1;
  5432. }
  5433. if (length2 === 1) {
  5434. dest -= length1;
  5435. cursor1 -= length1;
  5436. customDest = dest + 1;
  5437. customCursor = cursor1 + 1;
  5438. for (i = length1 - 1; i >= 0; i--) {
  5439. array[customDest + i] = array[customCursor + i];
  5440. }
  5441. array[dest] = tmp[cursor2];
  5442. }
  5443. else if (length2 === 0) {
  5444. throw new Error();
  5445. }
  5446. else {
  5447. customCursor = dest - (length2 - 1);
  5448. for (i = 0; i < length2; i++) {
  5449. array[customCursor + i] = tmp[i];
  5450. }
  5451. }
  5452. }
  5453. return {
  5454. mergeRuns: mergeRuns,
  5455. forceMergeRuns: forceMergeRuns,
  5456. pushRun: pushRun
  5457. };
  5458. }
  5459. function sort(array, compare, lo, hi) {
  5460. if (!lo) {
  5461. lo = 0;
  5462. }
  5463. if (!hi) {
  5464. hi = array.length;
  5465. }
  5466. var remaining = hi - lo;
  5467. if (remaining < 2) {
  5468. return;
  5469. }
  5470. var runLength = 0;
  5471. if (remaining < DEFAULT_MIN_MERGE) {
  5472. runLength = makeAscendingRun(array, lo, hi, compare);
  5473. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5474. return;
  5475. }
  5476. var ts = TimSort(array, compare);
  5477. var minRun = minRunLength(remaining);
  5478. do {
  5479. runLength = makeAscendingRun(array, lo, hi, compare);
  5480. if (runLength < minRun) {
  5481. var force = remaining;
  5482. if (force > minRun) {
  5483. force = minRun;
  5484. }
  5485. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5486. runLength = force;
  5487. }
  5488. ts.pushRun(lo, runLength);
  5489. ts.mergeRuns();
  5490. remaining -= runLength;
  5491. lo += runLength;
  5492. } while (remaining !== 0);
  5493. ts.forceMergeRuns();
  5494. }
  5495. var invalidZErrorLogged = false;
  5496. function logInvalidZError() {
  5497. if (invalidZErrorLogged) {
  5498. return;
  5499. }
  5500. invalidZErrorLogged = true;
  5501. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  5502. }
  5503. function shapeCompareFunc(a, b) {
  5504. if (a.zlevel === b.zlevel) {
  5505. if (a.z === b.z) {
  5506. return a.z2 - b.z2;
  5507. }
  5508. return a.z - b.z;
  5509. }
  5510. return a.zlevel - b.zlevel;
  5511. }
  5512. var Storage = (function () {
  5513. function Storage() {
  5514. this._roots = [];
  5515. this._displayList = [];
  5516. this._displayListLen = 0;
  5517. this.displayableSortFunc = shapeCompareFunc;
  5518. }
  5519. Storage.prototype.traverse = function (cb, context) {
  5520. for (var i = 0; i < this._roots.length; i++) {
  5521. this._roots[i].traverse(cb, context);
  5522. }
  5523. };
  5524. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  5525. includeIgnore = includeIgnore || false;
  5526. var displayList = this._displayList;
  5527. if (update || !displayList.length) {
  5528. this.updateDisplayList(includeIgnore);
  5529. }
  5530. return displayList;
  5531. };
  5532. Storage.prototype.updateDisplayList = function (includeIgnore) {
  5533. this._displayListLen = 0;
  5534. var roots = this._roots;
  5535. var displayList = this._displayList;
  5536. for (var i = 0, len = roots.length; i < len; i++) {
  5537. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5538. }
  5539. displayList.length = this._displayListLen;
  5540. env.canvasSupported && sort(displayList, shapeCompareFunc);
  5541. };
  5542. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  5543. if (el.ignore && !includeIgnore) {
  5544. return;
  5545. }
  5546. el.beforeUpdate();
  5547. el.update();
  5548. el.afterUpdate();
  5549. var userSetClipPath = el.getClipPath();
  5550. if (el.ignoreClip) {
  5551. clipPaths = null;
  5552. }
  5553. else if (userSetClipPath) {
  5554. if (clipPaths) {
  5555. clipPaths = clipPaths.slice();
  5556. }
  5557. else {
  5558. clipPaths = [];
  5559. }
  5560. var currentClipPath = userSetClipPath;
  5561. var parentClipPath = el;
  5562. while (currentClipPath) {
  5563. currentClipPath.parent = parentClipPath;
  5564. currentClipPath.updateTransform();
  5565. clipPaths.push(currentClipPath);
  5566. parentClipPath = currentClipPath;
  5567. currentClipPath = currentClipPath.getClipPath();
  5568. }
  5569. }
  5570. if (el.childrenRef) {
  5571. var children = el.childrenRef();
  5572. for (var i = 0; i < children.length; i++) {
  5573. var child = children[i];
  5574. if (el.__dirty) {
  5575. child.__dirty |= Element.REDARAW_BIT;
  5576. }
  5577. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5578. }
  5579. el.__dirty = 0;
  5580. }
  5581. else {
  5582. var disp = el;
  5583. if (clipPaths && clipPaths.length) {
  5584. disp.__clipPaths = clipPaths;
  5585. }
  5586. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  5587. disp.__clipPaths = [];
  5588. }
  5589. if (isNaN(disp.z)) {
  5590. logInvalidZError();
  5591. disp.z = 0;
  5592. }
  5593. if (isNaN(disp.z2)) {
  5594. logInvalidZError();
  5595. disp.z2 = 0;
  5596. }
  5597. if (isNaN(disp.zlevel)) {
  5598. logInvalidZError();
  5599. disp.zlevel = 0;
  5600. }
  5601. this._displayList[this._displayListLen++] = disp;
  5602. }
  5603. var decalEl = el.getDecalElement && el.getDecalElement();
  5604. if (decalEl) {
  5605. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  5606. }
  5607. var textGuide = el.getTextGuideLine();
  5608. if (textGuide) {
  5609. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  5610. }
  5611. var textEl = el.getTextContent();
  5612. if (textEl) {
  5613. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  5614. }
  5615. };
  5616. Storage.prototype.addRoot = function (el) {
  5617. if (el.__zr && el.__zr.storage === this) {
  5618. return;
  5619. }
  5620. this._roots.push(el);
  5621. };
  5622. Storage.prototype.delRoot = function (el) {
  5623. if (el instanceof Array) {
  5624. for (var i = 0, l = el.length; i < l; i++) {
  5625. this.delRoot(el[i]);
  5626. }
  5627. return;
  5628. }
  5629. var idx = indexOf(this._roots, el);
  5630. if (idx >= 0) {
  5631. this._roots.splice(idx, 1);
  5632. }
  5633. };
  5634. Storage.prototype.delAllRoots = function () {
  5635. this._roots = [];
  5636. this._displayList = [];
  5637. this._displayListLen = 0;
  5638. return;
  5639. };
  5640. Storage.prototype.getRoots = function () {
  5641. return this._roots;
  5642. };
  5643. Storage.prototype.dispose = function () {
  5644. this._displayList = null;
  5645. this._roots = null;
  5646. };
  5647. return Storage;
  5648. }());
  5649. var requestAnimationFrame;
  5650. requestAnimationFrame = (typeof window !== 'undefined'
  5651. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5652. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5653. || window.mozRequestAnimationFrame
  5654. || window.webkitRequestAnimationFrame)) || function (func) {
  5655. return setTimeout(func, 16);
  5656. };
  5657. var requestAnimationFrame$1 = requestAnimationFrame;
  5658. var Animation = (function (_super) {
  5659. __extends(Animation, _super);
  5660. function Animation(opts) {
  5661. var _this = _super.call(this) || this;
  5662. _this._running = false;
  5663. _this._time = 0;
  5664. _this._pausedTime = 0;
  5665. _this._pauseStart = 0;
  5666. _this._paused = false;
  5667. opts = opts || {};
  5668. _this.stage = opts.stage || {};
  5669. _this.onframe = opts.onframe || function () { };
  5670. return _this;
  5671. }
  5672. Animation.prototype.addClip = function (clip) {
  5673. if (clip.animation) {
  5674. this.removeClip(clip);
  5675. }
  5676. if (!this._clipsHead) {
  5677. this._clipsHead = this._clipsTail = clip;
  5678. }
  5679. else {
  5680. this._clipsTail.next = clip;
  5681. clip.prev = this._clipsTail;
  5682. clip.next = null;
  5683. this._clipsTail = clip;
  5684. }
  5685. clip.animation = this;
  5686. };
  5687. Animation.prototype.addAnimator = function (animator) {
  5688. animator.animation = this;
  5689. var clip = animator.getClip();
  5690. if (clip) {
  5691. this.addClip(clip);
  5692. }
  5693. };
  5694. Animation.prototype.removeClip = function (clip) {
  5695. if (!clip.animation) {
  5696. return;
  5697. }
  5698. var prev = clip.prev;
  5699. var next = clip.next;
  5700. if (prev) {
  5701. prev.next = next;
  5702. }
  5703. else {
  5704. this._clipsHead = next;
  5705. }
  5706. if (next) {
  5707. next.prev = prev;
  5708. }
  5709. else {
  5710. this._clipsTail = prev;
  5711. }
  5712. clip.next = clip.prev = clip.animation = null;
  5713. };
  5714. Animation.prototype.removeAnimator = function (animator) {
  5715. var clip = animator.getClip();
  5716. if (clip) {
  5717. this.removeClip(clip);
  5718. }
  5719. animator.animation = null;
  5720. };
  5721. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  5722. var time = new Date().getTime() - this._pausedTime;
  5723. var delta = time - this._time;
  5724. var clip = this._clipsHead;
  5725. while (clip) {
  5726. var nextClip = clip.next;
  5727. var finished = clip.step(time, delta);
  5728. if (finished) {
  5729. clip.ondestroy && clip.ondestroy();
  5730. this.removeClip(clip);
  5731. clip = nextClip;
  5732. }
  5733. else {
  5734. clip = nextClip;
  5735. }
  5736. }
  5737. this._time = time;
  5738. if (!notTriggerFrameAndStageUpdate) {
  5739. this.onframe(delta);
  5740. this.trigger('frame', delta);
  5741. this.stage.update && this.stage.update();
  5742. }
  5743. };
  5744. Animation.prototype._startLoop = function () {
  5745. var self = this;
  5746. this._running = true;
  5747. function step() {
  5748. if (self._running) {
  5749. requestAnimationFrame$1(step);
  5750. !self._paused && self.update();
  5751. }
  5752. }
  5753. requestAnimationFrame$1(step);
  5754. };
  5755. Animation.prototype.start = function () {
  5756. if (this._running) {
  5757. return;
  5758. }
  5759. this._time = new Date().getTime();
  5760. this._pausedTime = 0;
  5761. this._startLoop();
  5762. };
  5763. Animation.prototype.stop = function () {
  5764. this._running = false;
  5765. };
  5766. Animation.prototype.pause = function () {
  5767. if (!this._paused) {
  5768. this._pauseStart = new Date().getTime();
  5769. this._paused = true;
  5770. }
  5771. };
  5772. Animation.prototype.resume = function () {
  5773. if (this._paused) {
  5774. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  5775. this._paused = false;
  5776. }
  5777. };
  5778. Animation.prototype.clear = function () {
  5779. var clip = this._clipsHead;
  5780. while (clip) {
  5781. var nextClip = clip.next;
  5782. clip.prev = clip.next = clip.animation = null;
  5783. clip = nextClip;
  5784. }
  5785. this._clipsHead = this._clipsTail = null;
  5786. };
  5787. Animation.prototype.isFinished = function () {
  5788. return this._clipsHead == null;
  5789. };
  5790. Animation.prototype.animate = function (target, options) {
  5791. options = options || {};
  5792. this.start();
  5793. var animator = new Animator(target, options.loop);
  5794. this.addAnimator(animator);
  5795. return animator;
  5796. };
  5797. return Animation;
  5798. }(Eventful));
  5799. var TOUCH_CLICK_DELAY = 300;
  5800. var globalEventSupported = env.domSupported;
  5801. var localNativeListenerNames = (function () {
  5802. var mouseHandlerNames = [
  5803. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5804. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5805. ];
  5806. var touchHandlerNames = [
  5807. 'touchstart', 'touchend', 'touchmove'
  5808. ];
  5809. var pointerEventNameMap = {
  5810. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5811. };
  5812. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5813. var nm = name.replace('mouse', 'pointer');
  5814. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5815. });
  5816. return {
  5817. mouse: mouseHandlerNames,
  5818. touch: touchHandlerNames,
  5819. pointer: pointerHandlerNames
  5820. };
  5821. })();
  5822. var globalNativeListenerNames = {
  5823. mouse: ['mousemove', 'mouseup'],
  5824. pointer: ['pointermove', 'pointerup']
  5825. };
  5826. var wheelEventSupported = false;
  5827. function isPointerFromTouch(event) {
  5828. var pointerType = event.pointerType;
  5829. return pointerType === 'pen' || pointerType === 'touch';
  5830. }
  5831. function setTouchTimer(scope) {
  5832. scope.touching = true;
  5833. if (scope.touchTimer != null) {
  5834. clearTimeout(scope.touchTimer);
  5835. scope.touchTimer = null;
  5836. }
  5837. scope.touchTimer = setTimeout(function () {
  5838. scope.touching = false;
  5839. scope.touchTimer = null;
  5840. }, 700);
  5841. }
  5842. function markTouch(event) {
  5843. event && (event.zrByTouch = true);
  5844. }
  5845. function normalizeGlobalEvent(instance, event) {
  5846. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5847. }
  5848. function isLocalEl(instance, el) {
  5849. var elTmp = el;
  5850. var isLocal = false;
  5851. while (elTmp && elTmp.nodeType !== 9
  5852. && !(isLocal = elTmp.domBelongToZr
  5853. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5854. elTmp = elTmp.parentNode;
  5855. }
  5856. return isLocal;
  5857. }
  5858. var FakeGlobalEvent = (function () {
  5859. function FakeGlobalEvent(instance, event) {
  5860. this.stopPropagation = noop;
  5861. this.stopImmediatePropagation = noop;
  5862. this.preventDefault = noop;
  5863. this.type = event.type;
  5864. this.target = this.currentTarget = instance.dom;
  5865. this.pointerType = event.pointerType;
  5866. this.clientX = event.clientX;
  5867. this.clientY = event.clientY;
  5868. }
  5869. return FakeGlobalEvent;
  5870. }());
  5871. var localDOMHandlers = {
  5872. mousedown: function (event) {
  5873. event = normalizeEvent(this.dom, event);
  5874. this.__mayPointerCapture = [event.zrX, event.zrY];
  5875. this.trigger('mousedown', event);
  5876. },
  5877. mousemove: function (event) {
  5878. event = normalizeEvent(this.dom, event);
  5879. var downPoint = this.__mayPointerCapture;
  5880. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5881. this.__togglePointerCapture(true);
  5882. }
  5883. this.trigger('mousemove', event);
  5884. },
  5885. mouseup: function (event) {
  5886. event = normalizeEvent(this.dom, event);
  5887. this.__togglePointerCapture(false);
  5888. this.trigger('mouseup', event);
  5889. },
  5890. mouseout: function (event) {
  5891. event = normalizeEvent(this.dom, event);
  5892. var element = event.toElement || event.relatedTarget;
  5893. if (!isLocalEl(this, element)) {
  5894. if (this.__pointerCapturing) {
  5895. event.zrEventControl = 'no_globalout';
  5896. }
  5897. this.trigger('mouseout', event);
  5898. }
  5899. },
  5900. wheel: function (event) {
  5901. wheelEventSupported = true;
  5902. event = normalizeEvent(this.dom, event);
  5903. this.trigger('mousewheel', event);
  5904. },
  5905. mousewheel: function (event) {
  5906. if (wheelEventSupported) {
  5907. return;
  5908. }
  5909. event = normalizeEvent(this.dom, event);
  5910. this.trigger('mousewheel', event);
  5911. },
  5912. touchstart: function (event) {
  5913. event = normalizeEvent(this.dom, event);
  5914. markTouch(event);
  5915. this.__lastTouchMoment = new Date();
  5916. this.handler.processGesture(event, 'start');
  5917. localDOMHandlers.mousemove.call(this, event);
  5918. localDOMHandlers.mousedown.call(this, event);
  5919. },
  5920. touchmove: function (event) {
  5921. event = normalizeEvent(this.dom, event);
  5922. markTouch(event);
  5923. this.handler.processGesture(event, 'change');
  5924. localDOMHandlers.mousemove.call(this, event);
  5925. },
  5926. touchend: function (event) {
  5927. event = normalizeEvent(this.dom, event);
  5928. markTouch(event);
  5929. this.handler.processGesture(event, 'end');
  5930. localDOMHandlers.mouseup.call(this, event);
  5931. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5932. localDOMHandlers.click.call(this, event);
  5933. }
  5934. },
  5935. pointerdown: function (event) {
  5936. localDOMHandlers.mousedown.call(this, event);
  5937. },
  5938. pointermove: function (event) {
  5939. if (!isPointerFromTouch(event)) {
  5940. localDOMHandlers.mousemove.call(this, event);
  5941. }
  5942. },
  5943. pointerup: function (event) {
  5944. localDOMHandlers.mouseup.call(this, event);
  5945. },
  5946. pointerout: function (event) {
  5947. if (!isPointerFromTouch(event)) {
  5948. localDOMHandlers.mouseout.call(this, event);
  5949. }
  5950. }
  5951. };
  5952. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5953. localDOMHandlers[name] = function (event) {
  5954. event = normalizeEvent(this.dom, event);
  5955. this.trigger(name, event);
  5956. };
  5957. });
  5958. var globalDOMHandlers = {
  5959. pointermove: function (event) {
  5960. if (!isPointerFromTouch(event)) {
  5961. globalDOMHandlers.mousemove.call(this, event);
  5962. }
  5963. },
  5964. pointerup: function (event) {
  5965. globalDOMHandlers.mouseup.call(this, event);
  5966. },
  5967. mousemove: function (event) {
  5968. this.trigger('mousemove', event);
  5969. },
  5970. mouseup: function (event) {
  5971. var pointerCaptureReleasing = this.__pointerCapturing;
  5972. this.__togglePointerCapture(false);
  5973. this.trigger('mouseup', event);
  5974. if (pointerCaptureReleasing) {
  5975. event.zrEventControl = 'only_globalout';
  5976. this.trigger('mouseout', event);
  5977. }
  5978. }
  5979. };
  5980. function mountLocalDOMEventListeners(instance, scope) {
  5981. var domHandlers = scope.domHandlers;
  5982. if (env.pointerEventsSupported) {
  5983. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5984. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5985. domHandlers[nativeEventName].call(instance, event);
  5986. });
  5987. });
  5988. }
  5989. else {
  5990. if (env.touchEventsSupported) {
  5991. each(localNativeListenerNames.touch, function (nativeEventName) {
  5992. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5993. domHandlers[nativeEventName].call(instance, event);
  5994. setTouchTimer(scope);
  5995. });
  5996. });
  5997. }
  5998. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5999. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  6000. event = getNativeEvent(event);
  6001. if (!scope.touching) {
  6002. domHandlers[nativeEventName].call(instance, event);
  6003. }
  6004. });
  6005. });
  6006. }
  6007. }
  6008. function mountGlobalDOMEventListeners(instance, scope) {
  6009. if (env.pointerEventsSupported) {
  6010. each(globalNativeListenerNames.pointer, mount);
  6011. }
  6012. else if (!env.touchEventsSupported) {
  6013. each(globalNativeListenerNames.mouse, mount);
  6014. }
  6015. function mount(nativeEventName) {
  6016. function nativeEventListener(event) {
  6017. event = getNativeEvent(event);
  6018. if (!isLocalEl(instance, event.target)) {
  6019. event = normalizeGlobalEvent(instance, event);
  6020. scope.domHandlers[nativeEventName].call(instance, event);
  6021. }
  6022. }
  6023. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  6024. }
  6025. }
  6026. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  6027. scope.mounted[nativeEventName] = listener;
  6028. scope.listenerOpts[nativeEventName] = opt;
  6029. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  6030. }
  6031. function unmountDOMEventListeners(scope) {
  6032. var mounted = scope.mounted;
  6033. for (var nativeEventName in mounted) {
  6034. if (mounted.hasOwnProperty(nativeEventName)) {
  6035. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  6036. }
  6037. }
  6038. scope.mounted = {};
  6039. }
  6040. var DOMHandlerScope = (function () {
  6041. function DOMHandlerScope(domTarget, domHandlers) {
  6042. this.mounted = {};
  6043. this.listenerOpts = {};
  6044. this.touching = false;
  6045. this.domTarget = domTarget;
  6046. this.domHandlers = domHandlers;
  6047. }
  6048. return DOMHandlerScope;
  6049. }());
  6050. var HandlerDomProxy = (function (_super) {
  6051. __extends(HandlerDomProxy, _super);
  6052. function HandlerDomProxy(dom, painterRoot) {
  6053. var _this = _super.call(this) || this;
  6054. _this.__pointerCapturing = false;
  6055. _this.dom = dom;
  6056. _this.painterRoot = painterRoot;
  6057. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  6058. if (globalEventSupported) {
  6059. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  6060. }
  6061. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  6062. return _this;
  6063. }
  6064. HandlerDomProxy.prototype.dispose = function () {
  6065. unmountDOMEventListeners(this._localHandlerScope);
  6066. if (globalEventSupported) {
  6067. unmountDOMEventListeners(this._globalHandlerScope);
  6068. }
  6069. };
  6070. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  6071. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  6072. };
  6073. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  6074. this.__mayPointerCapture = null;
  6075. if (globalEventSupported
  6076. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  6077. this.__pointerCapturing = isPointerCapturing;
  6078. var globalHandlerScope = this._globalHandlerScope;
  6079. isPointerCapturing
  6080. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  6081. : unmountDOMEventListeners(globalHandlerScope);
  6082. }
  6083. };
  6084. return HandlerDomProxy;
  6085. }(Eventful));
  6086. var Group = (function (_super) {
  6087. __extends(Group, _super);
  6088. function Group(opts) {
  6089. var _this = _super.call(this) || this;
  6090. _this.isGroup = true;
  6091. _this._children = [];
  6092. _this.attr(opts);
  6093. return _this;
  6094. }
  6095. Group.prototype.childrenRef = function () {
  6096. return this._children;
  6097. };
  6098. Group.prototype.children = function () {
  6099. return this._children.slice();
  6100. };
  6101. Group.prototype.childAt = function (idx) {
  6102. return this._children[idx];
  6103. };
  6104. Group.prototype.childOfName = function (name) {
  6105. var children = this._children;
  6106. for (var i = 0; i < children.length; i++) {
  6107. if (children[i].name === name) {
  6108. return children[i];
  6109. }
  6110. }
  6111. };
  6112. Group.prototype.childCount = function () {
  6113. return this._children.length;
  6114. };
  6115. Group.prototype.add = function (child) {
  6116. if (child) {
  6117. if (child !== this && child.parent !== this) {
  6118. this._children.push(child);
  6119. this._doAdd(child);
  6120. }
  6121. if (child.__hostTarget) {
  6122. throw 'This elemenet has been used as an attachment';
  6123. }
  6124. }
  6125. return this;
  6126. };
  6127. Group.prototype.addBefore = function (child, nextSibling) {
  6128. if (child && child !== this && child.parent !== this
  6129. && nextSibling && nextSibling.parent === this) {
  6130. var children = this._children;
  6131. var idx = children.indexOf(nextSibling);
  6132. if (idx >= 0) {
  6133. children.splice(idx, 0, child);
  6134. this._doAdd(child);
  6135. }
  6136. }
  6137. return this;
  6138. };
  6139. Group.prototype.replaceAt = function (child, index) {
  6140. var children = this._children;
  6141. var old = children[index];
  6142. if (child && child !== this && child.parent !== this && child !== old) {
  6143. children[index] = child;
  6144. old.parent = null;
  6145. var zr = this.__zr;
  6146. if (zr) {
  6147. old.removeSelfFromZr(zr);
  6148. }
  6149. this._doAdd(child);
  6150. }
  6151. return this;
  6152. };
  6153. Group.prototype._doAdd = function (child) {
  6154. if (child.parent) {
  6155. child.parent.remove(child);
  6156. }
  6157. child.parent = this;
  6158. var zr = this.__zr;
  6159. if (zr && zr !== child.__zr) {
  6160. child.addSelfToZr(zr);
  6161. }
  6162. zr && zr.refresh();
  6163. };
  6164. Group.prototype.remove = function (child) {
  6165. var zr = this.__zr;
  6166. var children = this._children;
  6167. var idx = indexOf(children, child);
  6168. if (idx < 0) {
  6169. return this;
  6170. }
  6171. children.splice(idx, 1);
  6172. child.parent = null;
  6173. if (zr) {
  6174. child.removeSelfFromZr(zr);
  6175. }
  6176. zr && zr.refresh();
  6177. return this;
  6178. };
  6179. Group.prototype.removeAll = function () {
  6180. var children = this._children;
  6181. var zr = this.__zr;
  6182. for (var i = 0; i < children.length; i++) {
  6183. var child = children[i];
  6184. if (zr) {
  6185. child.removeSelfFromZr(zr);
  6186. }
  6187. child.parent = null;
  6188. }
  6189. children.length = 0;
  6190. return this;
  6191. };
  6192. Group.prototype.eachChild = function (cb, context) {
  6193. var children = this._children;
  6194. for (var i = 0; i < children.length; i++) {
  6195. var child = children[i];
  6196. cb.call(context, child, i);
  6197. }
  6198. return this;
  6199. };
  6200. Group.prototype.traverse = function (cb, context) {
  6201. for (var i = 0; i < this._children.length; i++) {
  6202. var child = this._children[i];
  6203. var stopped = cb.call(context, child);
  6204. if (child.isGroup && !stopped) {
  6205. child.traverse(cb, context);
  6206. }
  6207. }
  6208. return this;
  6209. };
  6210. Group.prototype.addSelfToZr = function (zr) {
  6211. _super.prototype.addSelfToZr.call(this, zr);
  6212. for (var i = 0; i < this._children.length; i++) {
  6213. var child = this._children[i];
  6214. child.addSelfToZr(zr);
  6215. }
  6216. };
  6217. Group.prototype.removeSelfFromZr = function (zr) {
  6218. _super.prototype.removeSelfFromZr.call(this, zr);
  6219. for (var i = 0; i < this._children.length; i++) {
  6220. var child = this._children[i];
  6221. child.removeSelfFromZr(zr);
  6222. }
  6223. };
  6224. Group.prototype.getBoundingRect = function (includeChildren) {
  6225. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6226. var children = includeChildren || this._children;
  6227. var tmpMat = [];
  6228. var rect = null;
  6229. for (var i = 0; i < children.length; i++) {
  6230. var child = children[i];
  6231. if (child.ignore || child.invisible) {
  6232. continue;
  6233. }
  6234. var childRect = child.getBoundingRect();
  6235. var transform = child.getLocalTransform(tmpMat);
  6236. if (transform) {
  6237. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6238. rect = rect || tmpRect.clone();
  6239. rect.union(tmpRect);
  6240. }
  6241. else {
  6242. rect = rect || childRect.clone();
  6243. rect.union(childRect);
  6244. }
  6245. }
  6246. return rect || tmpRect;
  6247. };
  6248. return Group;
  6249. }(Element));
  6250. Group.prototype.type = 'group';
  6251. /*!
  6252. * ZRender, a high performance 2d drawing library.
  6253. *
  6254. * Copyright (c) 2013, Baidu Inc.
  6255. * All rights reserved.
  6256. *
  6257. * LICENSE
  6258. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6259. */
  6260. var useVML = !env.canvasSupported;
  6261. var painterCtors = {};
  6262. var instances = {};
  6263. function delInstance(id) {
  6264. delete instances[id];
  6265. }
  6266. function isDarkMode(backgroundColor) {
  6267. if (!backgroundColor) {
  6268. return false;
  6269. }
  6270. if (typeof backgroundColor === 'string') {
  6271. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6272. }
  6273. else if (backgroundColor.colorStops) {
  6274. var colorStops = backgroundColor.colorStops;
  6275. var totalLum = 0;
  6276. var len = colorStops.length;
  6277. for (var i = 0; i < len; i++) {
  6278. totalLum += lum(colorStops[i].color, 1);
  6279. }
  6280. totalLum /= len;
  6281. return totalLum < DARK_MODE_THRESHOLD;
  6282. }
  6283. return false;
  6284. }
  6285. var ZRender = (function () {
  6286. function ZRender(id, dom, opts) {
  6287. var _this = this;
  6288. this._sleepAfterStill = 10;
  6289. this._stillFrameAccum = 0;
  6290. this._needsRefresh = true;
  6291. this._needsRefreshHover = true;
  6292. this._darkMode = false;
  6293. opts = opts || {};
  6294. this.dom = dom;
  6295. this.id = id;
  6296. var storage = new Storage();
  6297. var rendererType = opts.renderer || 'canvas';
  6298. if (useVML) {
  6299. throw new Error('IE8 support has been dropped since 5.0');
  6300. }
  6301. if (!painterCtors[rendererType]) {
  6302. rendererType = keys(painterCtors)[0];
  6303. }
  6304. if (!painterCtors[rendererType]) {
  6305. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  6306. }
  6307. opts.useDirtyRect = opts.useDirtyRect == null
  6308. ? false
  6309. : opts.useDirtyRect;
  6310. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  6311. this.storage = storage;
  6312. this.painter = painter;
  6313. var handerProxy = (!env.node && !env.worker)
  6314. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  6315. : null;
  6316. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  6317. this.animation = new Animation({
  6318. stage: {
  6319. update: function () { return _this._flush(true); }
  6320. }
  6321. });
  6322. this.animation.start();
  6323. }
  6324. ZRender.prototype.add = function (el) {
  6325. if (!el) {
  6326. return;
  6327. }
  6328. this.storage.addRoot(el);
  6329. el.addSelfToZr(this);
  6330. this.refresh();
  6331. };
  6332. ZRender.prototype.remove = function (el) {
  6333. if (!el) {
  6334. return;
  6335. }
  6336. this.storage.delRoot(el);
  6337. el.removeSelfFromZr(this);
  6338. this.refresh();
  6339. };
  6340. ZRender.prototype.configLayer = function (zLevel, config) {
  6341. if (this.painter.configLayer) {
  6342. this.painter.configLayer(zLevel, config);
  6343. }
  6344. this.refresh();
  6345. };
  6346. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  6347. if (this.painter.setBackgroundColor) {
  6348. this.painter.setBackgroundColor(backgroundColor);
  6349. }
  6350. this.refresh();
  6351. this._backgroundColor = backgroundColor;
  6352. this._darkMode = isDarkMode(backgroundColor);
  6353. };
  6354. ZRender.prototype.getBackgroundColor = function () {
  6355. return this._backgroundColor;
  6356. };
  6357. ZRender.prototype.setDarkMode = function (darkMode) {
  6358. this._darkMode = darkMode;
  6359. };
  6360. ZRender.prototype.isDarkMode = function () {
  6361. return this._darkMode;
  6362. };
  6363. ZRender.prototype.refreshImmediately = function (fromInside) {
  6364. if (!fromInside) {
  6365. this.animation.update(true);
  6366. }
  6367. this._needsRefresh = false;
  6368. this.painter.refresh();
  6369. this._needsRefresh = false;
  6370. };
  6371. ZRender.prototype.refresh = function () {
  6372. this._needsRefresh = true;
  6373. this.animation.start();
  6374. };
  6375. ZRender.prototype.flush = function () {
  6376. this._flush(false);
  6377. };
  6378. ZRender.prototype._flush = function (fromInside) {
  6379. var triggerRendered;
  6380. var start = new Date().getTime();
  6381. if (this._needsRefresh) {
  6382. triggerRendered = true;
  6383. this.refreshImmediately(fromInside);
  6384. }
  6385. if (this._needsRefreshHover) {
  6386. triggerRendered = true;
  6387. this.refreshHoverImmediately();
  6388. }
  6389. var end = new Date().getTime();
  6390. if (triggerRendered) {
  6391. this._stillFrameAccum = 0;
  6392. this.trigger('rendered', {
  6393. elapsedTime: end - start
  6394. });
  6395. }
  6396. else if (this._sleepAfterStill > 0) {
  6397. this._stillFrameAccum++;
  6398. if (this._stillFrameAccum > this._sleepAfterStill) {
  6399. this.animation.stop();
  6400. }
  6401. }
  6402. };
  6403. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  6404. this._sleepAfterStill = stillFramesCount;
  6405. };
  6406. ZRender.prototype.wakeUp = function () {
  6407. this.animation.start();
  6408. this._stillFrameAccum = 0;
  6409. };
  6410. ZRender.prototype.addHover = function (el) {
  6411. };
  6412. ZRender.prototype.removeHover = function (el) {
  6413. };
  6414. ZRender.prototype.clearHover = function () {
  6415. };
  6416. ZRender.prototype.refreshHover = function () {
  6417. this._needsRefreshHover = true;
  6418. };
  6419. ZRender.prototype.refreshHoverImmediately = function () {
  6420. this._needsRefreshHover = false;
  6421. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  6422. this.painter.refreshHover();
  6423. }
  6424. };
  6425. ZRender.prototype.resize = function (opts) {
  6426. opts = opts || {};
  6427. this.painter.resize(opts.width, opts.height);
  6428. this.handler.resize();
  6429. };
  6430. ZRender.prototype.clearAnimation = function () {
  6431. this.animation.clear();
  6432. };
  6433. ZRender.prototype.getWidth = function () {
  6434. return this.painter.getWidth();
  6435. };
  6436. ZRender.prototype.getHeight = function () {
  6437. return this.painter.getHeight();
  6438. };
  6439. ZRender.prototype.pathToImage = function (e, dpr) {
  6440. if (this.painter.pathToImage) {
  6441. return this.painter.pathToImage(e, dpr);
  6442. }
  6443. };
  6444. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  6445. this.handler.setCursorStyle(cursorStyle);
  6446. };
  6447. ZRender.prototype.findHover = function (x, y) {
  6448. return this.handler.findHover(x, y);
  6449. };
  6450. ZRender.prototype.on = function (eventName, eventHandler, context) {
  6451. this.handler.on(eventName, eventHandler, context);
  6452. return this;
  6453. };
  6454. ZRender.prototype.off = function (eventName, eventHandler) {
  6455. this.handler.off(eventName, eventHandler);
  6456. };
  6457. ZRender.prototype.trigger = function (eventName, event) {
  6458. this.handler.trigger(eventName, event);
  6459. };
  6460. ZRender.prototype.clear = function () {
  6461. var roots = this.storage.getRoots();
  6462. for (var i = 0; i < roots.length; i++) {
  6463. if (roots[i] instanceof Group) {
  6464. roots[i].removeSelfFromZr(this);
  6465. }
  6466. }
  6467. this.storage.delAllRoots();
  6468. this.painter.clear();
  6469. };
  6470. ZRender.prototype.dispose = function () {
  6471. this.animation.stop();
  6472. this.clear();
  6473. this.storage.dispose();
  6474. this.painter.dispose();
  6475. this.handler.dispose();
  6476. this.animation =
  6477. this.storage =
  6478. this.painter =
  6479. this.handler = null;
  6480. delInstance(this.id);
  6481. };
  6482. return ZRender;
  6483. }());
  6484. function init(dom, opts) {
  6485. var zr = new ZRender(guid(), dom, opts);
  6486. instances[zr.id] = zr;
  6487. return zr;
  6488. }
  6489. function dispose(zr) {
  6490. zr.dispose();
  6491. }
  6492. function disposeAll() {
  6493. for (var key in instances) {
  6494. if (instances.hasOwnProperty(key)) {
  6495. instances[key].dispose();
  6496. }
  6497. }
  6498. instances = {};
  6499. }
  6500. function getInstance(id) {
  6501. return instances[id];
  6502. }
  6503. function registerPainter(name, Ctor) {
  6504. painterCtors[name] = Ctor;
  6505. }
  6506. var version = '5.0.4';
  6507. var zrender = /*#__PURE__*/Object.freeze({
  6508. __proto__: null,
  6509. init: init,
  6510. dispose: dispose,
  6511. disposeAll: disposeAll,
  6512. getInstance: getInstance,
  6513. registerPainter: registerPainter,
  6514. version: version
  6515. });
  6516. var RADIAN_EPSILON = 1e-4;
  6517. function _trim(str) {
  6518. return str.replace(/^\s+|\s+$/g, '');
  6519. }
  6520. /**
  6521. * Linear mapping a value from domain to range
  6522. * @param val
  6523. * @param domain Domain extent domain[0] can be bigger than domain[1]
  6524. * @param range Range extent range[0] can be bigger than range[1]
  6525. * @param clamp Default to be false
  6526. */
  6527. function linearMap(val, domain, range, clamp) {
  6528. var subDomain = domain[1] - domain[0];
  6529. var subRange = range[1] - range[0];
  6530. if (subDomain === 0) {
  6531. return subRange === 0 ? range[0] : (range[0] + range[1]) / 2;
  6532. } // Avoid accuracy problem in edge, such as
  6533. // 146.39 - 62.83 === 83.55999999999999.
  6534. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  6535. // It is a little verbose for efficiency considering this method
  6536. // is a hotspot.
  6537. if (clamp) {
  6538. if (subDomain > 0) {
  6539. if (val <= domain[0]) {
  6540. return range[0];
  6541. } else if (val >= domain[1]) {
  6542. return range[1];
  6543. }
  6544. } else {
  6545. if (val >= domain[0]) {
  6546. return range[0];
  6547. } else if (val <= domain[1]) {
  6548. return range[1];
  6549. }
  6550. }
  6551. } else {
  6552. if (val === domain[0]) {
  6553. return range[0];
  6554. }
  6555. if (val === domain[1]) {
  6556. return range[1];
  6557. }
  6558. }
  6559. return (val - domain[0]) / subDomain * subRange + range[0];
  6560. }
  6561. /**
  6562. * Convert a percent string to absolute number.
  6563. * Returns NaN if percent is not a valid string or number
  6564. */
  6565. function parsePercent$1(percent, all) {
  6566. switch (percent) {
  6567. case 'center':
  6568. case 'middle':
  6569. percent = '50%';
  6570. break;
  6571. case 'left':
  6572. case 'top':
  6573. percent = '0%';
  6574. break;
  6575. case 'right':
  6576. case 'bottom':
  6577. percent = '100%';
  6578. break;
  6579. }
  6580. if (typeof percent === 'string') {
  6581. if (_trim(percent).match(/%$/)) {
  6582. return parseFloat(percent) / 100 * all;
  6583. }
  6584. return parseFloat(percent);
  6585. }
  6586. return percent == null ? NaN : +percent;
  6587. }
  6588. function round(x, precision, returnStr) {
  6589. if (precision == null) {
  6590. precision = 10;
  6591. } // Avoid range error
  6592. precision = Math.min(Math.max(0, precision), 20);
  6593. x = (+x).toFixed(precision);
  6594. return returnStr ? x : +x;
  6595. }
  6596. /**
  6597. * Inplacd asc sort arr.
  6598. * The input arr will be modified.
  6599. */
  6600. function asc(arr) {
  6601. arr.sort(function (a, b) {
  6602. return a - b;
  6603. });
  6604. return arr;
  6605. }
  6606. /**
  6607. * Get precision
  6608. */
  6609. function getPrecision(val) {
  6610. val = +val;
  6611. if (isNaN(val)) {
  6612. return 0;
  6613. } // It is much faster than methods converting number to string as follows
  6614. // let tmp = val.toString();
  6615. // return tmp.length - 1 - tmp.indexOf('.');
  6616. // especially when precision is low
  6617. var e = 1;
  6618. var count = 0;
  6619. while (Math.round(val * e) / e !== val) {
  6620. e *= 10;
  6621. count++;
  6622. }
  6623. return count;
  6624. }
  6625. /**
  6626. * Get precision with slow but safe method
  6627. */
  6628. function getPrecisionSafe(val) {
  6629. var str = val.toString(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  6630. var eIndex = str.indexOf('e');
  6631. if (eIndex > 0) {
  6632. var precision = +str.slice(eIndex + 1);
  6633. return precision < 0 ? -precision : 0;
  6634. } else {
  6635. var dotIndex = str.indexOf('.');
  6636. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  6637. }
  6638. }
  6639. /**
  6640. * Minimal dicernible data precisioin according to a single pixel.
  6641. */
  6642. function getPixelPrecision(dataExtent, pixelExtent) {
  6643. var log = Math.log;
  6644. var LN10 = Math.LN10;
  6645. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  6646. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  6647. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  6648. return !isFinite(precision) ? 20 : precision;
  6649. }
  6650. /**
  6651. * Get a data of given precision, assuring the sum of percentages
  6652. * in valueList is 1.
  6653. * The largest remainer method is used.
  6654. * https://en.wikipedia.org/wiki/Largest_remainder_method
  6655. *
  6656. * @param valueList a list of all data
  6657. * @param idx index of the data to be processed in valueList
  6658. * @param precision integer number showing digits of precision
  6659. * @return percent ranging from 0 to 100
  6660. */
  6661. function getPercentWithPrecision(valueList, idx, precision) {
  6662. if (!valueList[idx]) {
  6663. return 0;
  6664. }
  6665. var sum = reduce(valueList, function (acc, val) {
  6666. return acc + (isNaN(val) ? 0 : val);
  6667. }, 0);
  6668. if (sum === 0) {
  6669. return 0;
  6670. }
  6671. var digits = Math.pow(10, precision);
  6672. var votesPerQuota = map(valueList, function (val) {
  6673. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  6674. });
  6675. var targetSeats = digits * 100;
  6676. var seats = map(votesPerQuota, function (votes) {
  6677. // Assign automatic seats.
  6678. return Math.floor(votes);
  6679. });
  6680. var currentSum = reduce(seats, function (acc, val) {
  6681. return acc + val;
  6682. }, 0);
  6683. var remainder = map(votesPerQuota, function (votes, idx) {
  6684. return votes - seats[idx];
  6685. }); // Has remainding votes.
  6686. while (currentSum < targetSeats) {
  6687. // Find next largest remainder.
  6688. var max = Number.NEGATIVE_INFINITY;
  6689. var maxId = null;
  6690. for (var i = 0, len = remainder.length; i < len; ++i) {
  6691. if (remainder[i] > max) {
  6692. max = remainder[i];
  6693. maxId = i;
  6694. }
  6695. } // Add a vote to max remainder.
  6696. ++seats[maxId];
  6697. remainder[maxId] = 0;
  6698. ++currentSum;
  6699. }
  6700. return seats[idx] / digits;
  6701. } // Number.MAX_SAFE_INTEGER, ie do not support.
  6702. var MAX_SAFE_INTEGER = 9007199254740991;
  6703. /**
  6704. * To 0 - 2 * PI, considering negative radian.
  6705. */
  6706. function remRadian(radian) {
  6707. var pi2 = Math.PI * 2;
  6708. return (radian % pi2 + pi2) % pi2;
  6709. }
  6710. /**
  6711. * @param {type} radian
  6712. * @return {boolean}
  6713. */
  6714. function isRadianAroundZero(val) {
  6715. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  6716. } // eslint-disable-next-line
  6717. 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
  6718. /**
  6719. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  6720. * These values can be accepted:
  6721. * + An instance of Date, represent a time in its own time zone.
  6722. * + Or string in a subset of ISO 8601, only including:
  6723. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  6724. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  6725. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  6726. * all of which will be treated as local time if time zone is not specified
  6727. * (see <https://momentjs.com/>).
  6728. * + Or other string format, including (all of which will be treated as loacal time):
  6729. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  6730. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  6731. * + a timestamp, which represent a time in UTC.
  6732. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  6733. */
  6734. function parseDate(value) {
  6735. if (value instanceof Date) {
  6736. return value;
  6737. } else if (typeof value === 'string') {
  6738. // Different browsers parse date in different way, so we parse it manually.
  6739. // Some other issues:
  6740. // new Date('1970-01-01') is UTC,
  6741. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  6742. // See issue #3623
  6743. var match = TIME_REG.exec(value);
  6744. if (!match) {
  6745. // return Invalid Date.
  6746. return new Date(NaN);
  6747. } // Use local time when no timezone offset specifed.
  6748. if (!match[8]) {
  6749. // match[n] can only be string or undefined.
  6750. // But take care of '12' + 1 => '121'.
  6751. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
  6752. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  6753. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  6754. // For example, system timezone is set as "Time Zone: America/Toronto",
  6755. // then these code will get different result:
  6756. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  6757. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  6758. // So we should not use `new Date`, but use `Date.UTC`.
  6759. else {
  6760. var hour = +match[4] || 0;
  6761. if (match[8].toUpperCase() !== 'Z') {
  6762. hour -= +match[8].slice(0, 3);
  6763. }
  6764. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
  6765. }
  6766. } else if (value == null) {
  6767. return new Date(NaN);
  6768. }
  6769. return new Date(Math.round(value));
  6770. }
  6771. /**
  6772. * Quantity of a number. e.g. 0.1, 1, 10, 100
  6773. *
  6774. * @param val
  6775. * @return
  6776. */
  6777. function quantity(val) {
  6778. return Math.pow(10, quantityExponent(val));
  6779. }
  6780. /**
  6781. * Exponent of the quantity of a number
  6782. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  6783. *
  6784. * @param val non-negative value
  6785. * @return
  6786. */
  6787. function quantityExponent(val) {
  6788. if (val === 0) {
  6789. return 0;
  6790. }
  6791. var exp = Math.floor(Math.log(val) / Math.LN10);
  6792. /**
  6793. * exp is expected to be the rounded-down result of the base-10 log of val.
  6794. * But due to the precision loss with Math.log(val), we need to restore it
  6795. * using 10^exp to make sure we can get val back from exp. #11249
  6796. */
  6797. if (val / Math.pow(10, exp) >= 10) {
  6798. exp++;
  6799. }
  6800. return exp;
  6801. }
  6802. /**
  6803. * find a “nice” number approximately equal to x. Round the number if round = true,
  6804. * take ceiling if round = false. The primary observation is that the “nicest”
  6805. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  6806. *
  6807. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  6808. *
  6809. * @param val Non-negative value.
  6810. * @param round
  6811. * @return Niced number
  6812. */
  6813. function nice(val, round) {
  6814. var exponent = quantityExponent(val);
  6815. var exp10 = Math.pow(10, exponent);
  6816. var f = val / exp10; // 1 <= f < 10
  6817. var nf;
  6818. if (round) {
  6819. if (f < 1.5) {
  6820. nf = 1;
  6821. } else if (f < 2.5) {
  6822. nf = 2;
  6823. } else if (f < 4) {
  6824. nf = 3;
  6825. } else if (f < 7) {
  6826. nf = 5;
  6827. } else {
  6828. nf = 10;
  6829. }
  6830. } else {
  6831. if (f < 1) {
  6832. nf = 1;
  6833. } else if (f < 2) {
  6834. nf = 2;
  6835. } else if (f < 3) {
  6836. nf = 3;
  6837. } else if (f < 5) {
  6838. nf = 5;
  6839. } else {
  6840. nf = 10;
  6841. }
  6842. }
  6843. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  6844. // 20 is the uppper bound of toFixed.
  6845. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  6846. }
  6847. /**
  6848. * This code was copied from "d3.js"
  6849. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  6850. * See the license statement at the head of this file.
  6851. * @param ascArr
  6852. */
  6853. function quantile(ascArr, p) {
  6854. var H = (ascArr.length - 1) * p + 1;
  6855. var h = Math.floor(H);
  6856. var v = +ascArr[h - 1];
  6857. var e = H - h;
  6858. return e ? v + e * (ascArr[h] - v) : v;
  6859. }
  6860. /**
  6861. * Order intervals asc, and split them when overlap.
  6862. * expect(numberUtil.reformIntervals([
  6863. * {interval: [18, 62], close: [1, 1]},
  6864. * {interval: [-Infinity, -70], close: [0, 0]},
  6865. * {interval: [-70, -26], close: [1, 1]},
  6866. * {interval: [-26, 18], close: [1, 1]},
  6867. * {interval: [62, 150], close: [1, 1]},
  6868. * {interval: [106, 150], close: [1, 1]},
  6869. * {interval: [150, Infinity], close: [0, 0]}
  6870. * ])).toEqual([
  6871. * {interval: [-Infinity, -70], close: [0, 0]},
  6872. * {interval: [-70, -26], close: [1, 1]},
  6873. * {interval: [-26, 18], close: [0, 1]},
  6874. * {interval: [18, 62], close: [0, 1]},
  6875. * {interval: [62, 150], close: [0, 1]},
  6876. * {interval: [150, Infinity], close: [0, 0]}
  6877. * ]);
  6878. * @param list, where `close` mean open or close
  6879. * of the interval, and Infinity can be used.
  6880. * @return The origin list, which has been reformed.
  6881. */
  6882. function reformIntervals(list) {
  6883. list.sort(function (a, b) {
  6884. return littleThan(a, b, 0) ? -1 : 1;
  6885. });
  6886. var curr = -Infinity;
  6887. var currClose = 1;
  6888. for (var i = 0; i < list.length;) {
  6889. var interval = list[i].interval;
  6890. var close_1 = list[i].close;
  6891. for (var lg = 0; lg < 2; lg++) {
  6892. if (interval[lg] <= curr) {
  6893. interval[lg] = curr;
  6894. close_1[lg] = !lg ? 1 - currClose : 1;
  6895. }
  6896. curr = interval[lg];
  6897. currClose = close_1[lg];
  6898. }
  6899. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  6900. list.splice(i, 1);
  6901. } else {
  6902. i++;
  6903. }
  6904. }
  6905. return list;
  6906. function littleThan(a, b, lg) {
  6907. 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));
  6908. }
  6909. }
  6910. /**
  6911. * [Numberic is defined as]:
  6912. * `parseFloat(val) == val`
  6913. * For example:
  6914. * numeric:
  6915. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  6916. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  6917. * not-numeric:
  6918. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  6919. * empty string, string with only white-spaces or line-terminal (see es spec),
  6920. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  6921. * non-string, ...
  6922. *
  6923. * @test See full test cases in `test/ut/spec/util/number.js`.
  6924. * @return Must be a typeof number. If not numeric, return NaN.
  6925. */
  6926. function numericToNumber(val) {
  6927. var valFloat = parseFloat(val);
  6928. return valFloat == val // eslint-disable-line eqeqeq
  6929. && (valFloat !== 0 || typeof val !== 'string' || val.indexOf('x') <= 0) // For case ' 0x0 '.
  6930. ? valFloat : NaN;
  6931. }
  6932. /**
  6933. * Definition of "numeric": see `numericToNumber`.
  6934. */
  6935. function isNumeric(val) {
  6936. return !isNaN(numericToNumber(val));
  6937. }
  6938. /**
  6939. * Use random base to prevent users hard code depending on
  6940. * this auto generated marker id.
  6941. * @return An positive integer.
  6942. */
  6943. function getRandomIdBase() {
  6944. return Math.round(Math.random() * 9);
  6945. }
  6946. /**
  6947. * Get the greatest common dividor
  6948. *
  6949. * @param {number} a one number
  6950. * @param {number} b the other number
  6951. */
  6952. function getGreatestCommonDividor(a, b) {
  6953. if (b === 0) {
  6954. return a;
  6955. }
  6956. return getGreatestCommonDividor(b, a % b);
  6957. }
  6958. /**
  6959. * Get the least common multiple
  6960. *
  6961. * @param {number} a one number
  6962. * @param {number} b the other number
  6963. */
  6964. function getLeastCommonMultiple(a, b) {
  6965. if (a == null) {
  6966. return b;
  6967. }
  6968. if (b == null) {
  6969. return a;
  6970. }
  6971. return a * b / getGreatestCommonDividor(a, b);
  6972. }
  6973. var ECHARTS_PREFIX = '[ECharts] ';
  6974. var storedLogs = {};
  6975. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  6976. && console.warn && console.log;
  6977. function warn(str) {
  6978. if (hasConsole) {
  6979. console.warn(ECHARTS_PREFIX + str);
  6980. }
  6981. }
  6982. function error(str) {
  6983. if (hasConsole) {
  6984. console.error(ECHARTS_PREFIX + str);
  6985. }
  6986. }
  6987. function deprecateLog(str) {
  6988. if ("development" !== 'production') {
  6989. if (storedLogs[str]) {
  6990. // Not display duplicate message.
  6991. return;
  6992. }
  6993. if (hasConsole) {
  6994. storedLogs[str] = true;
  6995. console.warn(ECHARTS_PREFIX + 'DEPRECATED: ' + str);
  6996. }
  6997. }
  6998. }
  6999. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7000. if ("development" !== 'production') {
  7001. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7002. }
  7003. }
  7004. function consoleLog() {
  7005. var args = [];
  7006. for (var _i = 0; _i < arguments.length; _i++) {
  7007. args[_i] = arguments[_i];
  7008. }
  7009. if ("development" !== 'production') {
  7010. /* eslint-disable no-console */
  7011. if (typeof console !== 'undefined' && console.log) {
  7012. console.log.apply(console, args);
  7013. }
  7014. /* eslint-enable no-console */
  7015. }
  7016. }
  7017. /**
  7018. * If in __DEV__ environment, get console printable message for users hint.
  7019. * Parameters are separated by ' '.
  7020. * @usuage
  7021. * makePrintable('This is an error on', someVar, someObj);
  7022. *
  7023. * @param hintInfo anything about the current execution context to hint users.
  7024. * @throws Error
  7025. */
  7026. function makePrintable() {
  7027. var hintInfo = [];
  7028. for (var _i = 0; _i < arguments.length; _i++) {
  7029. hintInfo[_i] = arguments[_i];
  7030. }
  7031. var msg = '';
  7032. if ("development" !== 'production') {
  7033. // Fuzzy stringify for print.
  7034. // This code only exist in dev environment.
  7035. var makePrintableStringIfPossible_1 = function (val) {
  7036. 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;
  7037. };
  7038. msg = map(hintInfo, function (arg) {
  7039. if (isString(arg)) {
  7040. // Print without quotation mark for some statement.
  7041. return arg;
  7042. } else {
  7043. var printableStr = makePrintableStringIfPossible_1(arg);
  7044. if (printableStr != null) {
  7045. return printableStr;
  7046. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7047. try {
  7048. return JSON.stringify(arg, function (n, val) {
  7049. var printableStr = makePrintableStringIfPossible_1(val);
  7050. return printableStr == null ? val : printableStr;
  7051. }); // In most cases the info object is small, so do not line break.
  7052. } catch (err) {
  7053. return '?';
  7054. }
  7055. } else {
  7056. return '?';
  7057. }
  7058. }
  7059. }).join(' ');
  7060. }
  7061. return msg;
  7062. }
  7063. /**
  7064. * @throws Error
  7065. */
  7066. function throwError(msg) {
  7067. throw new Error(msg);
  7068. }
  7069. /**
  7070. * Make the name displayable. But we should
  7071. * make sure it is not duplicated with user
  7072. * specified name, so use '\0';
  7073. */
  7074. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7075. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7076. /**
  7077. * If value is not array, then translate it to array.
  7078. * @param {*} value
  7079. * @return {Array} [value] or value
  7080. */
  7081. function normalizeToArray(value) {
  7082. return value instanceof Array ? value : value == null ? [] : [value];
  7083. }
  7084. /**
  7085. * Sync default option between normal and emphasis like `position` and `show`
  7086. * In case some one will write code like
  7087. * label: {
  7088. * show: false,
  7089. * position: 'outside',
  7090. * fontSize: 18
  7091. * },
  7092. * emphasis: {
  7093. * label: { show: true }
  7094. * }
  7095. */
  7096. function defaultEmphasis(opt, key, subOpts) {
  7097. // Caution: performance sensitive.
  7098. if (opt) {
  7099. opt[key] = opt[key] || {};
  7100. opt.emphasis = opt.emphasis || {};
  7101. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7102. for (var i = 0, len = subOpts.length; i < len; i++) {
  7103. var subOptName = subOpts[i];
  7104. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7105. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7106. }
  7107. }
  7108. }
  7109. }
  7110. 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([
  7111. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7112. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7113. // // FIXME: deprecated, check and remove it.
  7114. // 'textStyle'
  7115. // ]);
  7116. /**
  7117. * The method do not ensure performance.
  7118. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7119. * This helper method retieves value from data.
  7120. */
  7121. function getDataItemValue(dataItem) {
  7122. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7123. }
  7124. /**
  7125. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7126. * This helper method determine if dataItem has extra option besides value
  7127. */
  7128. function isDataItemOption(dataItem) {
  7129. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7130. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7131. }
  7132. /**
  7133. * Mapping to existings for merge.
  7134. *
  7135. * Mode "normalMege":
  7136. * The mapping result (merge result) will keep the order of the existing
  7137. * component, rather than the order of new option. Because we should ensure
  7138. * some specified index reference (like xAxisIndex) keep work.
  7139. * And in most cases, "merge option" is used to update partial option but not
  7140. * be expected to change the order.
  7141. *
  7142. * Mode "replaceMege":
  7143. * (1) Only the id mapped components will be merged.
  7144. * (2) Other existing components (except internal compoonets) will be removed.
  7145. * (3) Other new options will be used to create new component.
  7146. * (4) The index of the existing compoents will not be modified.
  7147. * That means their might be "hole" after the removal.
  7148. * The new components are created first at those available index.
  7149. *
  7150. * Mode "replaceAll":
  7151. * This mode try to support that reproduce an echarts instance from another
  7152. * echarts instance (via `getOption`) in some simple cases.
  7153. * In this senario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7154. * which ensures the compoennt index referring (like `xAxisIndex: ?`) corrent. That is,
  7155. * the "hole" in `newCmptOptions` will also be kept.
  7156. * On the contrary, other modes try best to eliminate holes.
  7157. * PENDING: This is an experimental mode yet.
  7158. *
  7159. * @return See the comment of <MappingResult>.
  7160. */
  7161. function mappingToExists(existings, newCmptOptions, mode) {
  7162. var isNormalMergeMode = mode === 'normalMerge';
  7163. var isReplaceMergeMode = mode === 'replaceMerge';
  7164. var isReplaceAllMode = mode === 'replaceAll';
  7165. existings = existings || [];
  7166. newCmptOptions = (newCmptOptions || []).slice();
  7167. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7168. each(newCmptOptions, function (cmptOption, index) {
  7169. if (!isObject(cmptOption)) {
  7170. newCmptOptions[index] = null;
  7171. return;
  7172. }
  7173. if ("development" !== 'production') {
  7174. // There is some legacy case that name is set as `false`.
  7175. // But should work normally rather than throw error.
  7176. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7177. warnInvalidateIdOrName(cmptOption.id);
  7178. }
  7179. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7180. warnInvalidateIdOrName(cmptOption.name);
  7181. }
  7182. }
  7183. });
  7184. var result = prepareResult(existings, existingIdIdxMap, mode);
  7185. if (isNormalMergeMode || isReplaceMergeMode) {
  7186. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7187. }
  7188. if (isNormalMergeMode) {
  7189. mappingByName(result, newCmptOptions);
  7190. }
  7191. if (isNormalMergeMode || isReplaceMergeMode) {
  7192. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7193. } else if (isReplaceAllMode) {
  7194. mappingInReplaceAllMode(result, newCmptOptions);
  7195. }
  7196. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7197. // forEach will ommit those items and result in incorrect result.
  7198. return result;
  7199. }
  7200. function prepareResult(existings, existingIdIdxMap, mode) {
  7201. var result = [];
  7202. if (mode === 'replaceAll') {
  7203. return result;
  7204. } // Do not use native `map` to in case that the array `existings`
  7205. // contains elided items, which will be ommited.
  7206. for (var index = 0; index < existings.length; index++) {
  7207. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7208. if (existing && existing.id != null) {
  7209. existingIdIdxMap.set(existing.id, index);
  7210. } // For non-internal-componnets:
  7211. // Mode "normalMerge": all existings kept.
  7212. // Mode "replaceMerge": all existing removed unless mapped by id.
  7213. // For internal-components:
  7214. // go with "replaceMerge" approach in both mode.
  7215. result.push({
  7216. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7217. newOption: null,
  7218. keyInfo: null,
  7219. brandNew: null
  7220. });
  7221. }
  7222. return result;
  7223. }
  7224. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7225. // Mapping by id if specified.
  7226. each(newCmptOptions, function (cmptOption, index) {
  7227. if (!cmptOption || cmptOption.id == null) {
  7228. return;
  7229. }
  7230. var optionId = makeComparableKey(cmptOption.id);
  7231. var existingIdx = existingIdIdxMap.get(optionId);
  7232. if (existingIdx != null) {
  7233. var resultItem = result[existingIdx];
  7234. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7235. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7236. // the existings rather than creating new component model.
  7237. resultItem.existing = existings[existingIdx];
  7238. newCmptOptions[index] = null;
  7239. }
  7240. });
  7241. }
  7242. function mappingByName(result, newCmptOptions) {
  7243. // Mapping by name if specified.
  7244. each(newCmptOptions, function (cmptOption, index) {
  7245. if (!cmptOption || cmptOption.name == null) {
  7246. return;
  7247. }
  7248. for (var i = 0; i < result.length; i++) {
  7249. var existing = result[i].existing;
  7250. if (!result[i].newOption // Consider name: two map to one.
  7251. // Can not match when both ids existing but different.
  7252. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  7253. result[i].newOption = cmptOption;
  7254. newCmptOptions[index] = null;
  7255. return;
  7256. }
  7257. }
  7258. });
  7259. }
  7260. function mappingByIndex(result, newCmptOptions, brandNew) {
  7261. each(newCmptOptions, function (cmptOption) {
  7262. if (!cmptOption) {
  7263. return;
  7264. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  7265. var resultItem;
  7266. var nextIdx = 0;
  7267. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  7268. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  7269. // after mapping performed, model will always be assigned with an id if user not given.
  7270. // After that all models have id.
  7271. // (2) If new option has id, it can only set to a hole or append to the last. It should
  7272. // not be merged to the existings with different id. Because id should not be overwritten.
  7273. // (3) Name can be overwritten, because axis use name as 'show label text'.
  7274. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  7275. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  7276. nextIdx++;
  7277. }
  7278. if (resultItem) {
  7279. resultItem.newOption = cmptOption;
  7280. resultItem.brandNew = brandNew;
  7281. } else {
  7282. result.push({
  7283. newOption: cmptOption,
  7284. brandNew: brandNew,
  7285. existing: null,
  7286. keyInfo: null
  7287. });
  7288. }
  7289. nextIdx++;
  7290. });
  7291. }
  7292. function mappingInReplaceAllMode(result, newCmptOptions) {
  7293. each(newCmptOptions, function (cmptOption) {
  7294. // The feature "reproduce" requires "hole" will also reproduced
  7295. // in case that compoennt index referring are broken.
  7296. result.push({
  7297. newOption: cmptOption,
  7298. brandNew: true,
  7299. existing: null,
  7300. keyInfo: null
  7301. });
  7302. });
  7303. }
  7304. /**
  7305. * Make id and name for mapping result (result of mappingToExists)
  7306. * into `keyInfo` field.
  7307. */
  7308. function makeIdAndName(mapResult) {
  7309. // We use this id to hash component models and view instances
  7310. // in echarts. id can be specified by user, or auto generated.
  7311. // The id generation rule ensures new view instance are able
  7312. // to mapped to old instance when setOption are called in
  7313. // no-merge mode. So we generate model id by name and plus
  7314. // type in view id.
  7315. // name can be duplicated among components, which is convenient
  7316. // to specify multi components (like series) by one name.
  7317. // Ensure that each id is distinct.
  7318. var idMap = createHashMap();
  7319. each(mapResult, function (item) {
  7320. var existing = item.existing;
  7321. existing && idMap.set(existing.id, item);
  7322. });
  7323. each(mapResult, function (item) {
  7324. var opt = item.newOption; // Force ensure id not duplicated.
  7325. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  7326. opt && opt.id != null && idMap.set(opt.id, item);
  7327. !item.keyInfo && (item.keyInfo = {});
  7328. }); // Make name and id.
  7329. each(mapResult, function (item, index) {
  7330. var existing = item.existing;
  7331. var opt = item.newOption;
  7332. var keyInfo = item.keyInfo;
  7333. if (!isObject(opt)) {
  7334. return;
  7335. } // name can be overwitten. Consider case: axis.name = '20km'.
  7336. // But id generated by name will not be changed, which affect
  7337. // only in that case: setOption with 'not merge mode' and view
  7338. // instance will be recreated, which can be accepted.
  7339. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid diffferent series has the same name,
  7340. // because name may be used like in color pallet.
  7341. : DUMMY_COMPONENT_NAME_PREFIX + index;
  7342. if (existing) {
  7343. keyInfo.id = makeComparableKey(existing.id);
  7344. } else if (opt.id != null) {
  7345. keyInfo.id = makeComparableKey(opt.id);
  7346. } else {
  7347. // Consider this situatoin:
  7348. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  7349. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  7350. // Series with the same name between optionA and optionB
  7351. // should be mapped.
  7352. var idNum = 0;
  7353. do {
  7354. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  7355. } while (idMap.get(keyInfo.id));
  7356. }
  7357. idMap.set(keyInfo.id, item);
  7358. });
  7359. }
  7360. function keyExistAndEqual(attr, obj1, obj2) {
  7361. var key1 = convertOptionIdName(obj1[attr], null);
  7362. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  7363. return key1 != null && key2 != null && key1 === key2;
  7364. }
  7365. /**
  7366. * @return return null if not exist.
  7367. */
  7368. function makeComparableKey(val) {
  7369. if ("development" !== 'production') {
  7370. if (val == null) {
  7371. throw new Error();
  7372. }
  7373. }
  7374. return convertOptionIdName(val, '');
  7375. }
  7376. function convertOptionIdName(idOrName, defaultValue) {
  7377. if (idOrName == null) {
  7378. return defaultValue;
  7379. }
  7380. var type = typeof idOrName;
  7381. return type === 'string' ? idOrName : type === 'number' || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  7382. }
  7383. function warnInvalidateIdOrName(idOrName) {
  7384. if ("development" !== 'production') {
  7385. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  7386. }
  7387. }
  7388. function isValidIdOrName(idOrName) {
  7389. return isStringSafe(idOrName) || isNumeric(idOrName);
  7390. }
  7391. function isNameSpecified(componentModel) {
  7392. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  7393. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  7394. }
  7395. /**
  7396. * @public
  7397. * @param {Object} cmptOption
  7398. * @return {boolean}
  7399. */
  7400. function isComponentIdInternal(cmptOption) {
  7401. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  7402. }
  7403. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  7404. // Set mainType and complete subType.
  7405. each(mappingResult, function (item) {
  7406. var newOption = item.newOption;
  7407. if (isObject(newOption)) {
  7408. item.keyInfo.mainType = mainType;
  7409. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  7410. }
  7411. });
  7412. }
  7413. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  7414. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  7415. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  7416. return subType;
  7417. }
  7418. /**
  7419. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  7420. * each of which can be Array or primary type.
  7421. * @return dataIndex If not found, return undefined/null.
  7422. */
  7423. function queryDataIndex(data, payload) {
  7424. if (payload.dataIndexInside != null) {
  7425. return payload.dataIndexInside;
  7426. } else if (payload.dataIndex != null) {
  7427. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  7428. return data.indexOfRawIndex(value);
  7429. }) : data.indexOfRawIndex(payload.dataIndex);
  7430. } else if (payload.name != null) {
  7431. return isArray(payload.name) ? map(payload.name, function (value) {
  7432. return data.indexOfName(value);
  7433. }) : data.indexOfName(payload.name);
  7434. }
  7435. }
  7436. /**
  7437. * Enable property storage to any host object.
  7438. * Notice: Serialization is not supported.
  7439. *
  7440. * For example:
  7441. * let inner = zrUitl.makeInner();
  7442. *
  7443. * function some1(hostObj) {
  7444. * inner(hostObj).someProperty = 1212;
  7445. * ...
  7446. * }
  7447. * function some2() {
  7448. * let fields = inner(this);
  7449. * fields.someProperty1 = 1212;
  7450. * fields.someProperty2 = 'xx';
  7451. * ...
  7452. * }
  7453. *
  7454. * @return {Function}
  7455. */
  7456. function makeInner() {
  7457. var key = '__ec_inner_' + innerUniqueIndex++;
  7458. return function (hostObj) {
  7459. return hostObj[key] || (hostObj[key] = {});
  7460. };
  7461. }
  7462. var innerUniqueIndex = getRandomIdBase();
  7463. /**
  7464. * The same behavior as `component.getReferringComponents`.
  7465. */
  7466. function parseFinder(ecModel, finderInput, opt) {
  7467. var finder;
  7468. if (isString(finderInput)) {
  7469. var obj = {};
  7470. obj[finderInput + 'Index'] = 0;
  7471. finder = obj;
  7472. } else {
  7473. finder = finderInput;
  7474. }
  7475. var queryOptionMap = createHashMap();
  7476. var result = {};
  7477. var mainTypeSpecified = false;
  7478. each(finder, function (value, key) {
  7479. // Exclude 'dataIndex' and other illgal keys.
  7480. if (key === 'dataIndex' || key === 'dataIndexInside') {
  7481. result[key] = value;
  7482. return;
  7483. }
  7484. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  7485. var mainType = parsedKey[1];
  7486. var queryType = (parsedKey[2] || '').toLowerCase();
  7487. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  7488. return;
  7489. }
  7490. mainTypeSpecified = mainTypeSpecified || !!mainType;
  7491. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  7492. queryOption[queryType] = value;
  7493. });
  7494. var defaultMainType = opt ? opt.defaultMainType : null;
  7495. if (!mainTypeSpecified && defaultMainType) {
  7496. queryOptionMap.set(defaultMainType, {});
  7497. }
  7498. queryOptionMap.each(function (queryOption, mainType) {
  7499. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  7500. useDefault: defaultMainType === mainType,
  7501. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  7502. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  7503. });
  7504. result[mainType + 'Models'] = queryResult.models;
  7505. result[mainType + 'Model'] = queryResult.models[0];
  7506. });
  7507. return result;
  7508. }
  7509. var SINGLE_REFERRING = {
  7510. useDefault: true,
  7511. enableAll: false,
  7512. enableNone: false
  7513. };
  7514. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  7515. opt = opt || SINGLE_REFERRING;
  7516. var indexOption = userOption.index;
  7517. var idOption = userOption.id;
  7518. var nameOption = userOption.name;
  7519. var result = {
  7520. models: null,
  7521. specified: indexOption != null || idOption != null || nameOption != null
  7522. };
  7523. if (!result.specified) {
  7524. // Use the first as default if `useDefault`.
  7525. var firstCmpt = void 0;
  7526. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  7527. return result;
  7528. }
  7529. if (indexOption === 'none' || indexOption === false) {
  7530. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  7531. result.models = [];
  7532. return result;
  7533. } // `queryComponents` will return all components if
  7534. // both all of index/id/name are null/undefined.
  7535. if (indexOption === 'all') {
  7536. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  7537. indexOption = idOption = nameOption = null;
  7538. }
  7539. result.models = ecModel.queryComponents({
  7540. mainType: mainType,
  7541. index: indexOption,
  7542. id: idOption,
  7543. name: nameOption
  7544. });
  7545. return result;
  7546. }
  7547. function setAttribute(dom, key, value) {
  7548. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  7549. }
  7550. function getAttribute(dom, key) {
  7551. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  7552. }
  7553. /**
  7554. * Interpolate raw values of a series with percent
  7555. *
  7556. * @param data data
  7557. * @param labelModel label model of the text element
  7558. * @param sourceValue start value. May be null/undefined when init.
  7559. * @param targetValue end value
  7560. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  7561. * @return interpolated values
  7562. * If `sourceValue` and `targetValue` are `number`, return `number`.
  7563. * If `sourceValue` and `targetValue` are `string`, return `string`.
  7564. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  7565. * Other cases do not supported.
  7566. */
  7567. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  7568. var isAutoPrecision = precision == null || precision === 'auto';
  7569. if (targetValue == null) {
  7570. return targetValue;
  7571. }
  7572. if (typeof targetValue === 'number') {
  7573. var value = interpolateNumber(sourceValue || 0, targetValue, percent);
  7574. return round(value, isAutoPrecision ? Math.max(getPrecisionSafe(sourceValue || 0), getPrecisionSafe(targetValue)) : precision);
  7575. } else if (typeof targetValue === 'string') {
  7576. return percent < 1 ? sourceValue : targetValue;
  7577. } else {
  7578. var interpolated = [];
  7579. var leftArr = sourceValue;
  7580. var rightArr = targetValue;
  7581. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  7582. for (var i = 0; i < length_1; ++i) {
  7583. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  7584. if (info.type === 'ordinal') {
  7585. // In init, there is no `sourceValue`, but should better not to get undefined result.
  7586. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  7587. } else {
  7588. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  7589. var rightVal = rightArr[i];
  7590. var value = interpolateNumber(leftVal, rightVal, percent);
  7591. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecisionSafe(leftVal), getPrecisionSafe(rightVal)) : precision);
  7592. }
  7593. }
  7594. return interpolated;
  7595. }
  7596. }
  7597. var TYPE_DELIMITER = '.';
  7598. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  7599. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  7600. /**
  7601. * Notice, parseClassType('') should returns {main: '', sub: ''}
  7602. * @public
  7603. */
  7604. function parseClassType(componentType) {
  7605. var ret = {
  7606. main: '',
  7607. sub: ''
  7608. };
  7609. if (componentType) {
  7610. var typeArr = componentType.split(TYPE_DELIMITER);
  7611. ret.main = typeArr[0] || '';
  7612. ret.sub = typeArr[1] || '';
  7613. }
  7614. return ret;
  7615. }
  7616. /**
  7617. * @public
  7618. */
  7619. function checkClassType(componentType) {
  7620. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  7621. }
  7622. function isExtendedClass(clz) {
  7623. return !!(clz && clz[IS_EXTENDED_CLASS]);
  7624. }
  7625. /**
  7626. * Implements `ExtendableConstructor` for `rootClz`.
  7627. *
  7628. * @usage
  7629. * ```ts
  7630. * class Xxx {}
  7631. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  7632. * enableClassExtend(Xxx as XxxConstructor);
  7633. * ```
  7634. */
  7635. function enableClassExtend(rootClz, mandatoryMethods) {
  7636. rootClz.$constructor = rootClz; // FIXME: not necessary?
  7637. rootClz.extend = function (proto) {
  7638. if ("development" !== 'production') {
  7639. each(mandatoryMethods, function (method) {
  7640. if (!proto[method]) {
  7641. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  7642. }
  7643. });
  7644. }
  7645. var superClass = this; // For backward compat, we both support ts class inheritance and this
  7646. // "extend" approach.
  7647. // The constructor should keep the same behavior as ts class inheritance:
  7648. // If this constructor/$constructor is not declared, auto invoke the super
  7649. // constructor.
  7650. // If this constructor/$constructor is declared, it is responsible for
  7651. // calling the super constructor.
  7652. function ExtendedClass() {
  7653. var args = [];
  7654. for (var _i = 0; _i < arguments.length; _i++) {
  7655. args[_i] = arguments[_i];
  7656. }
  7657. if (!proto.$constructor) {
  7658. if (!isESClass(superClass)) {
  7659. // Will throw error if superClass is an es6 native class.
  7660. superClass.apply(this, arguments);
  7661. } else {
  7662. var ins = createObject( // @ts-ignore
  7663. ExtendedClass.prototype, new (superClass.bind.apply(superClass, __spreadArrays([void 0], args)))());
  7664. return ins;
  7665. }
  7666. } else {
  7667. proto.$constructor.apply(this, arguments);
  7668. }
  7669. }
  7670. ExtendedClass[IS_EXTENDED_CLASS] = true;
  7671. extend(ExtendedClass.prototype, proto);
  7672. ExtendedClass.extend = this.extend;
  7673. ExtendedClass.superCall = superCall;
  7674. ExtendedClass.superApply = superApply;
  7675. inherits(ExtendedClass, this);
  7676. ExtendedClass.superClass = superClass;
  7677. return ExtendedClass;
  7678. };
  7679. }
  7680. function isESClass(fn) {
  7681. return typeof fn === 'function' && /^class\s/.test(Function.prototype.toString.call(fn));
  7682. }
  7683. /**
  7684. * A work around to both support ts extend and this extend mechanism.
  7685. * on sub-class.
  7686. * @usage
  7687. * ```ts
  7688. * class Component { ... }
  7689. * classUtil.enableClassExtend(Component);
  7690. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  7691. *
  7692. * class Series extends Component { ... }
  7693. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  7694. * Component.markExtend(Series);
  7695. * ```
  7696. */
  7697. function mountExtend(SubClz, SupperClz) {
  7698. SubClz.extend = SupperClz.extend;
  7699. } // A random offset.
  7700. var classBase = Math.round(Math.random() * 10);
  7701. /**
  7702. * Implements `CheckableConstructor` for `target`.
  7703. * Can not use instanceof, consider different scope by
  7704. * cross domain or es module import in ec extensions.
  7705. * Mount a method "isInstance()" to Clz.
  7706. *
  7707. * @usage
  7708. * ```ts
  7709. * class Xxx {}
  7710. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  7711. * enableClassCheck(Xxx as XxxConstructor)
  7712. * ```
  7713. */
  7714. function enableClassCheck(target) {
  7715. var classAttr = ['__\0is_clz', classBase++].join('_');
  7716. target.prototype[classAttr] = true;
  7717. if ("development" !== 'production') {
  7718. assert(!target.isInstance, 'The method "is" can not be defined.');
  7719. }
  7720. target.isInstance = function (obj) {
  7721. return !!(obj && obj[classAttr]);
  7722. };
  7723. } // superCall should have class info, which can not be fetch from 'this'.
  7724. // Consider this case:
  7725. // class A has method f,
  7726. // class B inherits class A, overrides method f, f call superApply('f'),
  7727. // class C inherits class B, do not overrides method f,
  7728. // then when method of class C is called, dead loop occured.
  7729. function superCall(context, methodName) {
  7730. var args = [];
  7731. for (var _i = 2; _i < arguments.length; _i++) {
  7732. args[_i - 2] = arguments[_i];
  7733. }
  7734. return this.superClass.prototype[methodName].apply(context, args);
  7735. }
  7736. function superApply(context, methodName, args) {
  7737. return this.superClass.prototype[methodName].apply(context, args);
  7738. }
  7739. /**
  7740. * Implements `ClassManager` for `target`
  7741. *
  7742. * @usage
  7743. * ```ts
  7744. * class Xxx {}
  7745. * type XxxConstructor = typeof Xxx & ClassManager
  7746. * enableClassManagement(Xxx as XxxConstructor);
  7747. * ```
  7748. */
  7749. function enableClassManagement(target) {
  7750. /**
  7751. * Component model classes
  7752. * key: componentType,
  7753. * value:
  7754. * componentClass, when componentType is 'xxx'
  7755. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  7756. */
  7757. var storage = {};
  7758. target.registerClass = function (clz) {
  7759. // `type` should not be a "instance memeber".
  7760. // If using TS class, should better declared as `static type = 'series.pie'`.
  7761. // otherwise users have to mount `type` on prototype manually.
  7762. // For backward compat and enable instance visit type via `this.type`,
  7763. // we stil support fetch `type` from prototype.
  7764. var componentFullType = clz.type || clz.prototype.type;
  7765. if (componentFullType) {
  7766. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  7767. clz.prototype.type = componentFullType;
  7768. var componentTypeInfo = parseClassType(componentFullType);
  7769. if (!componentTypeInfo.sub) {
  7770. if ("development" !== 'production') {
  7771. if (storage[componentTypeInfo.main]) {
  7772. console.warn(componentTypeInfo.main + ' exists.');
  7773. }
  7774. }
  7775. storage[componentTypeInfo.main] = clz;
  7776. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  7777. var container = makeContainer(componentTypeInfo);
  7778. container[componentTypeInfo.sub] = clz;
  7779. }
  7780. }
  7781. return clz;
  7782. };
  7783. target.getClass = function (mainType, subType, throwWhenNotFound) {
  7784. var clz = storage[mainType];
  7785. if (clz && clz[IS_CONTAINER]) {
  7786. clz = subType ? clz[subType] : null;
  7787. }
  7788. if (throwWhenNotFound && !clz) {
  7789. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' not exists. Load it first.');
  7790. }
  7791. return clz;
  7792. };
  7793. target.getClassesByMainType = function (componentType) {
  7794. var componentTypeInfo = parseClassType(componentType);
  7795. var result = [];
  7796. var obj = storage[componentTypeInfo.main];
  7797. if (obj && obj[IS_CONTAINER]) {
  7798. each(obj, function (o, type) {
  7799. type !== IS_CONTAINER && result.push(o);
  7800. });
  7801. } else {
  7802. result.push(obj);
  7803. }
  7804. return result;
  7805. };
  7806. target.hasClass = function (componentType) {
  7807. // Just consider componentType.main.
  7808. var componentTypeInfo = parseClassType(componentType);
  7809. return !!storage[componentTypeInfo.main];
  7810. };
  7811. /**
  7812. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  7813. */
  7814. target.getAllClassMainTypes = function () {
  7815. var types = [];
  7816. each(storage, function (obj, type) {
  7817. types.push(type);
  7818. });
  7819. return types;
  7820. };
  7821. /**
  7822. * If a main type is container and has sub types
  7823. */
  7824. target.hasSubTypes = function (componentType) {
  7825. var componentTypeInfo = parseClassType(componentType);
  7826. var obj = storage[componentTypeInfo.main];
  7827. return obj && obj[IS_CONTAINER];
  7828. };
  7829. function makeContainer(componentTypeInfo) {
  7830. var container = storage[componentTypeInfo.main];
  7831. if (!container || !container[IS_CONTAINER]) {
  7832. container = storage[componentTypeInfo.main] = {};
  7833. container[IS_CONTAINER] = true;
  7834. }
  7835. return container;
  7836. }
  7837. } // /**
  7838. // * @param {string|Array.<string>} properties
  7839. // */
  7840. // export function setReadOnly(obj, properties) {
  7841. // FIXME It seems broken in IE8 simulation of IE11
  7842. // if (!zrUtil.isArray(properties)) {
  7843. // properties = properties != null ? [properties] : [];
  7844. // }
  7845. // zrUtil.each(properties, function (prop) {
  7846. // let value = obj[prop];
  7847. // Object.defineProperty
  7848. // && Object.defineProperty(obj, prop, {
  7849. // value: value, writable: false
  7850. // });
  7851. // zrUtil.isArray(obj[prop])
  7852. // && Object.freeze
  7853. // && Object.freeze(obj[prop]);
  7854. // });
  7855. // }
  7856. function makeStyleMapper(properties, ignoreParent) {
  7857. // Normalize
  7858. for (var i = 0; i < properties.length; i++) {
  7859. if (!properties[i][1]) {
  7860. properties[i][1] = properties[i][0];
  7861. }
  7862. }
  7863. ignoreParent = ignoreParent || false;
  7864. return function (model, excludes, includes) {
  7865. var style = {};
  7866. for (var i = 0; i < properties.length; i++) {
  7867. var propName = properties[i][1];
  7868. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  7869. continue;
  7870. }
  7871. var val = model.getShallow(propName, ignoreParent);
  7872. if (val != null) {
  7873. style[properties[i][0]] = val;
  7874. }
  7875. } // TODO Text or image?
  7876. return style;
  7877. };
  7878. }
  7879. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  7880. // So do not transfer decal directly.
  7881. ];
  7882. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  7883. var AreaStyleMixin =
  7884. /** @class */
  7885. function () {
  7886. function AreaStyleMixin() {}
  7887. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  7888. return getAreaStyle(this, excludes, includes);
  7889. };
  7890. return AreaStyleMixin;
  7891. }();
  7892. var globalImageCache = new LRU(50);
  7893. function findExistImage(newImageOrSrc) {
  7894. if (typeof newImageOrSrc === 'string') {
  7895. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  7896. return cachedImgObj && cachedImgObj.image;
  7897. }
  7898. else {
  7899. return newImageOrSrc;
  7900. }
  7901. }
  7902. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  7903. if (!newImageOrSrc) {
  7904. return image;
  7905. }
  7906. else if (typeof newImageOrSrc === 'string') {
  7907. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  7908. return image;
  7909. }
  7910. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  7911. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  7912. if (cachedImgObj) {
  7913. image = cachedImgObj.image;
  7914. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  7915. }
  7916. else {
  7917. image = new Image();
  7918. image.onload = image.onerror = imageOnLoad;
  7919. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  7920. image: image,
  7921. pending: [pendingWrap]
  7922. });
  7923. image.src = image.__zrImageSrc = newImageOrSrc;
  7924. }
  7925. return image;
  7926. }
  7927. else {
  7928. return newImageOrSrc;
  7929. }
  7930. }
  7931. function imageOnLoad() {
  7932. var cachedImgObj = this.__cachedImgObj;
  7933. this.onload = this.onerror = this.__cachedImgObj = null;
  7934. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  7935. var pendingWrap = cachedImgObj.pending[i];
  7936. var cb = pendingWrap.cb;
  7937. cb && cb(this, pendingWrap.cbPayload);
  7938. pendingWrap.hostEl.dirty();
  7939. }
  7940. cachedImgObj.pending.length = 0;
  7941. }
  7942. function isImageReady(image) {
  7943. return image && image.width && image.height;
  7944. }
  7945. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  7946. function truncateText(text, containerWidth, font, ellipsis, options) {
  7947. if (!containerWidth) {
  7948. return '';
  7949. }
  7950. var textLines = (text + '').split('\n');
  7951. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7952. for (var i = 0, len = textLines.length; i < len; i++) {
  7953. textLines[i] = truncateSingleLine(textLines[i], options);
  7954. }
  7955. return textLines.join('\n');
  7956. }
  7957. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7958. options = options || {};
  7959. var preparedOpts = extend({}, options);
  7960. preparedOpts.font = font;
  7961. ellipsis = retrieve2(ellipsis, '...');
  7962. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  7963. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  7964. preparedOpts.cnCharWidth = getWidth('国', font);
  7965. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  7966. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  7967. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  7968. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7969. contentWidth -= ascCharWidth;
  7970. }
  7971. var ellipsisWidth = getWidth(ellipsis, font);
  7972. if (ellipsisWidth > contentWidth) {
  7973. ellipsis = '';
  7974. ellipsisWidth = 0;
  7975. }
  7976. contentWidth = containerWidth - ellipsisWidth;
  7977. preparedOpts.ellipsis = ellipsis;
  7978. preparedOpts.ellipsisWidth = ellipsisWidth;
  7979. preparedOpts.contentWidth = contentWidth;
  7980. preparedOpts.containerWidth = containerWidth;
  7981. return preparedOpts;
  7982. }
  7983. function truncateSingleLine(textLine, options) {
  7984. var containerWidth = options.containerWidth;
  7985. var font = options.font;
  7986. var contentWidth = options.contentWidth;
  7987. if (!containerWidth) {
  7988. return '';
  7989. }
  7990. var lineWidth = getWidth(textLine, font);
  7991. if (lineWidth <= containerWidth) {
  7992. return textLine;
  7993. }
  7994. for (var j = 0;; j++) {
  7995. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7996. textLine += options.ellipsis;
  7997. break;
  7998. }
  7999. var subLength = j === 0
  8000. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8001. : lineWidth > 0
  8002. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8003. : 0;
  8004. textLine = textLine.substr(0, subLength);
  8005. lineWidth = getWidth(textLine, font);
  8006. }
  8007. if (textLine === '') {
  8008. textLine = options.placeholder;
  8009. }
  8010. return textLine;
  8011. }
  8012. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8013. var width = 0;
  8014. var i = 0;
  8015. for (var len = text.length; i < len && width < contentWidth; i++) {
  8016. var charCode = text.charCodeAt(i);
  8017. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8018. }
  8019. return i;
  8020. }
  8021. function parsePlainText(text, style) {
  8022. text != null && (text += '');
  8023. var overflow = style.overflow;
  8024. var padding = style.padding;
  8025. var font = style.font;
  8026. var truncate = overflow === 'truncate';
  8027. var calculatedLineHeight = getLineHeight(font);
  8028. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8029. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8030. var width = style.width;
  8031. var lines;
  8032. if (width != null && overflow === 'break' || overflow === 'breakAll') {
  8033. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8034. }
  8035. else {
  8036. lines = text ? text.split('\n') : [];
  8037. }
  8038. var contentHeight = lines.length * lineHeight;
  8039. var height = retrieve2(style.height, contentHeight);
  8040. if (contentHeight > height && truncateLineOverflow) {
  8041. var lineCount = Math.floor(height / lineHeight);
  8042. lines = lines.slice(0, lineCount);
  8043. }
  8044. var outerHeight = height;
  8045. var outerWidth = width;
  8046. if (padding) {
  8047. outerHeight += padding[0] + padding[2];
  8048. if (outerWidth != null) {
  8049. outerWidth += padding[1] + padding[3];
  8050. }
  8051. }
  8052. if (text && truncate && outerWidth != null) {
  8053. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8054. minChar: style.truncateMinChar,
  8055. placeholder: style.placeholder
  8056. });
  8057. for (var i = 0; i < lines.length; i++) {
  8058. lines[i] = truncateSingleLine(lines[i], options);
  8059. }
  8060. }
  8061. if (width == null) {
  8062. var maxWidth = 0;
  8063. for (var i = 0; i < lines.length; i++) {
  8064. maxWidth = Math.max(getWidth(lines[i], font), maxWidth);
  8065. }
  8066. width = maxWidth;
  8067. }
  8068. return {
  8069. lines: lines,
  8070. height: height,
  8071. outerHeight: outerHeight,
  8072. lineHeight: lineHeight,
  8073. calculatedLineHeight: calculatedLineHeight,
  8074. contentHeight: contentHeight,
  8075. width: width
  8076. };
  8077. }
  8078. var RichTextToken = (function () {
  8079. function RichTextToken() {
  8080. }
  8081. return RichTextToken;
  8082. }());
  8083. var RichTextLine = (function () {
  8084. function RichTextLine(tokens) {
  8085. this.tokens = [];
  8086. if (tokens) {
  8087. this.tokens = tokens;
  8088. }
  8089. }
  8090. return RichTextLine;
  8091. }());
  8092. var RichTextContentBlock = (function () {
  8093. function RichTextContentBlock() {
  8094. this.width = 0;
  8095. this.height = 0;
  8096. this.contentWidth = 0;
  8097. this.contentHeight = 0;
  8098. this.outerWidth = 0;
  8099. this.outerHeight = 0;
  8100. this.lines = [];
  8101. }
  8102. return RichTextContentBlock;
  8103. }());
  8104. function parseRichText(text, style) {
  8105. var contentBlock = new RichTextContentBlock();
  8106. text != null && (text += '');
  8107. if (!text) {
  8108. return contentBlock;
  8109. }
  8110. var topWidth = style.width;
  8111. var topHeight = style.height;
  8112. var overflow = style.overflow;
  8113. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8114. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8115. : null;
  8116. var lastIndex = STYLE_REG.lastIndex = 0;
  8117. var result;
  8118. while ((result = STYLE_REG.exec(text)) != null) {
  8119. var matchedIndex = result.index;
  8120. if (matchedIndex > lastIndex) {
  8121. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8122. }
  8123. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8124. lastIndex = STYLE_REG.lastIndex;
  8125. }
  8126. if (lastIndex < text.length) {
  8127. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8128. }
  8129. var pendingList = [];
  8130. var calculatedHeight = 0;
  8131. var calculatedWidth = 0;
  8132. var stlPadding = style.padding;
  8133. var truncate = overflow === 'truncate';
  8134. var truncateLine = style.lineOverflow === 'truncate';
  8135. function finishLine(line, lineWidth, lineHeight) {
  8136. line.width = lineWidth;
  8137. line.lineHeight = lineHeight;
  8138. calculatedHeight += lineHeight;
  8139. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8140. }
  8141. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8142. var line = contentBlock.lines[i];
  8143. var lineHeight = 0;
  8144. var lineWidth = 0;
  8145. for (var j = 0; j < line.tokens.length; j++) {
  8146. var token = line.tokens[j];
  8147. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8148. var textPadding = token.textPadding = tokenStyle.padding;
  8149. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8150. var font = token.font = tokenStyle.font || style.font;
  8151. token.contentHeight = getLineHeight(font);
  8152. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8153. token.innerHeight = tokenHeight;
  8154. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8155. token.height = tokenHeight;
  8156. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8157. token.align = tokenStyle && tokenStyle.align || style.align;
  8158. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8159. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8160. if (j > 0) {
  8161. line.tokens = line.tokens.slice(0, j);
  8162. finishLine(line, lineWidth, lineHeight);
  8163. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8164. }
  8165. else {
  8166. contentBlock.lines = contentBlock.lines.slice(0, i);
  8167. }
  8168. break outer;
  8169. }
  8170. var styleTokenWidth = tokenStyle.width;
  8171. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8172. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8173. token.percentWidth = styleTokenWidth;
  8174. pendingList.push(token);
  8175. token.contentWidth = getWidth(token.text, font);
  8176. }
  8177. else {
  8178. if (tokenWidthNotSpecified) {
  8179. var textBackgroundColor = tokenStyle.backgroundColor;
  8180. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8181. if (bgImg) {
  8182. bgImg = findExistImage(bgImg);
  8183. if (isImageReady(bgImg)) {
  8184. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8185. }
  8186. }
  8187. }
  8188. var remainTruncWidth = truncate && topWidth != null
  8189. ? topWidth - lineWidth : null;
  8190. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8191. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8192. token.text = '';
  8193. token.width = token.contentWidth = 0;
  8194. }
  8195. else {
  8196. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8197. token.width = token.contentWidth = getWidth(token.text, font);
  8198. }
  8199. }
  8200. else {
  8201. token.contentWidth = getWidth(token.text, font);
  8202. }
  8203. }
  8204. token.width += paddingH;
  8205. lineWidth += token.width;
  8206. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8207. }
  8208. finishLine(line, lineWidth, lineHeight);
  8209. }
  8210. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8211. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8212. contentBlock.contentHeight = calculatedHeight;
  8213. contentBlock.contentWidth = calculatedWidth;
  8214. if (stlPadding) {
  8215. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  8216. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  8217. }
  8218. for (var i = 0; i < pendingList.length; i++) {
  8219. var token = pendingList[i];
  8220. var percentWidth = token.percentWidth;
  8221. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  8222. }
  8223. return contentBlock;
  8224. }
  8225. function pushTokens(block, str, style, wrapInfo, styleName) {
  8226. var isEmptyStr = str === '';
  8227. var tokenStyle = styleName && style.rich[styleName] || {};
  8228. var lines = block.lines;
  8229. var font = tokenStyle.font || style.font;
  8230. var newLine = false;
  8231. var strLines;
  8232. var linesWidths;
  8233. if (wrapInfo) {
  8234. var tokenPadding = tokenStyle.padding;
  8235. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  8236. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  8237. var outerWidth_1 = parsePercent$2(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  8238. if (lines.length > 0) {
  8239. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  8240. strLines = str.split('\n');
  8241. newLine = true;
  8242. }
  8243. }
  8244. wrapInfo.accumWidth = outerWidth_1;
  8245. }
  8246. else {
  8247. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  8248. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  8249. linesWidths = res.linesWidths;
  8250. strLines = res.lines;
  8251. }
  8252. }
  8253. else {
  8254. strLines = str.split('\n');
  8255. }
  8256. for (var i = 0; i < strLines.length; i++) {
  8257. var text = strLines[i];
  8258. var token = new RichTextToken();
  8259. token.styleName = styleName;
  8260. token.text = text;
  8261. token.isLineHolder = !text && !isEmptyStr;
  8262. if (typeof tokenStyle.width === 'number') {
  8263. token.width = tokenStyle.width;
  8264. }
  8265. else {
  8266. token.width = linesWidths
  8267. ? linesWidths[i]
  8268. : getWidth(text, font);
  8269. }
  8270. if (!i && !newLine) {
  8271. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  8272. var tokensLen = tokens.length;
  8273. (tokensLen === 1 && tokens[0].isLineHolder)
  8274. ? (tokens[0] = token)
  8275. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  8276. }
  8277. else {
  8278. lines.push(new RichTextLine([token]));
  8279. }
  8280. }
  8281. }
  8282. function isLatin(ch) {
  8283. var code = ch.charCodeAt(0);
  8284. return code >= 0x21 && code <= 0xFF;
  8285. }
  8286. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  8287. obj[ch] = true;
  8288. return obj;
  8289. }, {});
  8290. function isWordBreakChar(ch) {
  8291. if (isLatin(ch)) {
  8292. if (breakCharMap[ch]) {
  8293. return true;
  8294. }
  8295. return false;
  8296. }
  8297. return true;
  8298. }
  8299. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  8300. var lines = [];
  8301. var linesWidths = [];
  8302. var line = '';
  8303. var currentWord = '';
  8304. var currentWordWidth = 0;
  8305. var accumWidth = 0;
  8306. for (var i = 0; i < text.length; i++) {
  8307. var ch = text.charAt(i);
  8308. if (ch === '\n') {
  8309. if (currentWord) {
  8310. line += currentWord;
  8311. accumWidth += currentWordWidth;
  8312. }
  8313. lines.push(line);
  8314. linesWidths.push(accumWidth);
  8315. line = '';
  8316. currentWord = '';
  8317. currentWordWidth = 0;
  8318. accumWidth = 0;
  8319. continue;
  8320. }
  8321. var chWidth = getWidth(ch, font);
  8322. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  8323. if (!lines.length
  8324. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  8325. : accumWidth + chWidth > lineWidth) {
  8326. if (!accumWidth) {
  8327. if (inWord) {
  8328. lines.push(currentWord);
  8329. linesWidths.push(currentWordWidth);
  8330. currentWord = ch;
  8331. currentWordWidth = chWidth;
  8332. }
  8333. else {
  8334. lines.push(ch);
  8335. linesWidths.push(chWidth);
  8336. }
  8337. }
  8338. else if (line || currentWord) {
  8339. if (inWord) {
  8340. if (!line) {
  8341. line = currentWord;
  8342. currentWord = '';
  8343. currentWordWidth = 0;
  8344. accumWidth = currentWordWidth;
  8345. }
  8346. lines.push(line);
  8347. linesWidths.push(accumWidth - currentWordWidth);
  8348. currentWord += ch;
  8349. currentWordWidth += chWidth;
  8350. line = '';
  8351. accumWidth = currentWordWidth;
  8352. }
  8353. else {
  8354. if (currentWord) {
  8355. line += currentWord;
  8356. accumWidth += currentWordWidth;
  8357. currentWord = '';
  8358. currentWordWidth = 0;
  8359. }
  8360. lines.push(line);
  8361. linesWidths.push(accumWidth);
  8362. line = ch;
  8363. accumWidth = chWidth;
  8364. }
  8365. }
  8366. continue;
  8367. }
  8368. accumWidth += chWidth;
  8369. if (inWord) {
  8370. currentWord += ch;
  8371. currentWordWidth += chWidth;
  8372. }
  8373. else {
  8374. if (currentWord) {
  8375. line += currentWord;
  8376. currentWord = '';
  8377. currentWordWidth = 0;
  8378. }
  8379. line += ch;
  8380. }
  8381. }
  8382. if (!lines.length && !line) {
  8383. line = text;
  8384. currentWord = '';
  8385. currentWordWidth = 0;
  8386. }
  8387. if (currentWord) {
  8388. line += currentWord;
  8389. }
  8390. if (line) {
  8391. lines.push(line);
  8392. linesWidths.push(accumWidth);
  8393. }
  8394. if (lines.length === 1) {
  8395. accumWidth += lastAccumWidth;
  8396. }
  8397. return {
  8398. accumWidth: accumWidth,
  8399. lines: lines,
  8400. linesWidths: linesWidths
  8401. };
  8402. }
  8403. function parsePercent$2(value, maxValue) {
  8404. if (typeof value === 'string') {
  8405. if (value.lastIndexOf('%') >= 0) {
  8406. return parseFloat(value) / 100 * maxValue;
  8407. }
  8408. return parseFloat(value);
  8409. }
  8410. return value;
  8411. }
  8412. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  8413. var DEFAULT_COMMON_STYLE = {
  8414. shadowBlur: 0,
  8415. shadowOffsetX: 0,
  8416. shadowOffsetY: 0,
  8417. shadowColor: '#000',
  8418. opacity: 1,
  8419. blend: 'source-over'
  8420. };
  8421. var DEFAULT_COMMON_ANIMATION_PROPS = {
  8422. style: {
  8423. shadowBlur: true,
  8424. shadowOffsetX: true,
  8425. shadowOffsetY: true,
  8426. shadowColor: true,
  8427. opacity: true
  8428. }
  8429. };
  8430. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  8431. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  8432. var Displayable = (function (_super) {
  8433. __extends(Displayable, _super);
  8434. function Displayable(props) {
  8435. return _super.call(this, props) || this;
  8436. }
  8437. Displayable.prototype._init = function (props) {
  8438. var keysArr = keys(props);
  8439. for (var i = 0; i < keysArr.length; i++) {
  8440. var key = keysArr[i];
  8441. if (key === 'style') {
  8442. this.useStyle(props[key]);
  8443. }
  8444. else {
  8445. _super.prototype.attrKV.call(this, key, props[key]);
  8446. }
  8447. }
  8448. if (!this.style) {
  8449. this.useStyle({});
  8450. }
  8451. };
  8452. Displayable.prototype.beforeBrush = function () { };
  8453. Displayable.prototype.afterBrush = function () { };
  8454. Displayable.prototype.innerBeforeBrush = function () { };
  8455. Displayable.prototype.innerAfterBrush = function () { };
  8456. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  8457. var m = this.transform;
  8458. if (this.ignore
  8459. || this.invisible
  8460. || this.style.opacity === 0
  8461. || (this.culling
  8462. && isDisplayableCulled(this, viewWidth, viewHeight))
  8463. || (m && !m[0] && !m[3])) {
  8464. return false;
  8465. }
  8466. if (considerClipPath && this.__clipPaths) {
  8467. for (var i = 0; i < this.__clipPaths.length; ++i) {
  8468. if (this.__clipPaths[i].isZeroArea()) {
  8469. return false;
  8470. }
  8471. }
  8472. }
  8473. if (considerAncestors && this.parent) {
  8474. var parent_1 = this.parent;
  8475. while (parent_1) {
  8476. if (parent_1.ignore) {
  8477. return false;
  8478. }
  8479. parent_1 = parent_1.parent;
  8480. }
  8481. }
  8482. return true;
  8483. };
  8484. Displayable.prototype.contain = function (x, y) {
  8485. return this.rectContain(x, y);
  8486. };
  8487. Displayable.prototype.traverse = function (cb, context) {
  8488. cb.call(context, this);
  8489. };
  8490. Displayable.prototype.rectContain = function (x, y) {
  8491. var coord = this.transformCoordToLocal(x, y);
  8492. var rect = this.getBoundingRect();
  8493. return rect.contain(coord[0], coord[1]);
  8494. };
  8495. Displayable.prototype.getPaintRect = function () {
  8496. var rect = this._paintRect;
  8497. if (!this._paintRect || this.__dirty) {
  8498. var transform = this.transform;
  8499. var elRect = this.getBoundingRect();
  8500. var style = this.style;
  8501. var shadowSize = style.shadowBlur || 0;
  8502. var shadowOffsetX = style.shadowOffsetX || 0;
  8503. var shadowOffsetY = style.shadowOffsetY || 0;
  8504. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  8505. if (transform) {
  8506. BoundingRect.applyTransform(rect, elRect, transform);
  8507. }
  8508. else {
  8509. rect.copy(elRect);
  8510. }
  8511. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  8512. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  8513. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  8514. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  8515. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  8516. }
  8517. var tolerance = this.dirtyRectTolerance;
  8518. if (!rect.isZero()) {
  8519. rect.x = Math.floor(rect.x - tolerance);
  8520. rect.y = Math.floor(rect.y - tolerance);
  8521. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  8522. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  8523. }
  8524. }
  8525. return rect;
  8526. };
  8527. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  8528. if (paintRect) {
  8529. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  8530. this._prevPaintRect.copy(paintRect);
  8531. }
  8532. else {
  8533. this._prevPaintRect = null;
  8534. }
  8535. };
  8536. Displayable.prototype.getPrevPaintRect = function () {
  8537. return this._prevPaintRect;
  8538. };
  8539. Displayable.prototype.animateStyle = function (loop) {
  8540. return this.animate('style', loop);
  8541. };
  8542. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  8543. if (targetKey === 'style') {
  8544. this.dirtyStyle();
  8545. }
  8546. else {
  8547. this.markRedraw();
  8548. }
  8549. };
  8550. Displayable.prototype.attrKV = function (key, value) {
  8551. if (key !== 'style') {
  8552. _super.prototype.attrKV.call(this, key, value);
  8553. }
  8554. else {
  8555. if (!this.style) {
  8556. this.useStyle(value);
  8557. }
  8558. else {
  8559. this.setStyle(value);
  8560. }
  8561. }
  8562. };
  8563. Displayable.prototype.setStyle = function (keyOrObj, value) {
  8564. if (typeof keyOrObj === 'string') {
  8565. this.style[keyOrObj] = value;
  8566. }
  8567. else {
  8568. extend(this.style, keyOrObj);
  8569. }
  8570. this.dirtyStyle();
  8571. return this;
  8572. };
  8573. Displayable.prototype.dirtyStyle = function () {
  8574. this.markRedraw();
  8575. this.__dirty |= Displayable.STYLE_CHANGED_BIT;
  8576. if (this._rect) {
  8577. this._rect = null;
  8578. }
  8579. };
  8580. Displayable.prototype.dirty = function () {
  8581. this.dirtyStyle();
  8582. };
  8583. Displayable.prototype.styleChanged = function () {
  8584. return !!(this.__dirty & Displayable.STYLE_CHANGED_BIT);
  8585. };
  8586. Displayable.prototype.styleUpdated = function () {
  8587. this.__dirty &= ~Displayable.STYLE_CHANGED_BIT;
  8588. };
  8589. Displayable.prototype.createStyle = function (obj) {
  8590. return createObject(DEFAULT_COMMON_STYLE, obj);
  8591. };
  8592. Displayable.prototype.useStyle = function (obj) {
  8593. if (!obj[STYLE_MAGIC_KEY]) {
  8594. obj = this.createStyle(obj);
  8595. }
  8596. if (this.__inHover) {
  8597. this.__hoverStyle = obj;
  8598. }
  8599. else {
  8600. this.style = obj;
  8601. }
  8602. this.dirtyStyle();
  8603. };
  8604. Displayable.prototype.isStyleObject = function (obj) {
  8605. return obj[STYLE_MAGIC_KEY];
  8606. };
  8607. Displayable.prototype._innerSaveToNormal = function (toState) {
  8608. _super.prototype._innerSaveToNormal.call(this, toState);
  8609. var normalState = this._normalState;
  8610. if (toState.style && !normalState.style) {
  8611. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  8612. }
  8613. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  8614. };
  8615. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  8616. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  8617. var needsRestoreToNormal = !(state && keepCurrentStates);
  8618. var targetStyle;
  8619. if (state && state.style) {
  8620. if (transition) {
  8621. if (keepCurrentStates) {
  8622. targetStyle = state.style;
  8623. }
  8624. else {
  8625. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  8626. this._mergeStyle(targetStyle, state.style);
  8627. }
  8628. }
  8629. else {
  8630. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  8631. this._mergeStyle(targetStyle, state.style);
  8632. }
  8633. }
  8634. else if (needsRestoreToNormal) {
  8635. targetStyle = normalState.style;
  8636. }
  8637. if (targetStyle) {
  8638. if (transition) {
  8639. var sourceStyle = this.style;
  8640. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  8641. if (needsRestoreToNormal) {
  8642. var changedKeys = keys(sourceStyle);
  8643. for (var i = 0; i < changedKeys.length; i++) {
  8644. var key = changedKeys[i];
  8645. if (key in targetStyle) {
  8646. targetStyle[key] = targetStyle[key];
  8647. this.style[key] = sourceStyle[key];
  8648. }
  8649. }
  8650. }
  8651. var targetKeys = keys(targetStyle);
  8652. for (var i = 0; i < targetKeys.length; i++) {
  8653. var key = targetKeys[i];
  8654. this.style[key] = this.style[key];
  8655. }
  8656. this._transitionState(stateName, {
  8657. style: targetStyle
  8658. }, animationCfg, this.getAnimationStyleProps());
  8659. }
  8660. else {
  8661. this.useStyle(targetStyle);
  8662. }
  8663. }
  8664. for (var i = 0; i < PRIMARY_STATES_KEYS$1.length; i++) {
  8665. var key = PRIMARY_STATES_KEYS$1[i];
  8666. if (state && state[key] != null) {
  8667. this[key] = state[key];
  8668. }
  8669. else if (needsRestoreToNormal) {
  8670. if (normalState[key] != null) {
  8671. this[key] = normalState[key];
  8672. }
  8673. }
  8674. }
  8675. };
  8676. Displayable.prototype._mergeStates = function (states) {
  8677. var mergedState = _super.prototype._mergeStates.call(this, states);
  8678. var mergedStyle;
  8679. for (var i = 0; i < states.length; i++) {
  8680. var state = states[i];
  8681. if (state.style) {
  8682. mergedStyle = mergedStyle || {};
  8683. this._mergeStyle(mergedStyle, state.style);
  8684. }
  8685. }
  8686. if (mergedStyle) {
  8687. mergedState.style = mergedStyle;
  8688. }
  8689. return mergedState;
  8690. };
  8691. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  8692. extend(targetStyle, sourceStyle);
  8693. return targetStyle;
  8694. };
  8695. Displayable.prototype.getAnimationStyleProps = function () {
  8696. return DEFAULT_COMMON_ANIMATION_PROPS;
  8697. };
  8698. Displayable.STYLE_CHANGED_BIT = 2;
  8699. Displayable.initDefaultProps = (function () {
  8700. var dispProto = Displayable.prototype;
  8701. dispProto.type = 'displayable';
  8702. dispProto.invisible = false;
  8703. dispProto.z = 0;
  8704. dispProto.z2 = 0;
  8705. dispProto.zlevel = 0;
  8706. dispProto.culling = false;
  8707. dispProto.cursor = 'pointer';
  8708. dispProto.rectHover = false;
  8709. dispProto.incremental = false;
  8710. dispProto._rect = null;
  8711. dispProto.dirtyRectTolerance = 0;
  8712. dispProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT;
  8713. })();
  8714. return Displayable;
  8715. }(Element));
  8716. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8717. var viewRect = new BoundingRect(0, 0, 0, 0);
  8718. function isDisplayableCulled(el, width, height) {
  8719. tmpRect.copy(el.getBoundingRect());
  8720. if (el.transform) {
  8721. tmpRect.applyTransform(el.transform);
  8722. }
  8723. viewRect.width = width;
  8724. viewRect.height = height;
  8725. return !tmpRect.intersect(viewRect);
  8726. }
  8727. var mathPow = Math.pow;
  8728. var mathSqrt = Math.sqrt;
  8729. var EPSILON$1 = 1e-8;
  8730. var EPSILON_NUMERIC = 1e-4;
  8731. var THREE_SQRT = mathSqrt(3);
  8732. var ONE_THIRD = 1 / 3;
  8733. var _v0 = create();
  8734. var _v1 = create();
  8735. var _v2 = create();
  8736. function isAroundZero(val) {
  8737. return val > -EPSILON$1 && val < EPSILON$1;
  8738. }
  8739. function isNotAroundZero$1(val) {
  8740. return val > EPSILON$1 || val < -EPSILON$1;
  8741. }
  8742. function cubicAt(p0, p1, p2, p3, t) {
  8743. var onet = 1 - t;
  8744. return onet * onet * (onet * p0 + 3 * t * p1)
  8745. + t * t * (t * p3 + 3 * onet * p2);
  8746. }
  8747. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  8748. var onet = 1 - t;
  8749. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  8750. + (p3 - p2) * t * t);
  8751. }
  8752. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  8753. var a = p3 + 3 * (p1 - p2) - p0;
  8754. var b = 3 * (p2 - p1 * 2 + p0);
  8755. var c = 3 * (p1 - p0);
  8756. var d = p0 - val;
  8757. var A = b * b - 3 * a * c;
  8758. var B = b * c - 9 * a * d;
  8759. var C = c * c - 3 * b * d;
  8760. var n = 0;
  8761. if (isAroundZero(A) && isAroundZero(B)) {
  8762. if (isAroundZero(b)) {
  8763. roots[0] = 0;
  8764. }
  8765. else {
  8766. var t1 = -c / b;
  8767. if (t1 >= 0 && t1 <= 1) {
  8768. roots[n++] = t1;
  8769. }
  8770. }
  8771. }
  8772. else {
  8773. var disc = B * B - 4 * A * C;
  8774. if (isAroundZero(disc)) {
  8775. var K = B / A;
  8776. var t1 = -b / a + K;
  8777. var t2 = -K / 2;
  8778. if (t1 >= 0 && t1 <= 1) {
  8779. roots[n++] = t1;
  8780. }
  8781. if (t2 >= 0 && t2 <= 1) {
  8782. roots[n++] = t2;
  8783. }
  8784. }
  8785. else if (disc > 0) {
  8786. var discSqrt = mathSqrt(disc);
  8787. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  8788. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  8789. if (Y1 < 0) {
  8790. Y1 = -mathPow(-Y1, ONE_THIRD);
  8791. }
  8792. else {
  8793. Y1 = mathPow(Y1, ONE_THIRD);
  8794. }
  8795. if (Y2 < 0) {
  8796. Y2 = -mathPow(-Y2, ONE_THIRD);
  8797. }
  8798. else {
  8799. Y2 = mathPow(Y2, ONE_THIRD);
  8800. }
  8801. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  8802. if (t1 >= 0 && t1 <= 1) {
  8803. roots[n++] = t1;
  8804. }
  8805. }
  8806. else {
  8807. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  8808. var theta = Math.acos(T) / 3;
  8809. var ASqrt = mathSqrt(A);
  8810. var tmp = Math.cos(theta);
  8811. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  8812. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  8813. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  8814. if (t1 >= 0 && t1 <= 1) {
  8815. roots[n++] = t1;
  8816. }
  8817. if (t2 >= 0 && t2 <= 1) {
  8818. roots[n++] = t2;
  8819. }
  8820. if (t3 >= 0 && t3 <= 1) {
  8821. roots[n++] = t3;
  8822. }
  8823. }
  8824. }
  8825. return n;
  8826. }
  8827. function cubicExtrema(p0, p1, p2, p3, extrema) {
  8828. var b = 6 * p2 - 12 * p1 + 6 * p0;
  8829. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  8830. var c = 3 * p1 - 3 * p0;
  8831. var n = 0;
  8832. if (isAroundZero(a)) {
  8833. if (isNotAroundZero$1(b)) {
  8834. var t1 = -c / b;
  8835. if (t1 >= 0 && t1 <= 1) {
  8836. extrema[n++] = t1;
  8837. }
  8838. }
  8839. }
  8840. else {
  8841. var disc = b * b - 4 * a * c;
  8842. if (isAroundZero(disc)) {
  8843. extrema[0] = -b / (2 * a);
  8844. }
  8845. else if (disc > 0) {
  8846. var discSqrt = mathSqrt(disc);
  8847. var t1 = (-b + discSqrt) / (2 * a);
  8848. var t2 = (-b - discSqrt) / (2 * a);
  8849. if (t1 >= 0 && t1 <= 1) {
  8850. extrema[n++] = t1;
  8851. }
  8852. if (t2 >= 0 && t2 <= 1) {
  8853. extrema[n++] = t2;
  8854. }
  8855. }
  8856. }
  8857. return n;
  8858. }
  8859. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  8860. var p01 = (p1 - p0) * t + p0;
  8861. var p12 = (p2 - p1) * t + p1;
  8862. var p23 = (p3 - p2) * t + p2;
  8863. var p012 = (p12 - p01) * t + p01;
  8864. var p123 = (p23 - p12) * t + p12;
  8865. var p0123 = (p123 - p012) * t + p012;
  8866. out[0] = p0;
  8867. out[1] = p01;
  8868. out[2] = p012;
  8869. out[3] = p0123;
  8870. out[4] = p0123;
  8871. out[5] = p123;
  8872. out[6] = p23;
  8873. out[7] = p3;
  8874. }
  8875. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  8876. var t;
  8877. var interval = 0.005;
  8878. var d = Infinity;
  8879. var prev;
  8880. var next;
  8881. var d1;
  8882. var d2;
  8883. _v0[0] = x;
  8884. _v0[1] = y;
  8885. for (var _t = 0; _t < 1; _t += 0.05) {
  8886. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  8887. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  8888. d1 = distSquare(_v0, _v1);
  8889. if (d1 < d) {
  8890. t = _t;
  8891. d = d1;
  8892. }
  8893. }
  8894. d = Infinity;
  8895. for (var i = 0; i < 32; i++) {
  8896. if (interval < EPSILON_NUMERIC) {
  8897. break;
  8898. }
  8899. prev = t - interval;
  8900. next = t + interval;
  8901. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  8902. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  8903. d1 = distSquare(_v1, _v0);
  8904. if (prev >= 0 && d1 < d) {
  8905. t = prev;
  8906. d = d1;
  8907. }
  8908. else {
  8909. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  8910. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  8911. d2 = distSquare(_v2, _v0);
  8912. if (next <= 1 && d2 < d) {
  8913. t = next;
  8914. d = d2;
  8915. }
  8916. else {
  8917. interval *= 0.5;
  8918. }
  8919. }
  8920. }
  8921. if (out) {
  8922. out[0] = cubicAt(x0, x1, x2, x3, t);
  8923. out[1] = cubicAt(y0, y1, y2, y3, t);
  8924. }
  8925. return mathSqrt(d);
  8926. }
  8927. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  8928. var px = x0;
  8929. var py = y0;
  8930. var d = 0;
  8931. var step = 1 / iteration;
  8932. for (var i = 1; i <= iteration; i++) {
  8933. var t = i * step;
  8934. var x = cubicAt(x0, x1, x2, x3, t);
  8935. var y = cubicAt(y0, y1, y2, y3, t);
  8936. var dx = x - px;
  8937. var dy = y - py;
  8938. d += Math.sqrt(dx * dx + dy * dy);
  8939. px = x;
  8940. py = y;
  8941. }
  8942. return d;
  8943. }
  8944. function quadraticAt(p0, p1, p2, t) {
  8945. var onet = 1 - t;
  8946. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  8947. }
  8948. function quadraticDerivativeAt(p0, p1, p2, t) {
  8949. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  8950. }
  8951. function quadraticRootAt(p0, p1, p2, val, roots) {
  8952. var a = p0 - 2 * p1 + p2;
  8953. var b = 2 * (p1 - p0);
  8954. var c = p0 - val;
  8955. var n = 0;
  8956. if (isAroundZero(a)) {
  8957. if (isNotAroundZero$1(b)) {
  8958. var t1 = -c / b;
  8959. if (t1 >= 0 && t1 <= 1) {
  8960. roots[n++] = t1;
  8961. }
  8962. }
  8963. }
  8964. else {
  8965. var disc = b * b - 4 * a * c;
  8966. if (isAroundZero(disc)) {
  8967. var t1 = -b / (2 * a);
  8968. if (t1 >= 0 && t1 <= 1) {
  8969. roots[n++] = t1;
  8970. }
  8971. }
  8972. else if (disc > 0) {
  8973. var discSqrt = mathSqrt(disc);
  8974. var t1 = (-b + discSqrt) / (2 * a);
  8975. var t2 = (-b - discSqrt) / (2 * a);
  8976. if (t1 >= 0 && t1 <= 1) {
  8977. roots[n++] = t1;
  8978. }
  8979. if (t2 >= 0 && t2 <= 1) {
  8980. roots[n++] = t2;
  8981. }
  8982. }
  8983. }
  8984. return n;
  8985. }
  8986. function quadraticExtremum(p0, p1, p2) {
  8987. var divider = p0 + p2 - 2 * p1;
  8988. if (divider === 0) {
  8989. return 0.5;
  8990. }
  8991. else {
  8992. return (p0 - p1) / divider;
  8993. }
  8994. }
  8995. function quadraticSubdivide(p0, p1, p2, t, out) {
  8996. var p01 = (p1 - p0) * t + p0;
  8997. var p12 = (p2 - p1) * t + p1;
  8998. var p012 = (p12 - p01) * t + p01;
  8999. out[0] = p0;
  9000. out[1] = p01;
  9001. out[2] = p012;
  9002. out[3] = p012;
  9003. out[4] = p12;
  9004. out[5] = p2;
  9005. }
  9006. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  9007. var t;
  9008. var interval = 0.005;
  9009. var d = Infinity;
  9010. _v0[0] = x;
  9011. _v0[1] = y;
  9012. for (var _t = 0; _t < 1; _t += 0.05) {
  9013. _v1[0] = quadraticAt(x0, x1, x2, _t);
  9014. _v1[1] = quadraticAt(y0, y1, y2, _t);
  9015. var d1 = distSquare(_v0, _v1);
  9016. if (d1 < d) {
  9017. t = _t;
  9018. d = d1;
  9019. }
  9020. }
  9021. d = Infinity;
  9022. for (var i = 0; i < 32; i++) {
  9023. if (interval < EPSILON_NUMERIC) {
  9024. break;
  9025. }
  9026. var prev = t - interval;
  9027. var next = t + interval;
  9028. _v1[0] = quadraticAt(x0, x1, x2, prev);
  9029. _v1[1] = quadraticAt(y0, y1, y2, prev);
  9030. var d1 = distSquare(_v1, _v0);
  9031. if (prev >= 0 && d1 < d) {
  9032. t = prev;
  9033. d = d1;
  9034. }
  9035. else {
  9036. _v2[0] = quadraticAt(x0, x1, x2, next);
  9037. _v2[1] = quadraticAt(y0, y1, y2, next);
  9038. var d2 = distSquare(_v2, _v0);
  9039. if (next <= 1 && d2 < d) {
  9040. t = next;
  9041. d = d2;
  9042. }
  9043. else {
  9044. interval *= 0.5;
  9045. }
  9046. }
  9047. }
  9048. if (out) {
  9049. out[0] = quadraticAt(x0, x1, x2, t);
  9050. out[1] = quadraticAt(y0, y1, y2, t);
  9051. }
  9052. return mathSqrt(d);
  9053. }
  9054. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  9055. var px = x0;
  9056. var py = y0;
  9057. var d = 0;
  9058. var step = 1 / iteration;
  9059. for (var i = 1; i <= iteration; i++) {
  9060. var t = i * step;
  9061. var x = quadraticAt(x0, x1, x2, t);
  9062. var y = quadraticAt(y0, y1, y2, t);
  9063. var dx = x - px;
  9064. var dy = y - py;
  9065. d += Math.sqrt(dx * dx + dy * dy);
  9066. px = x;
  9067. py = y;
  9068. }
  9069. return d;
  9070. }
  9071. var mathMin$1 = Math.min;
  9072. var mathMax$1 = Math.max;
  9073. var mathSin = Math.sin;
  9074. var mathCos = Math.cos;
  9075. var PI2 = Math.PI * 2;
  9076. var start = create();
  9077. var end = create();
  9078. var extremity = create();
  9079. function fromPoints(points, min, max) {
  9080. if (points.length === 0) {
  9081. return;
  9082. }
  9083. var p = points[0];
  9084. var left = p[0];
  9085. var right = p[0];
  9086. var top = p[1];
  9087. var bottom = p[1];
  9088. for (var i = 1; i < points.length; i++) {
  9089. p = points[i];
  9090. left = mathMin$1(left, p[0]);
  9091. right = mathMax$1(right, p[0]);
  9092. top = mathMin$1(top, p[1]);
  9093. bottom = mathMax$1(bottom, p[1]);
  9094. }
  9095. min[0] = left;
  9096. min[1] = top;
  9097. max[0] = right;
  9098. max[1] = bottom;
  9099. }
  9100. function fromLine(x0, y0, x1, y1, min, max) {
  9101. min[0] = mathMin$1(x0, x1);
  9102. min[1] = mathMin$1(y0, y1);
  9103. max[0] = mathMax$1(x0, x1);
  9104. max[1] = mathMax$1(y0, y1);
  9105. }
  9106. var xDim = [];
  9107. var yDim = [];
  9108. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9109. var cubicExtrema$1 = cubicExtrema;
  9110. var cubicAt$1 = cubicAt;
  9111. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9112. min[0] = Infinity;
  9113. min[1] = Infinity;
  9114. max[0] = -Infinity;
  9115. max[1] = -Infinity;
  9116. for (var i = 0; i < n; i++) {
  9117. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9118. min[0] = mathMin$1(x, min[0]);
  9119. max[0] = mathMax$1(x, max[0]);
  9120. }
  9121. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9122. for (var i = 0; i < n; i++) {
  9123. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9124. min[1] = mathMin$1(y, min[1]);
  9125. max[1] = mathMax$1(y, max[1]);
  9126. }
  9127. min[0] = mathMin$1(x0, min[0]);
  9128. max[0] = mathMax$1(x0, max[0]);
  9129. min[0] = mathMin$1(x3, min[0]);
  9130. max[0] = mathMax$1(x3, max[0]);
  9131. min[1] = mathMin$1(y0, min[1]);
  9132. max[1] = mathMax$1(y0, max[1]);
  9133. min[1] = mathMin$1(y3, min[1]);
  9134. max[1] = mathMax$1(y3, max[1]);
  9135. }
  9136. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9137. var quadraticExtremum$1 = quadraticExtremum;
  9138. var quadraticAt$1 = quadraticAt;
  9139. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9140. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9141. var x = quadraticAt$1(x0, x1, x2, tx);
  9142. var y = quadraticAt$1(y0, y1, y2, ty);
  9143. min[0] = mathMin$1(x0, x2, x);
  9144. min[1] = mathMin$1(y0, y2, y);
  9145. max[0] = mathMax$1(x0, x2, x);
  9146. max[1] = mathMax$1(y0, y2, y);
  9147. }
  9148. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9149. var vec2Min = min;
  9150. var vec2Max = max;
  9151. var diff = Math.abs(startAngle - endAngle);
  9152. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9153. min$1[0] = x - rx;
  9154. min$1[1] = y - ry;
  9155. max$1[0] = x + rx;
  9156. max$1[1] = y + ry;
  9157. return;
  9158. }
  9159. start[0] = mathCos(startAngle) * rx + x;
  9160. start[1] = mathSin(startAngle) * ry + y;
  9161. end[0] = mathCos(endAngle) * rx + x;
  9162. end[1] = mathSin(endAngle) * ry + y;
  9163. vec2Min(min$1, start, end);
  9164. vec2Max(max$1, start, end);
  9165. startAngle = startAngle % (PI2);
  9166. if (startAngle < 0) {
  9167. startAngle = startAngle + PI2;
  9168. }
  9169. endAngle = endAngle % (PI2);
  9170. if (endAngle < 0) {
  9171. endAngle = endAngle + PI2;
  9172. }
  9173. if (startAngle > endAngle && !anticlockwise) {
  9174. endAngle += PI2;
  9175. }
  9176. else if (startAngle < endAngle && anticlockwise) {
  9177. startAngle += PI2;
  9178. }
  9179. if (anticlockwise) {
  9180. var tmp = endAngle;
  9181. endAngle = startAngle;
  9182. startAngle = tmp;
  9183. }
  9184. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9185. if (angle > startAngle) {
  9186. extremity[0] = mathCos(angle) * rx + x;
  9187. extremity[1] = mathSin(angle) * ry + y;
  9188. vec2Min(min$1, extremity, min$1);
  9189. vec2Max(max$1, extremity, max$1);
  9190. }
  9191. }
  9192. }
  9193. var CMD = {
  9194. M: 1,
  9195. L: 2,
  9196. C: 3,
  9197. Q: 4,
  9198. A: 5,
  9199. Z: 6,
  9200. R: 7
  9201. };
  9202. var tmpOutX = [];
  9203. var tmpOutY = [];
  9204. var min$1 = [];
  9205. var max$1 = [];
  9206. var min2 = [];
  9207. var max2 = [];
  9208. var mathMin$2 = Math.min;
  9209. var mathMax$2 = Math.max;
  9210. var mathCos$1 = Math.cos;
  9211. var mathSin$1 = Math.sin;
  9212. var mathSqrt$1 = Math.sqrt;
  9213. var mathAbs = Math.abs;
  9214. var PI = Math.PI;
  9215. var PI2$1 = PI * 2;
  9216. var hasTypedArray = typeof Float32Array !== 'undefined';
  9217. var tmpAngles = [];
  9218. function modPI2(radian) {
  9219. var n = Math.round(radian / PI * 1e8) / 1e8;
  9220. return (n % 2) * PI;
  9221. }
  9222. function normalizeArcAngles(angles, anticlockwise) {
  9223. var newStartAngle = modPI2(angles[0]);
  9224. if (newStartAngle < 0) {
  9225. newStartAngle += PI2$1;
  9226. }
  9227. var delta = newStartAngle - angles[0];
  9228. var newEndAngle = angles[1];
  9229. newEndAngle += delta;
  9230. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9231. newEndAngle = newStartAngle + PI2$1;
  9232. }
  9233. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9234. newEndAngle = newStartAngle - PI2$1;
  9235. }
  9236. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9237. newEndAngle = newStartAngle +
  9238. (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9239. }
  9240. else if (anticlockwise && newStartAngle < newEndAngle) {
  9241. newEndAngle = newStartAngle -
  9242. (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9243. }
  9244. angles[0] = newStartAngle;
  9245. angles[1] = newEndAngle;
  9246. }
  9247. var PathProxy = (function () {
  9248. function PathProxy(notSaveData) {
  9249. this.dpr = 1;
  9250. this._version = 0;
  9251. this._xi = 0;
  9252. this._yi = 0;
  9253. this._x0 = 0;
  9254. this._y0 = 0;
  9255. this._len = 0;
  9256. if (notSaveData) {
  9257. this._saveData = false;
  9258. }
  9259. if (this._saveData) {
  9260. this.data = [];
  9261. }
  9262. }
  9263. PathProxy.prototype.increaseVersion = function () {
  9264. this._version++;
  9265. };
  9266. PathProxy.prototype.getVersion = function () {
  9267. return this._version;
  9268. };
  9269. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9270. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9271. if (segmentIgnoreThreshold > 0) {
  9272. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9273. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9274. }
  9275. };
  9276. PathProxy.prototype.setDPR = function (dpr) {
  9277. this.dpr = dpr;
  9278. };
  9279. PathProxy.prototype.setContext = function (ctx) {
  9280. this._ctx = ctx;
  9281. };
  9282. PathProxy.prototype.getContext = function () {
  9283. return this._ctx;
  9284. };
  9285. PathProxy.prototype.beginPath = function () {
  9286. this._ctx && this._ctx.beginPath();
  9287. this.reset();
  9288. return this;
  9289. };
  9290. PathProxy.prototype.reset = function () {
  9291. if (this._saveData) {
  9292. this._len = 0;
  9293. }
  9294. if (this._lineDash) {
  9295. this._lineDash = null;
  9296. this._dashOffset = 0;
  9297. }
  9298. if (this._pathSegLen) {
  9299. this._pathSegLen = null;
  9300. this._pathLen = 0;
  9301. }
  9302. this._version++;
  9303. };
  9304. PathProxy.prototype.moveTo = function (x, y) {
  9305. this.addData(CMD.M, x, y);
  9306. this._ctx && this._ctx.moveTo(x, y);
  9307. this._x0 = x;
  9308. this._y0 = y;
  9309. this._xi = x;
  9310. this._yi = y;
  9311. return this;
  9312. };
  9313. PathProxy.prototype.lineTo = function (x, y) {
  9314. var exceedUnit = mathAbs(x - this._xi) > this._ux
  9315. || mathAbs(y - this._yi) > this._uy
  9316. || this._len < 5;
  9317. this.addData(CMD.L, x, y);
  9318. if (this._ctx && exceedUnit) {
  9319. this._needsDash ? this._dashedLineTo(x, y)
  9320. : this._ctx.lineTo(x, y);
  9321. }
  9322. if (exceedUnit) {
  9323. this._xi = x;
  9324. this._yi = y;
  9325. }
  9326. return this;
  9327. };
  9328. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9329. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9330. if (this._ctx) {
  9331. this._needsDash ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  9332. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9333. }
  9334. this._xi = x3;
  9335. this._yi = y3;
  9336. return this;
  9337. };
  9338. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9339. this.addData(CMD.Q, x1, y1, x2, y2);
  9340. if (this._ctx) {
  9341. this._needsDash ? this._dashedQuadraticTo(x1, y1, x2, y2)
  9342. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9343. }
  9344. this._xi = x2;
  9345. this._yi = y2;
  9346. return this;
  9347. };
  9348. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9349. tmpAngles[0] = startAngle;
  9350. tmpAngles[1] = endAngle;
  9351. normalizeArcAngles(tmpAngles, anticlockwise);
  9352. startAngle = tmpAngles[0];
  9353. endAngle = tmpAngles[1];
  9354. var delta = endAngle - startAngle;
  9355. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9356. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9357. this._xi = mathCos$1(endAngle) * r + cx;
  9358. this._yi = mathSin$1(endAngle) * r + cy;
  9359. return this;
  9360. };
  9361. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9362. if (this._ctx) {
  9363. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9364. }
  9365. return this;
  9366. };
  9367. PathProxy.prototype.rect = function (x, y, w, h) {
  9368. this._ctx && this._ctx.rect(x, y, w, h);
  9369. this.addData(CMD.R, x, y, w, h);
  9370. return this;
  9371. };
  9372. PathProxy.prototype.closePath = function () {
  9373. this.addData(CMD.Z);
  9374. var ctx = this._ctx;
  9375. var x0 = this._x0;
  9376. var y0 = this._y0;
  9377. if (ctx) {
  9378. this._needsDash && this._dashedLineTo(x0, y0);
  9379. ctx.closePath();
  9380. }
  9381. this._xi = x0;
  9382. this._yi = y0;
  9383. return this;
  9384. };
  9385. PathProxy.prototype.fill = function (ctx) {
  9386. ctx && ctx.fill();
  9387. this.toStatic();
  9388. };
  9389. PathProxy.prototype.stroke = function (ctx) {
  9390. ctx && ctx.stroke();
  9391. this.toStatic();
  9392. };
  9393. PathProxy.prototype.setLineDash = function (lineDash) {
  9394. if (lineDash instanceof Array) {
  9395. this._lineDash = lineDash;
  9396. this._dashIdx = 0;
  9397. var lineDashSum = 0;
  9398. for (var i = 0; i < lineDash.length; i++) {
  9399. lineDashSum += lineDash[i];
  9400. }
  9401. this._dashSum = lineDashSum;
  9402. this._needsDash = true;
  9403. }
  9404. else {
  9405. this._lineDash = null;
  9406. this._needsDash = false;
  9407. }
  9408. return this;
  9409. };
  9410. PathProxy.prototype.setLineDashOffset = function (offset) {
  9411. this._dashOffset = offset;
  9412. return this;
  9413. };
  9414. PathProxy.prototype.len = function () {
  9415. return this._len;
  9416. };
  9417. PathProxy.prototype.setData = function (data) {
  9418. var len = data.length;
  9419. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9420. this.data = new Float32Array(len);
  9421. }
  9422. for (var i = 0; i < len; i++) {
  9423. this.data[i] = data[i];
  9424. }
  9425. this._len = len;
  9426. };
  9427. PathProxy.prototype.appendPath = function (path) {
  9428. if (!(path instanceof Array)) {
  9429. path = [path];
  9430. }
  9431. var len = path.length;
  9432. var appendSize = 0;
  9433. var offset = this._len;
  9434. for (var i = 0; i < len; i++) {
  9435. appendSize += path[i].len();
  9436. }
  9437. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9438. this.data = new Float32Array(offset + appendSize);
  9439. }
  9440. for (var i = 0; i < len; i++) {
  9441. var appendPathData = path[i].data;
  9442. for (var k = 0; k < appendPathData.length; k++) {
  9443. this.data[offset++] = appendPathData[k];
  9444. }
  9445. }
  9446. this._len = offset;
  9447. };
  9448. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9449. if (!this._saveData) {
  9450. return;
  9451. }
  9452. var data = this.data;
  9453. if (this._len + arguments.length > data.length) {
  9454. this._expandData();
  9455. data = this.data;
  9456. }
  9457. for (var i = 0; i < arguments.length; i++) {
  9458. data[this._len++] = arguments[i];
  9459. }
  9460. };
  9461. PathProxy.prototype._expandData = function () {
  9462. if (!(this.data instanceof Array)) {
  9463. var newData = [];
  9464. for (var i = 0; i < this._len; i++) {
  9465. newData[i] = this.data[i];
  9466. }
  9467. this.data = newData;
  9468. }
  9469. };
  9470. PathProxy.prototype._dashedLineTo = function (x1, y1) {
  9471. var dashSum = this._dashSum;
  9472. var lineDash = this._lineDash;
  9473. var ctx = this._ctx;
  9474. var offset = this._dashOffset;
  9475. var x0 = this._xi;
  9476. var y0 = this._yi;
  9477. var dx = x1 - x0;
  9478. var dy = y1 - y0;
  9479. var dist = mathSqrt$1(dx * dx + dy * dy);
  9480. var x = x0;
  9481. var y = y0;
  9482. var nDash = lineDash.length;
  9483. var dash;
  9484. var idx;
  9485. dx /= dist;
  9486. dy /= dist;
  9487. if (offset < 0) {
  9488. offset = dashSum + offset;
  9489. }
  9490. offset %= dashSum;
  9491. x -= offset * dx;
  9492. y -= offset * dy;
  9493. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  9494. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  9495. idx = this._dashIdx;
  9496. dash = lineDash[idx];
  9497. x += dx * dash;
  9498. y += dy * dash;
  9499. this._dashIdx = (idx + 1) % nDash;
  9500. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  9501. continue;
  9502. }
  9503. ctx[idx % 2 ? 'moveTo' : 'lineTo'](dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1), dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1));
  9504. }
  9505. dx = x - x1;
  9506. dy = y - y1;
  9507. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9508. };
  9509. PathProxy.prototype._dashedBezierTo = function (x1, y1, x2, y2, x3, y3) {
  9510. var ctx = this._ctx;
  9511. var dashSum = this._dashSum;
  9512. var offset = this._dashOffset;
  9513. var lineDash = this._lineDash;
  9514. var x0 = this._xi;
  9515. var y0 = this._yi;
  9516. var bezierLen = 0;
  9517. var idx = this._dashIdx;
  9518. var nDash = lineDash.length;
  9519. var t;
  9520. var dx;
  9521. var dy;
  9522. var x;
  9523. var y;
  9524. var tmpLen = 0;
  9525. if (offset < 0) {
  9526. offset = dashSum + offset;
  9527. }
  9528. offset %= dashSum;
  9529. for (t = 0; t < 1; t += 0.1) {
  9530. dx = cubicAt(x0, x1, x2, x3, t + 0.1)
  9531. - cubicAt(x0, x1, x2, x3, t);
  9532. dy = cubicAt(y0, y1, y2, y3, t + 0.1)
  9533. - cubicAt(y0, y1, y2, y3, t);
  9534. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  9535. }
  9536. for (; idx < nDash; idx++) {
  9537. tmpLen += lineDash[idx];
  9538. if (tmpLen > offset) {
  9539. break;
  9540. }
  9541. }
  9542. t = (tmpLen - offset) / bezierLen;
  9543. while (t <= 1) {
  9544. x = cubicAt(x0, x1, x2, x3, t);
  9545. y = cubicAt(y0, y1, y2, y3, t);
  9546. idx % 2 ? ctx.moveTo(x, y)
  9547. : ctx.lineTo(x, y);
  9548. t += lineDash[idx] / bezierLen;
  9549. idx = (idx + 1) % nDash;
  9550. }
  9551. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  9552. dx = x3 - x;
  9553. dy = y3 - y;
  9554. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9555. };
  9556. PathProxy.prototype._dashedQuadraticTo = function (x1, y1, x2, y2) {
  9557. var x3 = x2;
  9558. var y3 = y2;
  9559. x2 = (x2 + 2 * x1) / 3;
  9560. y2 = (y2 + 2 * y1) / 3;
  9561. x1 = (this._xi + 2 * x1) / 3;
  9562. y1 = (this._yi + 2 * y1) / 3;
  9563. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  9564. };
  9565. PathProxy.prototype.toStatic = function () {
  9566. if (!this._saveData) {
  9567. return;
  9568. }
  9569. var data = this.data;
  9570. if (data instanceof Array) {
  9571. data.length = this._len;
  9572. if (hasTypedArray && this._len > 11) {
  9573. this.data = new Float32Array(data);
  9574. }
  9575. }
  9576. };
  9577. PathProxy.prototype.getBoundingRect = function () {
  9578. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9579. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9580. var data = this.data;
  9581. var xi = 0;
  9582. var yi = 0;
  9583. var x0 = 0;
  9584. var y0 = 0;
  9585. var i;
  9586. for (i = 0; i < this._len;) {
  9587. var cmd = data[i++];
  9588. var isFirst = i === 1;
  9589. if (isFirst) {
  9590. xi = data[i];
  9591. yi = data[i + 1];
  9592. x0 = xi;
  9593. y0 = yi;
  9594. }
  9595. switch (cmd) {
  9596. case CMD.M:
  9597. xi = x0 = data[i++];
  9598. yi = y0 = data[i++];
  9599. min2[0] = x0;
  9600. min2[1] = y0;
  9601. max2[0] = x0;
  9602. max2[1] = y0;
  9603. break;
  9604. case CMD.L:
  9605. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9606. xi = data[i++];
  9607. yi = data[i++];
  9608. break;
  9609. case CMD.C:
  9610. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9611. xi = data[i++];
  9612. yi = data[i++];
  9613. break;
  9614. case CMD.Q:
  9615. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9616. xi = data[i++];
  9617. yi = data[i++];
  9618. break;
  9619. case CMD.A:
  9620. var cx = data[i++];
  9621. var cy = data[i++];
  9622. var rx = data[i++];
  9623. var ry = data[i++];
  9624. var startAngle = data[i++];
  9625. var endAngle = data[i++] + startAngle;
  9626. i += 1;
  9627. var anticlockwise = !data[i++];
  9628. if (isFirst) {
  9629. x0 = mathCos$1(startAngle) * rx + cx;
  9630. y0 = mathSin$1(startAngle) * ry + cy;
  9631. }
  9632. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9633. xi = mathCos$1(endAngle) * rx + cx;
  9634. yi = mathSin$1(endAngle) * ry + cy;
  9635. break;
  9636. case CMD.R:
  9637. x0 = xi = data[i++];
  9638. y0 = yi = data[i++];
  9639. var width = data[i++];
  9640. var height = data[i++];
  9641. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9642. break;
  9643. case CMD.Z:
  9644. xi = x0;
  9645. yi = y0;
  9646. break;
  9647. }
  9648. min(min$1, min$1, min2);
  9649. max(max$1, max$1, max2);
  9650. }
  9651. if (i === 0) {
  9652. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9653. }
  9654. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9655. };
  9656. PathProxy.prototype._calculateLength = function () {
  9657. var data = this.data;
  9658. var len = this._len;
  9659. var ux = this._ux;
  9660. var uy = this._uy;
  9661. var xi = 0;
  9662. var yi = 0;
  9663. var x0 = 0;
  9664. var y0 = 0;
  9665. if (!this._pathSegLen) {
  9666. this._pathSegLen = [];
  9667. }
  9668. var pathSegLen = this._pathSegLen;
  9669. var pathTotalLen = 0;
  9670. var segCount = 0;
  9671. for (var i = 0; i < len;) {
  9672. var cmd = data[i++];
  9673. var isFirst = i === 1;
  9674. if (isFirst) {
  9675. xi = data[i];
  9676. yi = data[i + 1];
  9677. x0 = xi;
  9678. y0 = yi;
  9679. }
  9680. var l = -1;
  9681. switch (cmd) {
  9682. case CMD.M:
  9683. xi = x0 = data[i++];
  9684. yi = y0 = data[i++];
  9685. break;
  9686. case CMD.L: {
  9687. var x2 = data[i++];
  9688. var y2 = data[i++];
  9689. var dx = x2 - xi;
  9690. var dy = y2 - yi;
  9691. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  9692. l = Math.sqrt(dx * dx + dy * dy);
  9693. xi = x2;
  9694. yi = y2;
  9695. }
  9696. break;
  9697. }
  9698. case CMD.C: {
  9699. var x1 = data[i++];
  9700. var y1 = data[i++];
  9701. var x2 = data[i++];
  9702. var y2 = data[i++];
  9703. var x3 = data[i++];
  9704. var y3 = data[i++];
  9705. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  9706. xi = x3;
  9707. yi = y3;
  9708. break;
  9709. }
  9710. case CMD.Q: {
  9711. var x1 = data[i++];
  9712. var y1 = data[i++];
  9713. var x2 = data[i++];
  9714. var y2 = data[i++];
  9715. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  9716. xi = x2;
  9717. yi = y2;
  9718. break;
  9719. }
  9720. case CMD.A:
  9721. var cx = data[i++];
  9722. var cy = data[i++];
  9723. var rx = data[i++];
  9724. var ry = data[i++];
  9725. var startAngle = data[i++];
  9726. var delta = data[i++];
  9727. var endAngle = delta + startAngle;
  9728. i += 1;
  9729. var anticlockwise = !data[i++];
  9730. if (isFirst) {
  9731. x0 = mathCos$1(startAngle) * rx + cx;
  9732. y0 = mathSin$1(startAngle) * ry + cy;
  9733. }
  9734. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  9735. xi = mathCos$1(endAngle) * rx + cx;
  9736. yi = mathSin$1(endAngle) * ry + cy;
  9737. break;
  9738. case CMD.R: {
  9739. x0 = xi = data[i++];
  9740. y0 = yi = data[i++];
  9741. var width = data[i++];
  9742. var height = data[i++];
  9743. l = width * 2 + height * 2;
  9744. break;
  9745. }
  9746. case CMD.Z: {
  9747. var dx = x0 - xi;
  9748. var dy = y0 - yi;
  9749. l = Math.sqrt(dx * dx + dy * dy);
  9750. xi = x0;
  9751. yi = y0;
  9752. break;
  9753. }
  9754. }
  9755. if (l >= 0) {
  9756. pathSegLen[segCount++] = l;
  9757. pathTotalLen += l;
  9758. }
  9759. }
  9760. this._pathLen = pathTotalLen;
  9761. return pathTotalLen;
  9762. };
  9763. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  9764. var d = this.data;
  9765. var ux = this._ux;
  9766. var uy = this._uy;
  9767. var len = this._len;
  9768. var x0;
  9769. var y0;
  9770. var xi;
  9771. var yi;
  9772. var x;
  9773. var y;
  9774. var drawPart = percent < 1;
  9775. var pathSegLen;
  9776. var pathTotalLen;
  9777. var accumLength = 0;
  9778. var segCount = 0;
  9779. var displayedLength;
  9780. if (drawPart) {
  9781. if (!this._pathSegLen) {
  9782. this._calculateLength();
  9783. }
  9784. pathSegLen = this._pathSegLen;
  9785. pathTotalLen = this._pathLen;
  9786. displayedLength = percent * pathTotalLen;
  9787. if (!displayedLength) {
  9788. return;
  9789. }
  9790. }
  9791. lo: for (var i = 0; i < len;) {
  9792. var cmd = d[i++];
  9793. var isFirst = i === 1;
  9794. if (isFirst) {
  9795. xi = d[i];
  9796. yi = d[i + 1];
  9797. x0 = xi;
  9798. y0 = yi;
  9799. }
  9800. switch (cmd) {
  9801. case CMD.M:
  9802. x0 = xi = d[i++];
  9803. y0 = yi = d[i++];
  9804. ctx.moveTo(xi, yi);
  9805. break;
  9806. case CMD.L: {
  9807. x = d[i++];
  9808. y = d[i++];
  9809. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len - 1) {
  9810. if (drawPart) {
  9811. var l = pathSegLen[segCount++];
  9812. if (accumLength + l > displayedLength) {
  9813. var t = (displayedLength - accumLength) / l;
  9814. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  9815. break lo;
  9816. }
  9817. accumLength += l;
  9818. }
  9819. ctx.lineTo(x, y);
  9820. xi = x;
  9821. yi = y;
  9822. }
  9823. break;
  9824. }
  9825. case CMD.C: {
  9826. var x1 = d[i++];
  9827. var y1 = d[i++];
  9828. var x2 = d[i++];
  9829. var y2 = d[i++];
  9830. var x3 = d[i++];
  9831. var y3 = d[i++];
  9832. if (drawPart) {
  9833. var l = pathSegLen[segCount++];
  9834. if (accumLength + l > displayedLength) {
  9835. var t = (displayedLength - accumLength) / l;
  9836. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  9837. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  9838. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  9839. break lo;
  9840. }
  9841. accumLength += l;
  9842. }
  9843. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9844. xi = x3;
  9845. yi = y3;
  9846. break;
  9847. }
  9848. case CMD.Q: {
  9849. var x1 = d[i++];
  9850. var y1 = d[i++];
  9851. var x2 = d[i++];
  9852. var y2 = d[i++];
  9853. if (drawPart) {
  9854. var l = pathSegLen[segCount++];
  9855. if (accumLength + l > displayedLength) {
  9856. var t = (displayedLength - accumLength) / l;
  9857. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  9858. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  9859. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  9860. break lo;
  9861. }
  9862. accumLength += l;
  9863. }
  9864. ctx.quadraticCurveTo(x1, y1, x2, y2);
  9865. xi = x2;
  9866. yi = y2;
  9867. break;
  9868. }
  9869. case CMD.A:
  9870. var cx = d[i++];
  9871. var cy = d[i++];
  9872. var rx = d[i++];
  9873. var ry = d[i++];
  9874. var startAngle = d[i++];
  9875. var delta = d[i++];
  9876. var psi = d[i++];
  9877. var anticlockwise = !d[i++];
  9878. var r = (rx > ry) ? rx : ry;
  9879. var isEllipse = mathAbs(rx - ry) > 1e-3;
  9880. var endAngle = startAngle + delta;
  9881. var breakBuild = false;
  9882. if (drawPart) {
  9883. var l = pathSegLen[segCount++];
  9884. if (accumLength + l > displayedLength) {
  9885. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  9886. breakBuild = true;
  9887. }
  9888. accumLength += l;
  9889. }
  9890. if (isEllipse && ctx.ellipse) {
  9891. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  9892. }
  9893. else {
  9894. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9895. }
  9896. if (breakBuild) {
  9897. break lo;
  9898. }
  9899. if (isFirst) {
  9900. x0 = mathCos$1(startAngle) * rx + cx;
  9901. y0 = mathSin$1(startAngle) * ry + cy;
  9902. }
  9903. xi = mathCos$1(endAngle) * rx + cx;
  9904. yi = mathSin$1(endAngle) * ry + cy;
  9905. break;
  9906. case CMD.R:
  9907. x0 = xi = d[i];
  9908. y0 = yi = d[i + 1];
  9909. x = d[i++];
  9910. y = d[i++];
  9911. var width = d[i++];
  9912. var height = d[i++];
  9913. if (drawPart) {
  9914. var l = pathSegLen[segCount++];
  9915. if (accumLength + l > displayedLength) {
  9916. var d_1 = displayedLength - accumLength;
  9917. ctx.moveTo(x, y);
  9918. ctx.lineTo(x + mathMin$2(d_1, width), y);
  9919. d_1 -= width;
  9920. if (d_1 > 0) {
  9921. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  9922. }
  9923. d_1 -= height;
  9924. if (d_1 > 0) {
  9925. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  9926. }
  9927. d_1 -= width;
  9928. if (d_1 > 0) {
  9929. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  9930. }
  9931. break lo;
  9932. }
  9933. accumLength += l;
  9934. }
  9935. ctx.rect(x, y, width, height);
  9936. break;
  9937. case CMD.Z:
  9938. if (drawPart) {
  9939. var l = pathSegLen[segCount++];
  9940. if (accumLength + l > displayedLength) {
  9941. var t = (displayedLength - accumLength) / l;
  9942. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  9943. break lo;
  9944. }
  9945. accumLength += l;
  9946. }
  9947. ctx.closePath();
  9948. xi = x0;
  9949. yi = y0;
  9950. }
  9951. }
  9952. };
  9953. PathProxy.CMD = CMD;
  9954. PathProxy.initDefaultProps = (function () {
  9955. var proto = PathProxy.prototype;
  9956. proto._saveData = true;
  9957. proto._needsDash = false;
  9958. proto._dashOffset = 0;
  9959. proto._dashIdx = 0;
  9960. proto._dashSum = 0;
  9961. proto._ux = 0;
  9962. proto._uy = 0;
  9963. })();
  9964. return PathProxy;
  9965. }());
  9966. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  9967. if (lineWidth === 0) {
  9968. return false;
  9969. }
  9970. var _l = lineWidth;
  9971. var _a = 0;
  9972. var _b = x0;
  9973. if ((y > y0 + _l && y > y1 + _l)
  9974. || (y < y0 - _l && y < y1 - _l)
  9975. || (x > x0 + _l && x > x1 + _l)
  9976. || (x < x0 - _l && x < x1 - _l)) {
  9977. return false;
  9978. }
  9979. if (x0 !== x1) {
  9980. _a = (y0 - y1) / (x0 - x1);
  9981. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  9982. }
  9983. else {
  9984. return Math.abs(x - x0) <= _l / 2;
  9985. }
  9986. var tmp = _a * x - y + _b;
  9987. var _s = tmp * tmp / (_a * _a + 1);
  9988. return _s <= _l / 2 * _l / 2;
  9989. }
  9990. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  9991. if (lineWidth === 0) {
  9992. return false;
  9993. }
  9994. var _l = lineWidth;
  9995. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  9996. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  9997. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  9998. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  9999. return false;
  10000. }
  10001. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10002. return d <= _l / 2;
  10003. }
  10004. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10005. if (lineWidth === 0) {
  10006. return false;
  10007. }
  10008. var _l = lineWidth;
  10009. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10010. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10011. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10012. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10013. return false;
  10014. }
  10015. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10016. return d <= _l / 2;
  10017. }
  10018. var PI2$2 = Math.PI * 2;
  10019. function normalizeRadian(angle) {
  10020. angle %= PI2$2;
  10021. if (angle < 0) {
  10022. angle += PI2$2;
  10023. }
  10024. return angle;
  10025. }
  10026. var PI2$3 = Math.PI * 2;
  10027. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10028. if (lineWidth === 0) {
  10029. return false;
  10030. }
  10031. var _l = lineWidth;
  10032. x -= cx;
  10033. y -= cy;
  10034. var d = Math.sqrt(x * x + y * y);
  10035. if ((d - _l > r) || (d + _l < r)) {
  10036. return false;
  10037. }
  10038. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10039. return true;
  10040. }
  10041. if (anticlockwise) {
  10042. var tmp = startAngle;
  10043. startAngle = normalizeRadian(endAngle);
  10044. endAngle = normalizeRadian(tmp);
  10045. }
  10046. else {
  10047. startAngle = normalizeRadian(startAngle);
  10048. endAngle = normalizeRadian(endAngle);
  10049. }
  10050. if (startAngle > endAngle) {
  10051. endAngle += PI2$3;
  10052. }
  10053. var angle = Math.atan2(y, x);
  10054. if (angle < 0) {
  10055. angle += PI2$3;
  10056. }
  10057. return (angle >= startAngle && angle <= endAngle)
  10058. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10059. }
  10060. function windingLine(x0, y0, x1, y1, x, y) {
  10061. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10062. return 0;
  10063. }
  10064. if (y1 === y0) {
  10065. return 0;
  10066. }
  10067. var t = (y - y0) / (y1 - y0);
  10068. var dir = y1 < y0 ? 1 : -1;
  10069. if (t === 1 || t === 0) {
  10070. dir = y1 < y0 ? 0.5 : -0.5;
  10071. }
  10072. var x_ = t * (x1 - x0) + x0;
  10073. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10074. }
  10075. var CMD$1 = PathProxy.CMD;
  10076. var PI2$4 = Math.PI * 2;
  10077. var EPSILON$2 = 1e-4;
  10078. function isAroundEqual(a, b) {
  10079. return Math.abs(a - b) < EPSILON$2;
  10080. }
  10081. var roots = [-1, -1, -1];
  10082. var extrema = [-1, -1];
  10083. function swapExtrema() {
  10084. var tmp = extrema[0];
  10085. extrema[0] = extrema[1];
  10086. extrema[1] = tmp;
  10087. }
  10088. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10089. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10090. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10091. return 0;
  10092. }
  10093. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10094. if (nRoots === 0) {
  10095. return 0;
  10096. }
  10097. else {
  10098. var w = 0;
  10099. var nExtrema = -1;
  10100. var y0_ = void 0;
  10101. var y1_ = void 0;
  10102. for (var i = 0; i < nRoots; i++) {
  10103. var t = roots[i];
  10104. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10105. var x_ = cubicAt(x0, x1, x2, x3, t);
  10106. if (x_ < x) {
  10107. continue;
  10108. }
  10109. if (nExtrema < 0) {
  10110. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10111. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10112. swapExtrema();
  10113. }
  10114. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10115. if (nExtrema > 1) {
  10116. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10117. }
  10118. }
  10119. if (nExtrema === 2) {
  10120. if (t < extrema[0]) {
  10121. w += y0_ < y0 ? unit : -unit;
  10122. }
  10123. else if (t < extrema[1]) {
  10124. w += y1_ < y0_ ? unit : -unit;
  10125. }
  10126. else {
  10127. w += y3 < y1_ ? unit : -unit;
  10128. }
  10129. }
  10130. else {
  10131. if (t < extrema[0]) {
  10132. w += y0_ < y0 ? unit : -unit;
  10133. }
  10134. else {
  10135. w += y3 < y0_ ? unit : -unit;
  10136. }
  10137. }
  10138. }
  10139. return w;
  10140. }
  10141. }
  10142. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10143. if ((y > y0 && y > y1 && y > y2)
  10144. || (y < y0 && y < y1 && y < y2)) {
  10145. return 0;
  10146. }
  10147. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10148. if (nRoots === 0) {
  10149. return 0;
  10150. }
  10151. else {
  10152. var t = quadraticExtremum(y0, y1, y2);
  10153. if (t >= 0 && t <= 1) {
  10154. var w = 0;
  10155. var y_ = quadraticAt(y0, y1, y2, t);
  10156. for (var i = 0; i < nRoots; i++) {
  10157. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10158. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10159. if (x_ < x) {
  10160. continue;
  10161. }
  10162. if (roots[i] < t) {
  10163. w += y_ < y0 ? unit : -unit;
  10164. }
  10165. else {
  10166. w += y2 < y_ ? unit : -unit;
  10167. }
  10168. }
  10169. return w;
  10170. }
  10171. else {
  10172. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10173. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10174. if (x_ < x) {
  10175. return 0;
  10176. }
  10177. return y2 < y0 ? unit : -unit;
  10178. }
  10179. }
  10180. }
  10181. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10182. y -= cy;
  10183. if (y > r || y < -r) {
  10184. return 0;
  10185. }
  10186. var tmp = Math.sqrt(r * r - y * y);
  10187. roots[0] = -tmp;
  10188. roots[1] = tmp;
  10189. var dTheta = Math.abs(startAngle - endAngle);
  10190. if (dTheta < 1e-4) {
  10191. return 0;
  10192. }
  10193. if (dTheta >= PI2$4 - 1e-4) {
  10194. startAngle = 0;
  10195. endAngle = PI2$4;
  10196. var dir = anticlockwise ? 1 : -1;
  10197. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10198. return dir;
  10199. }
  10200. else {
  10201. return 0;
  10202. }
  10203. }
  10204. if (startAngle > endAngle) {
  10205. var tmp_1 = startAngle;
  10206. startAngle = endAngle;
  10207. endAngle = tmp_1;
  10208. }
  10209. if (startAngle < 0) {
  10210. startAngle += PI2$4;
  10211. endAngle += PI2$4;
  10212. }
  10213. var w = 0;
  10214. for (var i = 0; i < 2; i++) {
  10215. var x_ = roots[i];
  10216. if (x_ + cx > x) {
  10217. var angle = Math.atan2(y, x_);
  10218. var dir = anticlockwise ? 1 : -1;
  10219. if (angle < 0) {
  10220. angle = PI2$4 + angle;
  10221. }
  10222. if ((angle >= startAngle && angle <= endAngle)
  10223. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10224. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10225. dir = -dir;
  10226. }
  10227. w += dir;
  10228. }
  10229. }
  10230. }
  10231. return w;
  10232. }
  10233. function containPath(path, lineWidth, isStroke, x, y) {
  10234. var data = path.data;
  10235. var len = path.len();
  10236. var w = 0;
  10237. var xi = 0;
  10238. var yi = 0;
  10239. var x0 = 0;
  10240. var y0 = 0;
  10241. var x1;
  10242. var y1;
  10243. for (var i = 0; i < len;) {
  10244. var cmd = data[i++];
  10245. var isFirst = i === 1;
  10246. if (cmd === CMD$1.M && i > 1) {
  10247. if (!isStroke) {
  10248. w += windingLine(xi, yi, x0, y0, x, y);
  10249. }
  10250. }
  10251. if (isFirst) {
  10252. xi = data[i];
  10253. yi = data[i + 1];
  10254. x0 = xi;
  10255. y0 = yi;
  10256. }
  10257. switch (cmd) {
  10258. case CMD$1.M:
  10259. x0 = data[i++];
  10260. y0 = data[i++];
  10261. xi = x0;
  10262. yi = y0;
  10263. break;
  10264. case CMD$1.L:
  10265. if (isStroke) {
  10266. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10267. return true;
  10268. }
  10269. }
  10270. else {
  10271. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10272. }
  10273. xi = data[i++];
  10274. yi = data[i++];
  10275. break;
  10276. case CMD$1.C:
  10277. if (isStroke) {
  10278. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10279. return true;
  10280. }
  10281. }
  10282. else {
  10283. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10284. }
  10285. xi = data[i++];
  10286. yi = data[i++];
  10287. break;
  10288. case CMD$1.Q:
  10289. if (isStroke) {
  10290. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10291. return true;
  10292. }
  10293. }
  10294. else {
  10295. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10296. }
  10297. xi = data[i++];
  10298. yi = data[i++];
  10299. break;
  10300. case CMD$1.A:
  10301. var cx = data[i++];
  10302. var cy = data[i++];
  10303. var rx = data[i++];
  10304. var ry = data[i++];
  10305. var theta = data[i++];
  10306. var dTheta = data[i++];
  10307. i += 1;
  10308. var anticlockwise = !!(1 - data[i++]);
  10309. x1 = Math.cos(theta) * rx + cx;
  10310. y1 = Math.sin(theta) * ry + cy;
  10311. if (!isFirst) {
  10312. w += windingLine(xi, yi, x1, y1, x, y);
  10313. }
  10314. else {
  10315. x0 = x1;
  10316. y0 = y1;
  10317. }
  10318. var _x = (x - cx) * ry / rx + cx;
  10319. if (isStroke) {
  10320. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10321. return true;
  10322. }
  10323. }
  10324. else {
  10325. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10326. }
  10327. xi = Math.cos(theta + dTheta) * rx + cx;
  10328. yi = Math.sin(theta + dTheta) * ry + cy;
  10329. break;
  10330. case CMD$1.R:
  10331. x0 = xi = data[i++];
  10332. y0 = yi = data[i++];
  10333. var width = data[i++];
  10334. var height = data[i++];
  10335. x1 = x0 + width;
  10336. y1 = y0 + height;
  10337. if (isStroke) {
  10338. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10339. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10340. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10341. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10342. return true;
  10343. }
  10344. }
  10345. else {
  10346. w += windingLine(x1, y0, x1, y1, x, y);
  10347. w += windingLine(x0, y1, x0, y0, x, y);
  10348. }
  10349. break;
  10350. case CMD$1.Z:
  10351. if (isStroke) {
  10352. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10353. return true;
  10354. }
  10355. }
  10356. else {
  10357. w += windingLine(xi, yi, x0, y0, x, y);
  10358. }
  10359. xi = x0;
  10360. yi = y0;
  10361. break;
  10362. }
  10363. }
  10364. if (!isStroke && !isAroundEqual(yi, y0)) {
  10365. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10366. }
  10367. return w !== 0;
  10368. }
  10369. function contain(pathProxy, x, y) {
  10370. return containPath(pathProxy, 0, false, x, y);
  10371. }
  10372. function containStroke$4(pathProxy, lineWidth, x, y) {
  10373. return containPath(pathProxy, lineWidth, true, x, y);
  10374. }
  10375. var DEFAULT_PATH_STYLE = defaults({
  10376. fill: '#000',
  10377. stroke: null,
  10378. strokePercent: 1,
  10379. fillOpacity: 1,
  10380. strokeOpacity: 1,
  10381. lineDashOffset: 0,
  10382. lineWidth: 1,
  10383. lineCap: 'butt',
  10384. miterLimit: 10,
  10385. strokeNoScale: false,
  10386. strokeFirst: false
  10387. }, DEFAULT_COMMON_STYLE);
  10388. var DEFAULT_PATH_ANIMATION_PROPS = {
  10389. style: defaults({
  10390. fill: true,
  10391. stroke: true,
  10392. strokePercent: true,
  10393. fillOpacity: true,
  10394. strokeOpacity: true,
  10395. lineDashOffset: true,
  10396. lineWidth: true,
  10397. miterLimit: true
  10398. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10399. };
  10400. var pathCopyParams = [
  10401. 'x', 'y', 'rotation', 'scaleX', 'scaleY', 'originX', 'originY', 'invisible',
  10402. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10403. ];
  10404. var Path = (function (_super) {
  10405. __extends(Path, _super);
  10406. function Path(opts) {
  10407. return _super.call(this, opts) || this;
  10408. }
  10409. Path.prototype.update = function () {
  10410. var _this = this;
  10411. _super.prototype.update.call(this);
  10412. var style = this.style;
  10413. if (style.decal) {
  10414. var decalEl = this._decalEl
  10415. = this._decalEl || new Path();
  10416. if (decalEl.buildPath === Path.prototype.buildPath) {
  10417. decalEl.buildPath = function (ctx) {
  10418. _this.buildPath(ctx, _this.shape);
  10419. };
  10420. }
  10421. decalEl.silent = true;
  10422. var decalElStyle = decalEl.style;
  10423. for (var key in style) {
  10424. if (decalElStyle[key] !== style[key]) {
  10425. decalElStyle[key] = style[key];
  10426. }
  10427. }
  10428. decalElStyle.fill = style.fill ? style.decal : null;
  10429. decalElStyle.decal = null;
  10430. decalElStyle.shadowColor = null;
  10431. style.strokeFirst && (decalElStyle.stroke = null);
  10432. for (var i = 0; i < pathCopyParams.length; ++i) {
  10433. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10434. }
  10435. decalEl.__dirty |= Element.REDARAW_BIT;
  10436. }
  10437. else if (this._decalEl) {
  10438. this._decalEl = null;
  10439. }
  10440. };
  10441. Path.prototype.getDecalElement = function () {
  10442. return this._decalEl;
  10443. };
  10444. Path.prototype._init = function (props) {
  10445. var keysArr = keys(props);
  10446. this.shape = this.getDefaultShape();
  10447. var defaultStyle = this.getDefaultStyle();
  10448. if (defaultStyle) {
  10449. this.useStyle(defaultStyle);
  10450. }
  10451. for (var i = 0; i < keysArr.length; i++) {
  10452. var key = keysArr[i];
  10453. var value = props[key];
  10454. if (key === 'style') {
  10455. if (!this.style) {
  10456. this.useStyle(value);
  10457. }
  10458. else {
  10459. extend(this.style, value);
  10460. }
  10461. }
  10462. else if (key === 'shape') {
  10463. extend(this.shape, value);
  10464. }
  10465. else {
  10466. _super.prototype.attrKV.call(this, key, value);
  10467. }
  10468. }
  10469. if (!this.style) {
  10470. this.useStyle({});
  10471. }
  10472. };
  10473. Path.prototype.getDefaultStyle = function () {
  10474. return null;
  10475. };
  10476. Path.prototype.getDefaultShape = function () {
  10477. return {};
  10478. };
  10479. Path.prototype.canBeInsideText = function () {
  10480. return this.hasFill();
  10481. };
  10482. Path.prototype.getInsideTextFill = function () {
  10483. var pathFill = this.style.fill;
  10484. if (pathFill !== 'none') {
  10485. if (isString(pathFill)) {
  10486. var fillLum = lum(pathFill, 0);
  10487. if (fillLum > 0.5) {
  10488. return DARK_LABEL_COLOR;
  10489. }
  10490. else if (fillLum > 0.2) {
  10491. return LIGHTER_LABEL_COLOR;
  10492. }
  10493. return LIGHT_LABEL_COLOR;
  10494. }
  10495. else if (pathFill) {
  10496. return LIGHT_LABEL_COLOR;
  10497. }
  10498. }
  10499. return DARK_LABEL_COLOR;
  10500. };
  10501. Path.prototype.getInsideTextStroke = function (textFill) {
  10502. var pathFill = this.style.fill;
  10503. if (isString(pathFill)) {
  10504. var zr = this.__zr;
  10505. var isDarkMode = !!(zr && zr.isDarkMode());
  10506. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10507. if (isDarkMode === isDarkLabel) {
  10508. return pathFill;
  10509. }
  10510. }
  10511. };
  10512. Path.prototype.buildPath = function (ctx, shapeCfg, inBundle) { };
  10513. Path.prototype.pathUpdated = function () {
  10514. this.__dirty &= ~Path.SHAPE_CHANGED_BIT;
  10515. };
  10516. Path.prototype.createPathProxy = function () {
  10517. this.path = new PathProxy(false);
  10518. };
  10519. Path.prototype.hasStroke = function () {
  10520. var style = this.style;
  10521. var stroke = style.stroke;
  10522. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10523. };
  10524. Path.prototype.hasFill = function () {
  10525. var style = this.style;
  10526. var fill = style.fill;
  10527. return fill != null && fill !== 'none';
  10528. };
  10529. Path.prototype.getBoundingRect = function () {
  10530. var rect = this._rect;
  10531. var style = this.style;
  10532. var needsUpdateRect = !rect;
  10533. if (needsUpdateRect) {
  10534. var firstInvoke = false;
  10535. if (!this.path) {
  10536. firstInvoke = true;
  10537. this.createPathProxy();
  10538. }
  10539. var path = this.path;
  10540. if (firstInvoke || (this.__dirty & Path.SHAPE_CHANGED_BIT)) {
  10541. path.beginPath();
  10542. this.buildPath(path, this.shape, false);
  10543. this.pathUpdated();
  10544. }
  10545. rect = path.getBoundingRect();
  10546. }
  10547. this._rect = rect;
  10548. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10549. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  10550. if (this.__dirty || needsUpdateRect) {
  10551. rectWithStroke.copy(rect);
  10552. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10553. var w = style.lineWidth;
  10554. if (!this.hasFill()) {
  10555. var strokeContainThreshold = this.strokeContainThreshold;
  10556. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10557. }
  10558. if (lineScale > 1e-10) {
  10559. rectWithStroke.width += w / lineScale;
  10560. rectWithStroke.height += w / lineScale;
  10561. rectWithStroke.x -= w / lineScale / 2;
  10562. rectWithStroke.y -= w / lineScale / 2;
  10563. }
  10564. }
  10565. return rectWithStroke;
  10566. }
  10567. return rect;
  10568. };
  10569. Path.prototype.contain = function (x, y) {
  10570. var localPos = this.transformCoordToLocal(x, y);
  10571. var rect = this.getBoundingRect();
  10572. var style = this.style;
  10573. x = localPos[0];
  10574. y = localPos[1];
  10575. if (rect.contain(x, y)) {
  10576. var pathProxy = this.path;
  10577. if (this.hasStroke()) {
  10578. var lineWidth = style.lineWidth;
  10579. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10580. if (lineScale > 1e-10) {
  10581. if (!this.hasFill()) {
  10582. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10583. }
  10584. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10585. return true;
  10586. }
  10587. }
  10588. }
  10589. if (this.hasFill()) {
  10590. return contain(pathProxy, x, y);
  10591. }
  10592. }
  10593. return false;
  10594. };
  10595. Path.prototype.dirtyShape = function () {
  10596. this.__dirty |= Path.SHAPE_CHANGED_BIT;
  10597. if (this._rect) {
  10598. this._rect = null;
  10599. }
  10600. if (this._decalEl) {
  10601. this._decalEl.dirtyShape();
  10602. }
  10603. this.markRedraw();
  10604. };
  10605. Path.prototype.dirty = function () {
  10606. this.dirtyStyle();
  10607. this.dirtyShape();
  10608. };
  10609. Path.prototype.animateShape = function (loop) {
  10610. return this.animate('shape', loop);
  10611. };
  10612. Path.prototype.updateDuringAnimation = function (targetKey) {
  10613. if (targetKey === 'style') {
  10614. this.dirtyStyle();
  10615. }
  10616. else if (targetKey === 'shape') {
  10617. this.dirtyShape();
  10618. }
  10619. else {
  10620. this.markRedraw();
  10621. }
  10622. };
  10623. Path.prototype.attrKV = function (key, value) {
  10624. if (key === 'shape') {
  10625. this.setShape(value);
  10626. }
  10627. else {
  10628. _super.prototype.attrKV.call(this, key, value);
  10629. }
  10630. };
  10631. Path.prototype.setShape = function (keyOrObj, value) {
  10632. var shape = this.shape;
  10633. if (!shape) {
  10634. shape = this.shape = {};
  10635. }
  10636. if (typeof keyOrObj === 'string') {
  10637. shape[keyOrObj] = value;
  10638. }
  10639. else {
  10640. extend(shape, keyOrObj);
  10641. }
  10642. this.dirtyShape();
  10643. return this;
  10644. };
  10645. Path.prototype.shapeChanged = function () {
  10646. return !!(this.__dirty & Path.SHAPE_CHANGED_BIT);
  10647. };
  10648. Path.prototype.createStyle = function (obj) {
  10649. return createObject(DEFAULT_PATH_STYLE, obj);
  10650. };
  10651. Path.prototype._innerSaveToNormal = function (toState) {
  10652. _super.prototype._innerSaveToNormal.call(this, toState);
  10653. var normalState = this._normalState;
  10654. if (toState.shape && !normalState.shape) {
  10655. normalState.shape = extend({}, this.shape);
  10656. }
  10657. };
  10658. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10659. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10660. var needsRestoreToNormal = !(state && keepCurrentStates);
  10661. var targetShape;
  10662. if (state && state.shape) {
  10663. if (transition) {
  10664. if (keepCurrentStates) {
  10665. targetShape = state.shape;
  10666. }
  10667. else {
  10668. targetShape = extend({}, normalState.shape);
  10669. extend(targetShape, state.shape);
  10670. }
  10671. }
  10672. else {
  10673. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  10674. extend(targetShape, state.shape);
  10675. }
  10676. }
  10677. else if (needsRestoreToNormal) {
  10678. targetShape = normalState.shape;
  10679. }
  10680. if (targetShape) {
  10681. if (transition) {
  10682. this.shape = extend({}, this.shape);
  10683. var targetShapePrimaryProps = {};
  10684. var shapeKeys = keys(targetShape);
  10685. for (var i = 0; i < shapeKeys.length; i++) {
  10686. var key = shapeKeys[i];
  10687. if (typeof targetShape[key] === 'object') {
  10688. this.shape[key] = targetShape[key];
  10689. }
  10690. else {
  10691. targetShapePrimaryProps[key] = targetShape[key];
  10692. }
  10693. }
  10694. this._transitionState(stateName, {
  10695. shape: targetShapePrimaryProps
  10696. }, animationCfg);
  10697. }
  10698. else {
  10699. this.shape = targetShape;
  10700. this.dirtyShape();
  10701. }
  10702. }
  10703. };
  10704. Path.prototype._mergeStates = function (states) {
  10705. var mergedState = _super.prototype._mergeStates.call(this, states);
  10706. var mergedShape;
  10707. for (var i = 0; i < states.length; i++) {
  10708. var state = states[i];
  10709. if (state.shape) {
  10710. mergedShape = mergedShape || {};
  10711. this._mergeStyle(mergedShape, state.shape);
  10712. }
  10713. }
  10714. if (mergedShape) {
  10715. mergedState.shape = mergedShape;
  10716. }
  10717. return mergedState;
  10718. };
  10719. Path.prototype.getAnimationStyleProps = function () {
  10720. return DEFAULT_PATH_ANIMATION_PROPS;
  10721. };
  10722. Path.prototype.isZeroArea = function () {
  10723. return false;
  10724. };
  10725. Path.extend = function (defaultProps) {
  10726. var Sub = (function (_super) {
  10727. __extends(Sub, _super);
  10728. function Sub(opts) {
  10729. var _this = _super.call(this, opts) || this;
  10730. defaultProps.init && defaultProps.init.call(_this, opts);
  10731. return _this;
  10732. }
  10733. Sub.prototype.getDefaultStyle = function () {
  10734. return clone(defaultProps.style);
  10735. };
  10736. Sub.prototype.getDefaultShape = function () {
  10737. return clone(defaultProps.shape);
  10738. };
  10739. return Sub;
  10740. }(Path));
  10741. for (var key in defaultProps) {
  10742. if (typeof defaultProps[key] === 'function') {
  10743. Sub.prototype[key] = defaultProps[key];
  10744. }
  10745. }
  10746. return Sub;
  10747. };
  10748. Path.SHAPE_CHANGED_BIT = 4;
  10749. Path.initDefaultProps = (function () {
  10750. var pathProto = Path.prototype;
  10751. pathProto.type = 'path';
  10752. pathProto.strokeContainThreshold = 5;
  10753. pathProto.segmentIgnoreThreshold = 0;
  10754. pathProto.subPixelOptimize = false;
  10755. pathProto.autoBatch = false;
  10756. pathProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT | Path.SHAPE_CHANGED_BIT;
  10757. })();
  10758. return Path;
  10759. }(Displayable));
  10760. var DEFAULT_TSPAN_STYLE = defaults({
  10761. strokeFirst: true,
  10762. font: DEFAULT_FONT,
  10763. x: 0,
  10764. y: 0,
  10765. textAlign: 'left',
  10766. textBaseline: 'top',
  10767. miterLimit: 2
  10768. }, DEFAULT_PATH_STYLE);
  10769. var TSpan = (function (_super) {
  10770. __extends(TSpan, _super);
  10771. function TSpan() {
  10772. return _super !== null && _super.apply(this, arguments) || this;
  10773. }
  10774. TSpan.prototype.hasStroke = function () {
  10775. var style = this.style;
  10776. var stroke = style.stroke;
  10777. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  10778. };
  10779. TSpan.prototype.hasFill = function () {
  10780. var style = this.style;
  10781. var fill = style.fill;
  10782. return fill != null && fill !== 'none';
  10783. };
  10784. TSpan.prototype.createStyle = function (obj) {
  10785. return createObject(DEFAULT_TSPAN_STYLE, obj);
  10786. };
  10787. TSpan.prototype.setBoundingRect = function (rect) {
  10788. this._rect = rect;
  10789. };
  10790. TSpan.prototype.getBoundingRect = function () {
  10791. var style = this.style;
  10792. if (!this._rect) {
  10793. var text = style.text;
  10794. text != null ? (text += '') : (text = '');
  10795. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  10796. rect.x += style.x || 0;
  10797. rect.y += style.y || 0;
  10798. if (this.hasStroke()) {
  10799. var w = style.lineWidth;
  10800. rect.x -= w / 2;
  10801. rect.y -= w / 2;
  10802. rect.width += w;
  10803. rect.height += w;
  10804. }
  10805. this._rect = rect;
  10806. }
  10807. return this._rect;
  10808. };
  10809. TSpan.initDefaultProps = (function () {
  10810. var tspanProto = TSpan.prototype;
  10811. tspanProto.dirtyRectTolerance = 10;
  10812. })();
  10813. return TSpan;
  10814. }(Displayable));
  10815. TSpan.prototype.type = 'tspan';
  10816. var DEFAULT_IMAGE_STYLE = defaults({
  10817. x: 0,
  10818. y: 0
  10819. }, DEFAULT_COMMON_STYLE);
  10820. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  10821. style: defaults({
  10822. x: true,
  10823. y: true,
  10824. width: true,
  10825. height: true,
  10826. sx: true,
  10827. sy: true,
  10828. sWidth: true,
  10829. sHeight: true
  10830. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10831. };
  10832. function isImageLike(source) {
  10833. return !!(source
  10834. && typeof source !== 'string'
  10835. && source.width && source.height);
  10836. }
  10837. var ZRImage = (function (_super) {
  10838. __extends(ZRImage, _super);
  10839. function ZRImage() {
  10840. return _super !== null && _super.apply(this, arguments) || this;
  10841. }
  10842. ZRImage.prototype.createStyle = function (obj) {
  10843. return createObject(DEFAULT_IMAGE_STYLE, obj);
  10844. };
  10845. ZRImage.prototype._getSize = function (dim) {
  10846. var style = this.style;
  10847. var size = style[dim];
  10848. if (size != null) {
  10849. return size;
  10850. }
  10851. var imageSource = isImageLike(style.image)
  10852. ? style.image : this.__image;
  10853. if (!imageSource) {
  10854. return 0;
  10855. }
  10856. var otherDim = dim === 'width' ? 'height' : 'width';
  10857. var otherDimSize = style[otherDim];
  10858. if (otherDimSize == null) {
  10859. return imageSource[dim];
  10860. }
  10861. else {
  10862. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  10863. }
  10864. };
  10865. ZRImage.prototype.getWidth = function () {
  10866. return this._getSize('width');
  10867. };
  10868. ZRImage.prototype.getHeight = function () {
  10869. return this._getSize('height');
  10870. };
  10871. ZRImage.prototype.getAnimationStyleProps = function () {
  10872. return DEFAULT_IMAGE_ANIMATION_PROPS;
  10873. };
  10874. ZRImage.prototype.getBoundingRect = function () {
  10875. var style = this.style;
  10876. if (!this._rect) {
  10877. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  10878. }
  10879. return this._rect;
  10880. };
  10881. return ZRImage;
  10882. }(Displayable));
  10883. ZRImage.prototype.type = 'image';
  10884. function buildPath(ctx, shape) {
  10885. var x = shape.x;
  10886. var y = shape.y;
  10887. var width = shape.width;
  10888. var height = shape.height;
  10889. var r = shape.r;
  10890. var r1;
  10891. var r2;
  10892. var r3;
  10893. var r4;
  10894. if (width < 0) {
  10895. x = x + width;
  10896. width = -width;
  10897. }
  10898. if (height < 0) {
  10899. y = y + height;
  10900. height = -height;
  10901. }
  10902. if (typeof r === 'number') {
  10903. r1 = r2 = r3 = r4 = r;
  10904. }
  10905. else if (r instanceof Array) {
  10906. if (r.length === 1) {
  10907. r1 = r2 = r3 = r4 = r[0];
  10908. }
  10909. else if (r.length === 2) {
  10910. r1 = r3 = r[0];
  10911. r2 = r4 = r[1];
  10912. }
  10913. else if (r.length === 3) {
  10914. r1 = r[0];
  10915. r2 = r4 = r[1];
  10916. r3 = r[2];
  10917. }
  10918. else {
  10919. r1 = r[0];
  10920. r2 = r[1];
  10921. r3 = r[2];
  10922. r4 = r[3];
  10923. }
  10924. }
  10925. else {
  10926. r1 = r2 = r3 = r4 = 0;
  10927. }
  10928. var total;
  10929. if (r1 + r2 > width) {
  10930. total = r1 + r2;
  10931. r1 *= width / total;
  10932. r2 *= width / total;
  10933. }
  10934. if (r3 + r4 > width) {
  10935. total = r3 + r4;
  10936. r3 *= width / total;
  10937. r4 *= width / total;
  10938. }
  10939. if (r2 + r3 > height) {
  10940. total = r2 + r3;
  10941. r2 *= height / total;
  10942. r3 *= height / total;
  10943. }
  10944. if (r1 + r4 > height) {
  10945. total = r1 + r4;
  10946. r1 *= height / total;
  10947. r4 *= height / total;
  10948. }
  10949. ctx.moveTo(x + r1, y);
  10950. ctx.lineTo(x + width - r2, y);
  10951. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  10952. ctx.lineTo(x + width, y + height - r3);
  10953. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  10954. ctx.lineTo(x + r4, y + height);
  10955. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  10956. ctx.lineTo(x, y + r1);
  10957. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  10958. }
  10959. var round$1 = Math.round;
  10960. function subPixelOptimizeLine(outputShape, inputShape, style) {
  10961. if (!inputShape) {
  10962. return;
  10963. }
  10964. var x1 = inputShape.x1;
  10965. var x2 = inputShape.x2;
  10966. var y1 = inputShape.y1;
  10967. var y2 = inputShape.y2;
  10968. outputShape.x1 = x1;
  10969. outputShape.x2 = x2;
  10970. outputShape.y1 = y1;
  10971. outputShape.y2 = y2;
  10972. var lineWidth = style && style.lineWidth;
  10973. if (!lineWidth) {
  10974. return outputShape;
  10975. }
  10976. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  10977. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  10978. }
  10979. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  10980. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  10981. }
  10982. return outputShape;
  10983. }
  10984. function subPixelOptimizeRect(outputShape, inputShape, style) {
  10985. if (!inputShape) {
  10986. return;
  10987. }
  10988. var originX = inputShape.x;
  10989. var originY = inputShape.y;
  10990. var originWidth = inputShape.width;
  10991. var originHeight = inputShape.height;
  10992. outputShape.x = originX;
  10993. outputShape.y = originY;
  10994. outputShape.width = originWidth;
  10995. outputShape.height = originHeight;
  10996. var lineWidth = style && style.lineWidth;
  10997. if (!lineWidth) {
  10998. return outputShape;
  10999. }
  11000. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11001. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11002. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11003. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11004. return outputShape;
  11005. }
  11006. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11007. if (!lineWidth) {
  11008. return position;
  11009. }
  11010. var doubledPosition = round$1(position * 2);
  11011. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11012. ? doubledPosition / 2
  11013. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11014. }
  11015. var RectShape = (function () {
  11016. function RectShape() {
  11017. this.x = 0;
  11018. this.y = 0;
  11019. this.width = 0;
  11020. this.height = 0;
  11021. }
  11022. return RectShape;
  11023. }());
  11024. var subPixelOptimizeOutputShape = {};
  11025. var Rect = (function (_super) {
  11026. __extends(Rect, _super);
  11027. function Rect(opts) {
  11028. return _super.call(this, opts) || this;
  11029. }
  11030. Rect.prototype.getDefaultShape = function () {
  11031. return new RectShape();
  11032. };
  11033. Rect.prototype.buildPath = function (ctx, shape) {
  11034. var x;
  11035. var y;
  11036. var width;
  11037. var height;
  11038. if (this.subPixelOptimize) {
  11039. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11040. x = optimizedShape.x;
  11041. y = optimizedShape.y;
  11042. width = optimizedShape.width;
  11043. height = optimizedShape.height;
  11044. optimizedShape.r = shape.r;
  11045. shape = optimizedShape;
  11046. }
  11047. else {
  11048. x = shape.x;
  11049. y = shape.y;
  11050. width = shape.width;
  11051. height = shape.height;
  11052. }
  11053. if (!shape.r) {
  11054. ctx.rect(x, y, width, height);
  11055. }
  11056. else {
  11057. buildPath(ctx, shape);
  11058. }
  11059. };
  11060. Rect.prototype.isZeroArea = function () {
  11061. return !this.shape.width || !this.shape.height;
  11062. };
  11063. return Rect;
  11064. }(Path));
  11065. Rect.prototype.type = 'rect';
  11066. var DEFAULT_RICH_TEXT_COLOR = {
  11067. fill: '#000'
  11068. };
  11069. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11070. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11071. style: defaults({
  11072. fill: true,
  11073. stroke: true,
  11074. fillOpacity: true,
  11075. strokeOpacity: true,
  11076. lineWidth: true,
  11077. fontSize: true,
  11078. lineHeight: true,
  11079. width: true,
  11080. height: true,
  11081. textShadowColor: true,
  11082. textShadowBlur: true,
  11083. textShadowOffsetX: true,
  11084. textShadowOffsetY: true,
  11085. backgroundColor: true,
  11086. padding: true,
  11087. borderColor: true,
  11088. borderWidth: true,
  11089. borderRadius: true
  11090. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11091. };
  11092. var ZRText = (function (_super) {
  11093. __extends(ZRText, _super);
  11094. function ZRText(opts) {
  11095. var _this = _super.call(this) || this;
  11096. _this.type = 'text';
  11097. _this._children = [];
  11098. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11099. _this.attr(opts);
  11100. return _this;
  11101. }
  11102. ZRText.prototype.childrenRef = function () {
  11103. return this._children;
  11104. };
  11105. ZRText.prototype.update = function () {
  11106. if (this.styleChanged()) {
  11107. this._updateSubTexts();
  11108. }
  11109. for (var i = 0; i < this._children.length; i++) {
  11110. var child = this._children[i];
  11111. child.zlevel = this.zlevel;
  11112. child.z = this.z;
  11113. child.z2 = this.z2;
  11114. child.culling = this.culling;
  11115. child.cursor = this.cursor;
  11116. child.invisible = this.invisible;
  11117. }
  11118. var attachedTransform = this.attachedTransform;
  11119. if (attachedTransform) {
  11120. attachedTransform.updateTransform();
  11121. var m = attachedTransform.transform;
  11122. if (m) {
  11123. this.transform = this.transform || [];
  11124. copy$1(this.transform, m);
  11125. }
  11126. else {
  11127. this.transform = null;
  11128. }
  11129. }
  11130. else {
  11131. _super.prototype.update.call(this);
  11132. }
  11133. };
  11134. ZRText.prototype.getComputedTransform = function () {
  11135. if (this.__hostTarget) {
  11136. this.__hostTarget.getComputedTransform();
  11137. this.__hostTarget.updateInnerText(true);
  11138. }
  11139. return this.attachedTransform ? this.attachedTransform.getComputedTransform()
  11140. : _super.prototype.getComputedTransform.call(this);
  11141. };
  11142. ZRText.prototype._updateSubTexts = function () {
  11143. this._childCursor = 0;
  11144. normalizeTextStyle(this.style);
  11145. this.style.rich
  11146. ? this._updateRichTexts()
  11147. : this._updatePlainTexts();
  11148. this._children.length = this._childCursor;
  11149. this.styleUpdated();
  11150. };
  11151. ZRText.prototype.addSelfToZr = function (zr) {
  11152. _super.prototype.addSelfToZr.call(this, zr);
  11153. for (var i = 0; i < this._children.length; i++) {
  11154. this._children[i].__zr = zr;
  11155. }
  11156. };
  11157. ZRText.prototype.removeSelfFromZr = function (zr) {
  11158. _super.prototype.removeSelfFromZr.call(this, zr);
  11159. for (var i = 0; i < this._children.length; i++) {
  11160. this._children[i].__zr = null;
  11161. }
  11162. };
  11163. ZRText.prototype.getBoundingRect = function () {
  11164. if (this.styleChanged()) {
  11165. this._updateSubTexts();
  11166. }
  11167. if (!this._rect) {
  11168. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11169. var children = this._children;
  11170. var tmpMat = [];
  11171. var rect = null;
  11172. for (var i = 0; i < children.length; i++) {
  11173. var child = children[i];
  11174. var childRect = child.getBoundingRect();
  11175. var transform = child.getLocalTransform(tmpMat);
  11176. if (transform) {
  11177. tmpRect.copy(childRect);
  11178. tmpRect.applyTransform(transform);
  11179. rect = rect || tmpRect.clone();
  11180. rect.union(tmpRect);
  11181. }
  11182. else {
  11183. rect = rect || childRect.clone();
  11184. rect.union(childRect);
  11185. }
  11186. }
  11187. this._rect = rect || tmpRect;
  11188. }
  11189. return this._rect;
  11190. };
  11191. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11192. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11193. };
  11194. ZRText.prototype.setTextContent = function (textContent) {
  11195. throw new Error('Can\'t attach text on another text');
  11196. };
  11197. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11198. if (!sourceStyle) {
  11199. return targetStyle;
  11200. }
  11201. var sourceRich = sourceStyle.rich;
  11202. var targetRich = targetStyle.rich || (sourceRich && {});
  11203. extend(targetStyle, sourceStyle);
  11204. if (sourceRich && targetRich) {
  11205. this._mergeRich(targetRich, sourceRich);
  11206. targetStyle.rich = targetRich;
  11207. }
  11208. else if (targetRich) {
  11209. targetStyle.rich = targetRich;
  11210. }
  11211. return targetStyle;
  11212. };
  11213. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11214. var richNames = keys(sourceRich);
  11215. for (var i = 0; i < richNames.length; i++) {
  11216. var richName = richNames[i];
  11217. targetRich[richName] = targetRich[richName] || {};
  11218. extend(targetRich[richName], sourceRich[richName]);
  11219. }
  11220. };
  11221. ZRText.prototype.getAnimationStyleProps = function () {
  11222. return DEFAULT_TEXT_ANIMATION_PROPS;
  11223. };
  11224. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11225. var child = this._children[this._childCursor];
  11226. if (!child || !(child instanceof Ctor)) {
  11227. child = new Ctor();
  11228. }
  11229. this._children[this._childCursor++] = child;
  11230. child.__zr = this.__zr;
  11231. child.parent = this;
  11232. return child;
  11233. };
  11234. ZRText.prototype._updatePlainTexts = function () {
  11235. var style = this.style;
  11236. var textFont = style.font || DEFAULT_FONT;
  11237. var textPadding = style.padding;
  11238. var text = getStyleText(style);
  11239. var contentBlock = parsePlainText(text, style);
  11240. var needDrawBg = needDrawBackground(style);
  11241. var bgColorDrawn = !!(style.backgroundColor);
  11242. var outerHeight = contentBlock.outerHeight;
  11243. var textLines = contentBlock.lines;
  11244. var lineHeight = contentBlock.lineHeight;
  11245. var defaultStyle = this._defaultStyle;
  11246. var baseX = style.x || 0;
  11247. var baseY = style.y || 0;
  11248. var textAlign = style.align || defaultStyle.align || 'left';
  11249. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11250. var textX = baseX;
  11251. var textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign);
  11252. if (needDrawBg || textPadding) {
  11253. var outerWidth_1 = contentBlock.width;
  11254. textPadding && (outerWidth_1 += textPadding[1] + textPadding[3]);
  11255. var boxX = adjustTextX(baseX, outerWidth_1, textAlign);
  11256. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11257. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth_1, outerHeight);
  11258. }
  11259. textY += lineHeight / 2;
  11260. if (textPadding) {
  11261. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11262. if (verticalAlign === 'top') {
  11263. textY += textPadding[0];
  11264. }
  11265. else if (verticalAlign === 'bottom') {
  11266. textY -= textPadding[2];
  11267. }
  11268. }
  11269. var defaultLineWidth = 0;
  11270. var useDefaultFill = false;
  11271. var textFill = getFill('fill' in style
  11272. ? style.fill
  11273. : (useDefaultFill = true, defaultStyle.fill));
  11274. var textStroke = getStroke('stroke' in style
  11275. ? style.stroke
  11276. : (!bgColorDrawn
  11277. && (!defaultStyle.autoStroke || useDefaultFill))
  11278. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11279. : null);
  11280. var hasShadow = style.textShadowBlur > 0;
  11281. var fixedBoundingRect = style.width != null
  11282. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11283. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11284. for (var i = 0; i < textLines.length; i++) {
  11285. var el = this._getOrCreateChild(TSpan);
  11286. var subElStyle = el.createStyle();
  11287. el.useStyle(subElStyle);
  11288. subElStyle.text = textLines[i];
  11289. subElStyle.x = textX;
  11290. subElStyle.y = textY;
  11291. if (textAlign) {
  11292. subElStyle.textAlign = textAlign;
  11293. }
  11294. subElStyle.textBaseline = 'middle';
  11295. subElStyle.opacity = style.opacity;
  11296. subElStyle.strokeFirst = true;
  11297. if (hasShadow) {
  11298. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11299. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11300. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11301. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11302. }
  11303. if (textStroke) {
  11304. subElStyle.stroke = textStroke;
  11305. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11306. subElStyle.lineDash = style.lineDash;
  11307. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11308. }
  11309. if (textFill) {
  11310. subElStyle.fill = textFill;
  11311. }
  11312. subElStyle.font = textFont;
  11313. textY += lineHeight;
  11314. if (fixedBoundingRect) {
  11315. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), style.width, calculatedLineHeight));
  11316. }
  11317. }
  11318. };
  11319. ZRText.prototype._updateRichTexts = function () {
  11320. var style = this.style;
  11321. var text = getStyleText(style);
  11322. var contentBlock = parseRichText(text, style);
  11323. var contentWidth = contentBlock.width;
  11324. var outerWidth = contentBlock.outerWidth;
  11325. var outerHeight = contentBlock.outerHeight;
  11326. var textPadding = style.padding;
  11327. var baseX = style.x || 0;
  11328. var baseY = style.y || 0;
  11329. var defaultStyle = this._defaultStyle;
  11330. var textAlign = style.align || defaultStyle.align;
  11331. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11332. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11333. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11334. var xLeft = boxX;
  11335. var lineTop = boxY;
  11336. if (textPadding) {
  11337. xLeft += textPadding[3];
  11338. lineTop += textPadding[0];
  11339. }
  11340. var xRight = xLeft + contentWidth;
  11341. if (needDrawBackground(style)) {
  11342. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11343. }
  11344. var bgColorDrawn = !!(style.backgroundColor);
  11345. for (var i = 0; i < contentBlock.lines.length; i++) {
  11346. var line = contentBlock.lines[i];
  11347. var tokens = line.tokens;
  11348. var tokenCount = tokens.length;
  11349. var lineHeight = line.lineHeight;
  11350. var remainedWidth = line.width;
  11351. var leftIndex = 0;
  11352. var lineXLeft = xLeft;
  11353. var lineXRight = xRight;
  11354. var rightIndex = tokenCount - 1;
  11355. var token = void 0;
  11356. while (leftIndex < tokenCount
  11357. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11358. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11359. remainedWidth -= token.width;
  11360. lineXLeft += token.width;
  11361. leftIndex++;
  11362. }
  11363. while (rightIndex >= 0
  11364. && (token = tokens[rightIndex], token.align === 'right')) {
  11365. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11366. remainedWidth -= token.width;
  11367. lineXRight -= token.width;
  11368. rightIndex--;
  11369. }
  11370. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11371. while (leftIndex <= rightIndex) {
  11372. token = tokens[leftIndex];
  11373. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11374. lineXLeft += token.width;
  11375. leftIndex++;
  11376. }
  11377. lineTop += lineHeight;
  11378. }
  11379. };
  11380. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11381. var tokenStyle = style.rich[token.styleName] || {};
  11382. tokenStyle.text = token.text;
  11383. var verticalAlign = token.verticalAlign;
  11384. var y = lineTop + lineHeight / 2;
  11385. if (verticalAlign === 'top') {
  11386. y = lineTop + token.height / 2;
  11387. }
  11388. else if (verticalAlign === 'bottom') {
  11389. y = lineTop + lineHeight - token.height / 2;
  11390. }
  11391. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11392. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11393. ? x - token.width
  11394. : textAlign === 'center'
  11395. ? x - token.width / 2
  11396. : x, y - token.height / 2, token.width, token.height);
  11397. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11398. var textPadding = token.textPadding;
  11399. if (textPadding) {
  11400. x = getTextXForPadding(x, textAlign, textPadding);
  11401. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11402. }
  11403. var el = this._getOrCreateChild(TSpan);
  11404. var subElStyle = el.createStyle();
  11405. el.useStyle(subElStyle);
  11406. var defaultStyle = this._defaultStyle;
  11407. var useDefaultFill = false;
  11408. var defaultLineWidth = 0;
  11409. var textFill = getStroke('fill' in tokenStyle ? tokenStyle.fill
  11410. : 'fill' in style ? style.fill
  11411. : (useDefaultFill = true, defaultStyle.fill));
  11412. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11413. : 'stroke' in style ? style.stroke
  11414. : (!bgColorDrawn
  11415. && !parentBgColorDrawn
  11416. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11417. : null);
  11418. var hasShadow = tokenStyle.textShadowBlur > 0
  11419. || style.textShadowBlur > 0;
  11420. subElStyle.text = token.text;
  11421. subElStyle.x = x;
  11422. subElStyle.y = y;
  11423. if (hasShadow) {
  11424. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11425. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11426. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11427. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11428. }
  11429. subElStyle.textAlign = textAlign;
  11430. subElStyle.textBaseline = 'middle';
  11431. subElStyle.font = token.font || DEFAULT_FONT;
  11432. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11433. if (textStroke) {
  11434. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11435. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11436. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11437. subElStyle.stroke = textStroke;
  11438. }
  11439. if (textFill) {
  11440. subElStyle.fill = textFill;
  11441. }
  11442. var textWidth = token.contentWidth;
  11443. var textHeight = token.contentHeight;
  11444. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11445. };
  11446. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11447. var textBackgroundColor = style.backgroundColor;
  11448. var textBorderWidth = style.borderWidth;
  11449. var textBorderColor = style.borderColor;
  11450. var isPlainBg = isString(textBackgroundColor);
  11451. var textBorderRadius = style.borderRadius;
  11452. var self = this;
  11453. var rectEl;
  11454. var imgEl;
  11455. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  11456. rectEl = this._getOrCreateChild(Rect);
  11457. rectEl.useStyle(rectEl.createStyle());
  11458. rectEl.style.fill = null;
  11459. var rectShape = rectEl.shape;
  11460. rectShape.x = x;
  11461. rectShape.y = y;
  11462. rectShape.width = width;
  11463. rectShape.height = height;
  11464. rectShape.r = textBorderRadius;
  11465. rectEl.dirtyShape();
  11466. }
  11467. if (isPlainBg) {
  11468. var rectStyle = rectEl.style;
  11469. rectStyle.fill = textBackgroundColor || null;
  11470. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11471. }
  11472. else if (textBackgroundColor && textBackgroundColor.image) {
  11473. imgEl = this._getOrCreateChild(ZRImage);
  11474. imgEl.onload = function () {
  11475. self.dirtyStyle();
  11476. };
  11477. var imgStyle = imgEl.style;
  11478. imgStyle.image = textBackgroundColor.image;
  11479. imgStyle.x = x;
  11480. imgStyle.y = y;
  11481. imgStyle.width = width;
  11482. imgStyle.height = height;
  11483. }
  11484. if (textBorderWidth && textBorderColor) {
  11485. var rectStyle = rectEl.style;
  11486. rectStyle.lineWidth = textBorderWidth;
  11487. rectStyle.stroke = textBorderColor;
  11488. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11489. rectStyle.lineDash = style.borderDash;
  11490. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11491. rectEl.strokeContainThreshold = 0;
  11492. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11493. rectStyle.strokeFirst = true;
  11494. rectStyle.lineWidth *= 2;
  11495. }
  11496. }
  11497. var commonStyle = (rectEl || imgEl).style;
  11498. commonStyle.shadowBlur = style.shadowBlur || 0;
  11499. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11500. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11501. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11502. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11503. };
  11504. ZRText.makeFont = function (style) {
  11505. var font = '';
  11506. if (style.fontSize || style.fontFamily || style.fontWeight) {
  11507. var fontSize = '';
  11508. if (typeof style.fontSize === 'string'
  11509. && (style.fontSize.indexOf('px') !== -1
  11510. || style.fontSize.indexOf('rem') !== -1
  11511. || style.fontSize.indexOf('em') !== -1)) {
  11512. fontSize = style.fontSize;
  11513. }
  11514. else if (!isNaN(+style.fontSize)) {
  11515. fontSize = style.fontSize + 'px';
  11516. }
  11517. else {
  11518. fontSize = '12px';
  11519. }
  11520. font = [
  11521. style.fontStyle,
  11522. style.fontWeight,
  11523. fontSize,
  11524. style.fontFamily || 'sans-serif'
  11525. ].join(' ');
  11526. }
  11527. return font && trim(font) || style.textFont || style.font;
  11528. };
  11529. return ZRText;
  11530. }(Displayable));
  11531. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11532. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11533. function normalizeTextStyle(style) {
  11534. normalizeStyle(style);
  11535. each(style.rich, normalizeStyle);
  11536. return style;
  11537. }
  11538. function normalizeStyle(style) {
  11539. if (style) {
  11540. style.font = ZRText.makeFont(style);
  11541. var textAlign = style.align;
  11542. textAlign === 'middle' && (textAlign = 'center');
  11543. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11544. var verticalAlign = style.verticalAlign;
  11545. verticalAlign === 'center' && (verticalAlign = 'middle');
  11546. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11547. var textPadding = style.padding;
  11548. if (textPadding) {
  11549. style.padding = normalizeCssArray(style.padding);
  11550. }
  11551. }
  11552. }
  11553. function getStroke(stroke, lineWidth) {
  11554. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11555. ? null
  11556. : (stroke.image || stroke.colorStops)
  11557. ? '#000'
  11558. : stroke;
  11559. }
  11560. function getFill(fill) {
  11561. return (fill == null || fill === 'none')
  11562. ? null
  11563. : (fill.image || fill.colorStops)
  11564. ? '#000'
  11565. : fill;
  11566. }
  11567. function getTextXForPadding(x, textAlign, textPadding) {
  11568. return textAlign === 'right'
  11569. ? (x - textPadding[1])
  11570. : textAlign === 'center'
  11571. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11572. : (x + textPadding[3]);
  11573. }
  11574. function getStyleText(style) {
  11575. var text = style.text;
  11576. text != null && (text += '');
  11577. return text;
  11578. }
  11579. function needDrawBackground(style) {
  11580. return !!(style.backgroundColor
  11581. || (style.borderWidth && style.borderColor));
  11582. }
  11583. var getECData = makeInner();
  11584. var _highlightNextDigit = 1;
  11585. var _highlightKeyMap = {};
  11586. var getSavedStates = makeInner();
  11587. var HOVER_STATE_NORMAL = 0;
  11588. var HOVER_STATE_BLUR = 1;
  11589. var HOVER_STATE_EMPHASIS = 2;
  11590. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11591. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11592. var Z2_EMPHASIS_LIFT = 10;
  11593. var Z2_SELECT_LIFT = 9;
  11594. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11595. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11596. var SELECT_ACTION_TYPE = 'select';
  11597. var UNSELECT_ACTION_TYPE = 'unselect';
  11598. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11599. function hasFillOrStroke(fillOrStroke) {
  11600. return fillOrStroke != null && fillOrStroke !== 'none';
  11601. } // Most lifted color are duplicated.
  11602. var liftedColorCache = new LRU(100);
  11603. function liftColor(color$1) {
  11604. if (typeof color$1 !== 'string') {
  11605. return color$1;
  11606. }
  11607. var liftedColor = liftedColorCache.get(color$1);
  11608. if (!liftedColor) {
  11609. liftedColor = lift(color$1, -0.1);
  11610. liftedColorCache.put(color$1, liftedColor);
  11611. }
  11612. return liftedColor;
  11613. }
  11614. function doChangeHoverState(el, stateName, hoverStateEnum) {
  11615. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  11616. el.onHoverStateChange(stateName);
  11617. }
  11618. el.hoverState = hoverStateEnum;
  11619. }
  11620. function singleEnterEmphasis(el) {
  11621. // Only mark the flag.
  11622. // States will be applied in the echarts.ts in next frame.
  11623. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  11624. }
  11625. function singleLeaveEmphasis(el) {
  11626. // Only mark the flag.
  11627. // States will be applied in the echarts.ts in next frame.
  11628. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  11629. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11630. }
  11631. }
  11632. function singleEnterBlur(el) {
  11633. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  11634. }
  11635. function singleLeaveBlur(el) {
  11636. if (el.hoverState === HOVER_STATE_BLUR) {
  11637. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11638. }
  11639. }
  11640. function singleEnterSelect(el) {
  11641. el.selected = true;
  11642. }
  11643. function singleLeaveSelect(el) {
  11644. el.selected = false;
  11645. }
  11646. function updateElementState(el, updater, commonParam) {
  11647. updater(el, commonParam);
  11648. }
  11649. function traverseUpdateState(el, updater, commonParam) {
  11650. updateElementState(el, updater, commonParam);
  11651. el.isGroup && el.traverse(function (child) {
  11652. updateElementState(child, updater, commonParam);
  11653. });
  11654. }
  11655. function setStatesFlag(el, stateName) {
  11656. switch (stateName) {
  11657. case 'emphasis':
  11658. el.hoverState = HOVER_STATE_EMPHASIS;
  11659. break;
  11660. case 'normal':
  11661. el.hoverState = HOVER_STATE_NORMAL;
  11662. break;
  11663. case 'blur':
  11664. el.hoverState = HOVER_STATE_BLUR;
  11665. break;
  11666. case 'select':
  11667. el.selected = true;
  11668. }
  11669. }
  11670. function getFromStateStyle(el, props, toStateName, defaultValue) {
  11671. var style = el.style;
  11672. var fromState = {};
  11673. for (var i = 0; i < props.length; i++) {
  11674. var propName = props[i];
  11675. var val = style[propName];
  11676. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  11677. }
  11678. for (var i = 0; i < el.animators.length; i++) {
  11679. var animator = el.animators[i];
  11680. if (animator.__fromStateTransition // Dont consider the animation to emphasis state.
  11681. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  11682. animator.saveFinalToTarget(fromState, props);
  11683. }
  11684. }
  11685. return fromState;
  11686. }
  11687. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  11688. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  11689. var cloned = false;
  11690. if (el instanceof Path) {
  11691. var store = getSavedStates(el);
  11692. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  11693. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  11694. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  11695. state = state || {}; // Apply default color lift
  11696. var emphasisStyle = state.style || {};
  11697. if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  11698. cloned = true; // Not modify the original value.
  11699. state = extend({}, state);
  11700. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  11701. emphasisStyle.fill = liftColor(fromFill);
  11702. } // Not highlight stroke if fill has been highlighted.
  11703. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  11704. if (!cloned) {
  11705. state = extend({}, state);
  11706. emphasisStyle = extend({}, emphasisStyle);
  11707. }
  11708. emphasisStyle.stroke = liftColor(fromStroke);
  11709. }
  11710. state.style = emphasisStyle;
  11711. }
  11712. }
  11713. if (state) {
  11714. // TODO Share with textContent?
  11715. if (state.z2 == null) {
  11716. if (!cloned) {
  11717. state = extend({}, state);
  11718. }
  11719. var z2EmphasisLift = el.z2EmphasisLift;
  11720. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  11721. }
  11722. }
  11723. return state;
  11724. }
  11725. function createSelectDefaultState(el, stateName, state) {
  11726. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  11727. if (state) {
  11728. // TODO Share with textContent?
  11729. if (state.z2 == null) {
  11730. state = extend({}, state);
  11731. var z2SelectLift = el.z2SelectLift;
  11732. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  11733. }
  11734. }
  11735. return state;
  11736. }
  11737. function createBlurDefaultState(el, stateName, state) {
  11738. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  11739. var currentOpacity = el.style.opacity;
  11740. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  11741. opacity: 1
  11742. }) : null;
  11743. state = state || {};
  11744. var blurStyle = state.style || {};
  11745. if (blurStyle.opacity == null) {
  11746. // clone state
  11747. state = extend({}, state);
  11748. blurStyle = extend({
  11749. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  11750. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  11751. }, blurStyle);
  11752. state.style = blurStyle;
  11753. }
  11754. return state;
  11755. }
  11756. function elementStateProxy(stateName, targetStates) {
  11757. var state = this.states[stateName];
  11758. if (this.style) {
  11759. if (stateName === 'emphasis') {
  11760. return createEmphasisDefaultState(this, stateName, targetStates, state);
  11761. } else if (stateName === 'blur') {
  11762. return createBlurDefaultState(this, stateName, state);
  11763. } else if (stateName === 'select') {
  11764. return createSelectDefaultState(this, stateName, state);
  11765. }
  11766. }
  11767. return state;
  11768. }
  11769. /**FI
  11770. * Set hover style (namely "emphasis style") of element.
  11771. * @param el Should not be `zrender/graphic/Group`.
  11772. * @param focus 'self' | 'selfInSeries' | 'series'
  11773. */
  11774. function setDefaultStateProxy(el) {
  11775. el.stateProxy = elementStateProxy;
  11776. var textContent = el.getTextContent();
  11777. var textGuide = el.getTextGuideLine();
  11778. if (textContent) {
  11779. textContent.stateProxy = elementStateProxy;
  11780. }
  11781. if (textGuide) {
  11782. textGuide.stateProxy = elementStateProxy;
  11783. }
  11784. }
  11785. function enterEmphasisWhenMouseOver(el, e) {
  11786. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11787. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  11788. }
  11789. function leaveEmphasisWhenMouseOut(el, e) {
  11790. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11791. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  11792. }
  11793. function enterEmphasis(el, highlightDigit) {
  11794. el.__highByOuter |= 1 << (highlightDigit || 0);
  11795. traverseUpdateState(el, singleEnterEmphasis);
  11796. }
  11797. function leaveEmphasis(el, highlightDigit) {
  11798. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  11799. }
  11800. function enterBlur(el) {
  11801. traverseUpdateState(el, singleEnterBlur);
  11802. }
  11803. function leaveBlur(el) {
  11804. traverseUpdateState(el, singleLeaveBlur);
  11805. }
  11806. function enterSelect(el) {
  11807. traverseUpdateState(el, singleEnterSelect);
  11808. }
  11809. function leaveSelect(el) {
  11810. traverseUpdateState(el, singleLeaveSelect);
  11811. }
  11812. function shouldSilent(el, e) {
  11813. return el.__highDownSilentOnTouch && e.zrByTouch;
  11814. }
  11815. function allLeaveBlur(api) {
  11816. var model = api.getModel();
  11817. model.eachComponent(function (componentType, componentModel) {
  11818. var view = componentType === 'series' ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel); // Leave blur anyway
  11819. view.group.traverse(function (child) {
  11820. singleLeaveBlur(child);
  11821. });
  11822. });
  11823. }
  11824. function toggleSeriesBlurState(targetSeriesIndex, focus, blurScope, api, isBlur) {
  11825. var ecModel = api.getModel();
  11826. blurScope = blurScope || 'coordinateSystem';
  11827. function leaveBlurOfIndices(data, dataIndices) {
  11828. for (var i = 0; i < dataIndices.length; i++) {
  11829. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  11830. itemEl && leaveBlur(itemEl);
  11831. }
  11832. }
  11833. if (!isBlur) {
  11834. allLeaveBlur(api);
  11835. return;
  11836. }
  11837. if (targetSeriesIndex == null) {
  11838. return;
  11839. }
  11840. if (!focus || focus === 'none') {
  11841. return;
  11842. }
  11843. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  11844. var targetCoordSys = targetSeriesModel.coordinateSystem;
  11845. if (targetCoordSys && targetCoordSys.master) {
  11846. targetCoordSys = targetCoordSys.master;
  11847. }
  11848. var blurredSeries = [];
  11849. ecModel.eachSeries(function (seriesModel) {
  11850. var sameSeries = targetSeriesModel === seriesModel;
  11851. var coordSys = seriesModel.coordinateSystem;
  11852. if (coordSys && coordSys.master) {
  11853. coordSys = coordSys.master;
  11854. }
  11855. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  11856. if (!( // Not blur other series if blurScope series
  11857. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  11858. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  11859. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  11860. )) {
  11861. var view = api.getViewOfSeriesModel(seriesModel);
  11862. view.group.traverse(function (child) {
  11863. singleEnterBlur(child);
  11864. });
  11865. if (isArrayLike(focus)) {
  11866. leaveBlurOfIndices(seriesModel.getData(), focus);
  11867. } else if (isObject(focus)) {
  11868. var dataTypes = keys(focus);
  11869. for (var d = 0; d < dataTypes.length; d++) {
  11870. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  11871. }
  11872. }
  11873. blurredSeries.push(seriesModel);
  11874. }
  11875. });
  11876. ecModel.eachComponent(function (componentType, componentModel) {
  11877. if (componentType === 'series') {
  11878. return;
  11879. }
  11880. var view = api.getViewOfComponentModel(componentModel);
  11881. if (view && view.blurSeries) {
  11882. view.blurSeries(blurredSeries, ecModel);
  11883. }
  11884. });
  11885. }
  11886. function toggleSeriesBlurStateFromPayload(seriesModel, payload, api) {
  11887. if (!isHighDownPayload(payload)) {
  11888. return;
  11889. }
  11890. var isHighlight = payload.type === HIGHLIGHT_ACTION_TYPE;
  11891. var seriesIndex = seriesModel.seriesIndex;
  11892. var data = seriesModel.getData(payload.dataType);
  11893. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  11894. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  11895. var el = data.getItemGraphicEl(dataIndex);
  11896. if (!el) {
  11897. var count = data.count();
  11898. var current = 0; // If data on dataIndex is NaN.
  11899. while (!el && current < count) {
  11900. el = data.getItemGraphicEl(current++);
  11901. }
  11902. }
  11903. if (el) {
  11904. var ecData = getECData(el);
  11905. toggleSeriesBlurState(seriesIndex, ecData.focus, ecData.blurScope, api, isHighlight);
  11906. } else {
  11907. // If there is no element put on the data. Try getting it from raw option
  11908. // TODO Should put it on seriesModel?
  11909. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  11910. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  11911. if (focus_1 != null) {
  11912. toggleSeriesBlurState(seriesIndex, focus_1, blurScope, api, isHighlight);
  11913. }
  11914. }
  11915. }
  11916. function toggleSelectionFromPayload(seriesModel, payload, api) {
  11917. if (!isSelectChangePayload(payload)) {
  11918. return;
  11919. }
  11920. var dataType = payload.dataType;
  11921. var data = seriesModel.getData(dataType);
  11922. var dataIndex = queryDataIndex(data, payload);
  11923. if (!isArray(dataIndex)) {
  11924. dataIndex = [dataIndex];
  11925. }
  11926. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  11927. }
  11928. function updateSeriesElementSelection(seriesModel) {
  11929. var allData = seriesModel.getAllData();
  11930. each(allData, function (_a) {
  11931. var data = _a.data,
  11932. type = _a.type;
  11933. data.eachItemGraphicEl(function (el, idx) {
  11934. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  11935. });
  11936. });
  11937. }
  11938. function getAllSelectedIndices(ecModel) {
  11939. var ret = [];
  11940. ecModel.eachSeries(function (seriesModel) {
  11941. var allData = seriesModel.getAllData();
  11942. each(allData, function (_a) {
  11943. var data = _a.data,
  11944. type = _a.type;
  11945. var dataIndices = seriesModel.getSelectedDataIndices();
  11946. if (dataIndices.length > 0) {
  11947. var item = {
  11948. dataIndex: dataIndices,
  11949. seriesIndex: seriesModel.seriesIndex
  11950. };
  11951. if (type != null) {
  11952. item.dataType = type;
  11953. }
  11954. ret.push(item);
  11955. }
  11956. });
  11957. });
  11958. return ret;
  11959. }
  11960. /**
  11961. * Enable the function that mouseover will trigger the emphasis state.
  11962. *
  11963. * NOTE:
  11964. * This function should be used on the element with dataIndex, seriesIndex.
  11965. *
  11966. */
  11967. function enableHoverEmphasis(el, focus, blurScope) {
  11968. setAsHighDownDispatcher(el, true);
  11969. traverseUpdateState(el, setDefaultStateProxy);
  11970. enableHoverFocus(el, focus, blurScope);
  11971. }
  11972. function enableHoverFocus(el, focus, blurScope) {
  11973. var ecData = getECData(el);
  11974. if (focus != null) {
  11975. // TODO dataIndex may be set after this function. This check is not useful.
  11976. // if (ecData.dataIndex == null) {
  11977. // if (__DEV__) {
  11978. // console.warn('focus can only been set on element with dataIndex');
  11979. // }
  11980. // }
  11981. // else {
  11982. ecData.focus = focus;
  11983. ecData.blurScope = blurScope; // }
  11984. } else if (ecData.focus) {
  11985. ecData.focus = null;
  11986. }
  11987. }
  11988. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  11989. var defaultStyleGetterMap = {
  11990. itemStyle: 'getItemStyle',
  11991. lineStyle: 'getLineStyle',
  11992. areaStyle: 'getAreaStyle'
  11993. };
  11994. /**
  11995. * Set emphasis/blur/selected states of element.
  11996. */
  11997. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  11998. getter) {
  11999. styleType = styleType || 'itemStyle';
  12000. for (var i = 0; i < OTHER_STATES.length; i++) {
  12001. var stateName = OTHER_STATES[i];
  12002. var model = itemModel.getModel([stateName, styleType]);
  12003. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12004. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12005. }
  12006. }
  12007. /**
  12008. * @parame el
  12009. * @param el.highDownSilentOnTouch
  12010. * In touch device, mouseover event will be trigger on touchstart event
  12011. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12012. * conveniently use hoverStyle when tap on touch screen without additional
  12013. * code for compatibility.
  12014. * But if the chart/component has select feature, which usually also use
  12015. * hoverStyle, there might be conflict between 'select-highlight' and
  12016. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12017. * In this case, `highDownSilentOnTouch` should be used to disable
  12018. * hover-highlight on touch device.
  12019. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12020. */
  12021. function setAsHighDownDispatcher(el, asDispatcher) {
  12022. var disable = asDispatcher === false;
  12023. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12024. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12025. if (el.highDownSilentOnTouch) {
  12026. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12027. } // Simple optimize, since this method might be
  12028. // called for each elements of a group in some cases.
  12029. if (!disable || extendedEl.__highDownDispatcher) {
  12030. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12031. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12032. // Also keep previous record.
  12033. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12034. extendedEl.__highDownDispatcher = !disable;
  12035. }
  12036. }
  12037. function isHighDownDispatcher(el) {
  12038. return !!(el && el.__highDownDispatcher);
  12039. }
  12040. /**
  12041. * Support hightlight/downplay record on each elements.
  12042. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12043. * user triggerred hightlight/downplay should not conflict.
  12044. * Only all of the highlightDigit cleared, return to normal.
  12045. * @param {string} highlightKey
  12046. * @return {number} highlightDigit
  12047. */
  12048. function getHighlightDigit(highlightKey) {
  12049. var highlightDigit = _highlightKeyMap[highlightKey];
  12050. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12051. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12052. }
  12053. return highlightDigit;
  12054. }
  12055. function isSelectChangePayload(payload) {
  12056. var payloadType = payload.type;
  12057. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12058. }
  12059. function isHighDownPayload(payload) {
  12060. var payloadType = payload.type;
  12061. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12062. }
  12063. function savePathStates(el) {
  12064. var store = getSavedStates(el);
  12065. store.normalFill = el.style.fill;
  12066. store.normalStroke = el.style.stroke;
  12067. var selectState = el.states.select || {};
  12068. store.selectFill = selectState.style && selectState.style.fill || null;
  12069. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12070. }
  12071. var CMD$2 = PathProxy.CMD;
  12072. var points = [[], [], []];
  12073. var mathSqrt$2 = Math.sqrt;
  12074. var mathAtan2 = Math.atan2;
  12075. function transformPath(path, m) {
  12076. var data = path.data;
  12077. var len = path.len();
  12078. var cmd;
  12079. var nPoint;
  12080. var i;
  12081. var j;
  12082. var k;
  12083. var p;
  12084. var M = CMD$2.M;
  12085. var C = CMD$2.C;
  12086. var L = CMD$2.L;
  12087. var R = CMD$2.R;
  12088. var A = CMD$2.A;
  12089. var Q = CMD$2.Q;
  12090. for (i = 0, j = 0; i < len;) {
  12091. cmd = data[i++];
  12092. j = i;
  12093. nPoint = 0;
  12094. switch (cmd) {
  12095. case M:
  12096. nPoint = 1;
  12097. break;
  12098. case L:
  12099. nPoint = 1;
  12100. break;
  12101. case C:
  12102. nPoint = 3;
  12103. break;
  12104. case Q:
  12105. nPoint = 2;
  12106. break;
  12107. case A:
  12108. var x = m[4];
  12109. var y = m[5];
  12110. var sx = mathSqrt$2(m[0] * m[0] + m[1] * m[1]);
  12111. var sy = mathSqrt$2(m[2] * m[2] + m[3] * m[3]);
  12112. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12113. data[i] *= sx;
  12114. data[i++] += x;
  12115. data[i] *= sy;
  12116. data[i++] += y;
  12117. data[i++] *= sx;
  12118. data[i++] *= sy;
  12119. data[i++] += angle;
  12120. data[i++] += angle;
  12121. i += 2;
  12122. j = i;
  12123. break;
  12124. case R:
  12125. p[0] = data[i++];
  12126. p[1] = data[i++];
  12127. applyTransform(p, p, m);
  12128. data[j++] = p[0];
  12129. data[j++] = p[1];
  12130. p[0] += data[i++];
  12131. p[1] += data[i++];
  12132. applyTransform(p, p, m);
  12133. data[j++] = p[0];
  12134. data[j++] = p[1];
  12135. }
  12136. for (k = 0; k < nPoint; k++) {
  12137. var p_1 = points[k];
  12138. p_1[0] = data[i++];
  12139. p_1[1] = data[i++];
  12140. applyTransform(p_1, p_1, m);
  12141. data[j++] = p_1[0];
  12142. data[j++] = p_1[1];
  12143. }
  12144. }
  12145. path.increaseVersion();
  12146. }
  12147. var mathSqrt$3 = Math.sqrt;
  12148. var mathSin$2 = Math.sin;
  12149. var mathCos$2 = Math.cos;
  12150. var PI$1 = Math.PI;
  12151. function vMag(v) {
  12152. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12153. }
  12154. function vRatio(u, v) {
  12155. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12156. }
  12157. function vAngle(u, v) {
  12158. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12159. * Math.acos(vRatio(u, v));
  12160. }
  12161. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12162. var psi = psiDeg * (PI$1 / 180.0);
  12163. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12164. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12165. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12166. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12167. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12168. if (lambda > 1) {
  12169. rx *= mathSqrt$3(lambda);
  12170. ry *= mathSqrt$3(lambda);
  12171. }
  12172. var f = (fa === fs ? -1 : 1)
  12173. * mathSqrt$3((((rx * rx) * (ry * ry))
  12174. - ((rx * rx) * (yp * yp))
  12175. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12176. + (ry * ry) * (xp * xp))) || 0;
  12177. var cxp = f * rx * yp / ry;
  12178. var cyp = f * -ry * xp / rx;
  12179. var cx = (x1 + x2) / 2.0
  12180. + mathCos$2(psi) * cxp
  12181. - mathSin$2(psi) * cyp;
  12182. var cy = (y1 + y2) / 2.0
  12183. + mathSin$2(psi) * cxp
  12184. + mathCos$2(psi) * cyp;
  12185. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12186. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12187. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12188. var dTheta = vAngle(u, v);
  12189. if (vRatio(u, v) <= -1) {
  12190. dTheta = PI$1;
  12191. }
  12192. if (vRatio(u, v) >= 1) {
  12193. dTheta = 0;
  12194. }
  12195. if (dTheta < 0) {
  12196. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12197. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12198. }
  12199. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12200. }
  12201. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12202. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12203. function createPathProxyFromString(data) {
  12204. var path = new PathProxy();
  12205. if (!data) {
  12206. return path;
  12207. }
  12208. var cpx = 0;
  12209. var cpy = 0;
  12210. var subpathX = cpx;
  12211. var subpathY = cpy;
  12212. var prevCmd;
  12213. var CMD = PathProxy.CMD;
  12214. var cmdList = data.match(commandReg);
  12215. if (!cmdList) {
  12216. return path;
  12217. }
  12218. for (var l = 0; l < cmdList.length; l++) {
  12219. var cmdText = cmdList[l];
  12220. var cmdStr = cmdText.charAt(0);
  12221. var cmd = void 0;
  12222. var p = cmdText.match(numberReg) || [];
  12223. var pLen = p.length;
  12224. for (var i = 0; i < pLen; i++) {
  12225. p[i] = parseFloat(p[i]);
  12226. }
  12227. var off = 0;
  12228. while (off < pLen) {
  12229. var ctlPtx = void 0;
  12230. var ctlPty = void 0;
  12231. var rx = void 0;
  12232. var ry = void 0;
  12233. var psi = void 0;
  12234. var fa = void 0;
  12235. var fs = void 0;
  12236. var x1 = cpx;
  12237. var y1 = cpy;
  12238. var len = void 0;
  12239. var pathData = void 0;
  12240. switch (cmdStr) {
  12241. case 'l':
  12242. cpx += p[off++];
  12243. cpy += p[off++];
  12244. cmd = CMD.L;
  12245. path.addData(cmd, cpx, cpy);
  12246. break;
  12247. case 'L':
  12248. cpx = p[off++];
  12249. cpy = p[off++];
  12250. cmd = CMD.L;
  12251. path.addData(cmd, cpx, cpy);
  12252. break;
  12253. case 'm':
  12254. cpx += p[off++];
  12255. cpy += p[off++];
  12256. cmd = CMD.M;
  12257. path.addData(cmd, cpx, cpy);
  12258. subpathX = cpx;
  12259. subpathY = cpy;
  12260. cmdStr = 'l';
  12261. break;
  12262. case 'M':
  12263. cpx = p[off++];
  12264. cpy = p[off++];
  12265. cmd = CMD.M;
  12266. path.addData(cmd, cpx, cpy);
  12267. subpathX = cpx;
  12268. subpathY = cpy;
  12269. cmdStr = 'L';
  12270. break;
  12271. case 'h':
  12272. cpx += p[off++];
  12273. cmd = CMD.L;
  12274. path.addData(cmd, cpx, cpy);
  12275. break;
  12276. case 'H':
  12277. cpx = p[off++];
  12278. cmd = CMD.L;
  12279. path.addData(cmd, cpx, cpy);
  12280. break;
  12281. case 'v':
  12282. cpy += p[off++];
  12283. cmd = CMD.L;
  12284. path.addData(cmd, cpx, cpy);
  12285. break;
  12286. case 'V':
  12287. cpy = p[off++];
  12288. cmd = CMD.L;
  12289. path.addData(cmd, cpx, cpy);
  12290. break;
  12291. case 'C':
  12292. cmd = CMD.C;
  12293. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12294. cpx = p[off - 2];
  12295. cpy = p[off - 1];
  12296. break;
  12297. case 'c':
  12298. cmd = CMD.C;
  12299. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12300. cpx += p[off - 2];
  12301. cpy += p[off - 1];
  12302. break;
  12303. case 'S':
  12304. ctlPtx = cpx;
  12305. ctlPty = cpy;
  12306. len = path.len();
  12307. pathData = path.data;
  12308. if (prevCmd === CMD.C) {
  12309. ctlPtx += cpx - pathData[len - 4];
  12310. ctlPty += cpy - pathData[len - 3];
  12311. }
  12312. cmd = CMD.C;
  12313. x1 = p[off++];
  12314. y1 = p[off++];
  12315. cpx = p[off++];
  12316. cpy = p[off++];
  12317. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12318. break;
  12319. case 's':
  12320. ctlPtx = cpx;
  12321. ctlPty = cpy;
  12322. len = path.len();
  12323. pathData = path.data;
  12324. if (prevCmd === CMD.C) {
  12325. ctlPtx += cpx - pathData[len - 4];
  12326. ctlPty += cpy - pathData[len - 3];
  12327. }
  12328. cmd = CMD.C;
  12329. x1 = cpx + p[off++];
  12330. y1 = cpy + p[off++];
  12331. cpx += p[off++];
  12332. cpy += p[off++];
  12333. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12334. break;
  12335. case 'Q':
  12336. x1 = p[off++];
  12337. y1 = p[off++];
  12338. cpx = p[off++];
  12339. cpy = p[off++];
  12340. cmd = CMD.Q;
  12341. path.addData(cmd, x1, y1, cpx, cpy);
  12342. break;
  12343. case 'q':
  12344. x1 = p[off++] + cpx;
  12345. y1 = p[off++] + cpy;
  12346. cpx += p[off++];
  12347. cpy += p[off++];
  12348. cmd = CMD.Q;
  12349. path.addData(cmd, x1, y1, cpx, cpy);
  12350. break;
  12351. case 'T':
  12352. ctlPtx = cpx;
  12353. ctlPty = cpy;
  12354. len = path.len();
  12355. pathData = path.data;
  12356. if (prevCmd === CMD.Q) {
  12357. ctlPtx += cpx - pathData[len - 4];
  12358. ctlPty += cpy - pathData[len - 3];
  12359. }
  12360. cpx = p[off++];
  12361. cpy = p[off++];
  12362. cmd = CMD.Q;
  12363. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12364. break;
  12365. case 't':
  12366. ctlPtx = cpx;
  12367. ctlPty = cpy;
  12368. len = path.len();
  12369. pathData = path.data;
  12370. if (prevCmd === CMD.Q) {
  12371. ctlPtx += cpx - pathData[len - 4];
  12372. ctlPty += cpy - pathData[len - 3];
  12373. }
  12374. cpx += p[off++];
  12375. cpy += p[off++];
  12376. cmd = CMD.Q;
  12377. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12378. break;
  12379. case 'A':
  12380. rx = p[off++];
  12381. ry = p[off++];
  12382. psi = p[off++];
  12383. fa = p[off++];
  12384. fs = p[off++];
  12385. x1 = cpx, y1 = cpy;
  12386. cpx = p[off++];
  12387. cpy = p[off++];
  12388. cmd = CMD.A;
  12389. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12390. break;
  12391. case 'a':
  12392. rx = p[off++];
  12393. ry = p[off++];
  12394. psi = p[off++];
  12395. fa = p[off++];
  12396. fs = p[off++];
  12397. x1 = cpx, y1 = cpy;
  12398. cpx += p[off++];
  12399. cpy += p[off++];
  12400. cmd = CMD.A;
  12401. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12402. break;
  12403. }
  12404. }
  12405. if (cmdStr === 'z' || cmdStr === 'Z') {
  12406. cmd = CMD.Z;
  12407. path.addData(cmd);
  12408. cpx = subpathX;
  12409. cpy = subpathY;
  12410. }
  12411. prevCmd = cmd;
  12412. }
  12413. path.toStatic();
  12414. return path;
  12415. }
  12416. var SVGPath = (function (_super) {
  12417. __extends(SVGPath, _super);
  12418. function SVGPath() {
  12419. return _super !== null && _super.apply(this, arguments) || this;
  12420. }
  12421. SVGPath.prototype.applyTransform = function (m) { };
  12422. return SVGPath;
  12423. }(Path));
  12424. function isPathProxy(path) {
  12425. return path.setData != null;
  12426. }
  12427. function createPathOptions(str, opts) {
  12428. var pathProxy = createPathProxyFromString(str);
  12429. var innerOpts = extend({}, opts);
  12430. innerOpts.buildPath = function (path) {
  12431. if (isPathProxy(path)) {
  12432. path.setData(pathProxy.data);
  12433. var ctx = path.getContext();
  12434. if (ctx) {
  12435. path.rebuildPath(ctx, 1);
  12436. }
  12437. }
  12438. else {
  12439. var ctx = path;
  12440. pathProxy.rebuildPath(ctx, 1);
  12441. }
  12442. };
  12443. innerOpts.applyTransform = function (m) {
  12444. transformPath(pathProxy, m);
  12445. this.dirtyShape();
  12446. };
  12447. return innerOpts;
  12448. }
  12449. function createFromString(str, opts) {
  12450. return new SVGPath(createPathOptions(str, opts));
  12451. }
  12452. function extendFromString(str, defaultOpts) {
  12453. var innerOpts = createPathOptions(str, defaultOpts);
  12454. var Sub = (function (_super) {
  12455. __extends(Sub, _super);
  12456. function Sub(opts) {
  12457. var _this = _super.call(this, opts) || this;
  12458. _this.applyTransform = innerOpts.applyTransform;
  12459. _this.buildPath = innerOpts.buildPath;
  12460. return _this;
  12461. }
  12462. return Sub;
  12463. }(SVGPath));
  12464. return Sub;
  12465. }
  12466. function mergePath(pathEls, opts) {
  12467. var pathList = [];
  12468. var len = pathEls.length;
  12469. for (var i = 0; i < len; i++) {
  12470. var pathEl = pathEls[i];
  12471. if (!pathEl.path) {
  12472. pathEl.createPathProxy();
  12473. }
  12474. if (pathEl.shapeChanged()) {
  12475. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12476. }
  12477. pathList.push(pathEl.path);
  12478. }
  12479. var pathBundle = new Path(opts);
  12480. pathBundle.createPathProxy();
  12481. pathBundle.buildPath = function (path) {
  12482. if (isPathProxy(path)) {
  12483. path.appendPath(pathList);
  12484. var ctx = path.getContext();
  12485. if (ctx) {
  12486. path.rebuildPath(ctx, 1);
  12487. }
  12488. }
  12489. };
  12490. return pathBundle;
  12491. }
  12492. var CircleShape = (function () {
  12493. function CircleShape() {
  12494. this.cx = 0;
  12495. this.cy = 0;
  12496. this.r = 0;
  12497. }
  12498. return CircleShape;
  12499. }());
  12500. var Circle = (function (_super) {
  12501. __extends(Circle, _super);
  12502. function Circle(opts) {
  12503. return _super.call(this, opts) || this;
  12504. }
  12505. Circle.prototype.getDefaultShape = function () {
  12506. return new CircleShape();
  12507. };
  12508. Circle.prototype.buildPath = function (ctx, shape, inBundle) {
  12509. if (inBundle) {
  12510. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12511. }
  12512. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  12513. };
  12514. return Circle;
  12515. }(Path));
  12516. Circle.prototype.type = 'circle';
  12517. var EllipseShape = (function () {
  12518. function EllipseShape() {
  12519. this.cx = 0;
  12520. this.cy = 0;
  12521. this.rx = 0;
  12522. this.ry = 0;
  12523. }
  12524. return EllipseShape;
  12525. }());
  12526. var Ellipse = (function (_super) {
  12527. __extends(Ellipse, _super);
  12528. function Ellipse(opts) {
  12529. return _super.call(this, opts) || this;
  12530. }
  12531. Ellipse.prototype.getDefaultShape = function () {
  12532. return new EllipseShape();
  12533. };
  12534. Ellipse.prototype.buildPath = function (ctx, shape) {
  12535. var k = 0.5522848;
  12536. var x = shape.cx;
  12537. var y = shape.cy;
  12538. var a = shape.rx;
  12539. var b = shape.ry;
  12540. var ox = a * k;
  12541. var oy = b * k;
  12542. ctx.moveTo(x - a, y);
  12543. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  12544. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  12545. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  12546. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  12547. ctx.closePath();
  12548. };
  12549. return Ellipse;
  12550. }(Path));
  12551. Ellipse.prototype.type = 'ellipse';
  12552. var PI$2 = Math.PI;
  12553. var PI2$5 = PI$2 * 2;
  12554. var mathSin$3 = Math.sin;
  12555. var mathCos$3 = Math.cos;
  12556. var mathACos = Math.acos;
  12557. var mathATan2 = Math.atan2;
  12558. var mathAbs$1 = Math.abs;
  12559. var mathSqrt$4 = Math.sqrt;
  12560. var mathMax$3 = Math.max;
  12561. var mathMin$3 = Math.min;
  12562. var e = 1e-4;
  12563. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  12564. var x10 = x1 - x0;
  12565. var y10 = y1 - y0;
  12566. var x32 = x3 - x2;
  12567. var y32 = y3 - y2;
  12568. var t = y32 * x10 - x32 * y10;
  12569. if (t * t < e) {
  12570. return;
  12571. }
  12572. t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  12573. return [x0 + t * x10, y0 + t * y10];
  12574. }
  12575. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  12576. var x01 = x0 - x1;
  12577. var y01 = y0 - y1;
  12578. var lo = (clockwise ? cr : -cr) / mathSqrt$4(x01 * x01 + y01 * y01);
  12579. var ox = lo * y01;
  12580. var oy = -lo * x01;
  12581. var x11 = x0 + ox;
  12582. var y11 = y0 + oy;
  12583. var x10 = x1 + ox;
  12584. var y10 = y1 + oy;
  12585. var x00 = (x11 + x10) / 2;
  12586. var y00 = (y11 + y10) / 2;
  12587. var dx = x10 - x11;
  12588. var dy = y10 - y11;
  12589. var d2 = dx * dx + dy * dy;
  12590. var r = radius - cr;
  12591. var s = x11 * y10 - x10 * y11;
  12592. var d = (dy < 0 ? -1 : 1) * mathSqrt$4(mathMax$3(0, r * r * d2 - s * s));
  12593. var cx0 = (s * dy - dx * d) / d2;
  12594. var cy0 = (-s * dx - dy * d) / d2;
  12595. var cx1 = (s * dy + dx * d) / d2;
  12596. var cy1 = (-s * dx + dy * d) / d2;
  12597. var dx0 = cx0 - x00;
  12598. var dy0 = cy0 - y00;
  12599. var dx1 = cx1 - x00;
  12600. var dy1 = cy1 - y00;
  12601. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  12602. cx0 = cx1;
  12603. cy0 = cy1;
  12604. }
  12605. return {
  12606. cx: cx0,
  12607. cy: cy0,
  12608. x01: -ox,
  12609. y01: -oy,
  12610. x11: cx0 * (radius / r - 1),
  12611. y11: cy0 * (radius / r - 1)
  12612. };
  12613. }
  12614. function buildPath$1(ctx, shape) {
  12615. var radius = mathMax$3(shape.r, 0);
  12616. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  12617. var hasRadius = radius > 0;
  12618. var hasInnerRadius = innerRadius > 0;
  12619. if (!hasRadius && !hasInnerRadius) {
  12620. return;
  12621. }
  12622. if (!hasRadius) {
  12623. radius = innerRadius;
  12624. innerRadius = 0;
  12625. }
  12626. if (innerRadius > radius) {
  12627. var tmp = radius;
  12628. radius = innerRadius;
  12629. innerRadius = tmp;
  12630. }
  12631. var clockwise = !!shape.clockwise;
  12632. var startAngle = shape.startAngle;
  12633. var endAngle = shape.endAngle;
  12634. var arc;
  12635. if (startAngle === endAngle) {
  12636. arc = 0;
  12637. }
  12638. else {
  12639. var tmpAngles = [startAngle, endAngle];
  12640. normalizeArcAngles(tmpAngles, !clockwise);
  12641. arc = mathAbs$1(tmpAngles[0] - tmpAngles[1]);
  12642. }
  12643. var x = shape.cx;
  12644. var y = shape.cy;
  12645. var cornerRadius = shape.cornerRadius || 0;
  12646. var innerCornerRadius = shape.innerCornerRadius || 0;
  12647. if (!(radius > e)) {
  12648. ctx.moveTo(x, y);
  12649. }
  12650. else if (arc > PI2$5 - e) {
  12651. ctx.moveTo(x + radius * mathCos$3(startAngle), y + radius * mathSin$3(startAngle));
  12652. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  12653. if (innerRadius > e) {
  12654. ctx.moveTo(x + innerRadius * mathCos$3(endAngle), y + innerRadius * mathSin$3(endAngle));
  12655. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  12656. }
  12657. }
  12658. else {
  12659. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  12660. var cr = mathMin$3(halfRd, cornerRadius);
  12661. var icr = mathMin$3(halfRd, innerCornerRadius);
  12662. var cr0 = icr;
  12663. var cr1 = cr;
  12664. var xrs = radius * mathCos$3(startAngle);
  12665. var yrs = radius * mathSin$3(startAngle);
  12666. var xire = innerRadius * mathCos$3(endAngle);
  12667. var yire = innerRadius * mathSin$3(endAngle);
  12668. var xre = void 0;
  12669. var yre = void 0;
  12670. var xirs = void 0;
  12671. var yirs = void 0;
  12672. if (cr > e || icr > e) {
  12673. xre = radius * mathCos$3(endAngle);
  12674. yre = radius * mathSin$3(endAngle);
  12675. xirs = innerRadius * mathCos$3(startAngle);
  12676. yirs = innerRadius * mathSin$3(startAngle);
  12677. if (arc < PI$2) {
  12678. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  12679. if (it_1) {
  12680. var x0 = xrs - it_1[0];
  12681. var y0 = yrs - it_1[1];
  12682. var x1 = xre - it_1[0];
  12683. var y1 = yre - it_1[1];
  12684. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$4(x0 * x0 + y0 * y0) * mathSqrt$4(x1 * x1 + y1 * y1))) / 2);
  12685. var b = mathSqrt$4(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  12686. cr0 = mathMin$3(icr, (innerRadius - b) / (a - 1));
  12687. cr1 = mathMin$3(cr, (radius - b) / (a + 1));
  12688. }
  12689. }
  12690. }
  12691. if (!(arc > e)) {
  12692. ctx.moveTo(x + xrs, y + yrs);
  12693. }
  12694. else if (cr1 > e) {
  12695. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, cr1, clockwise);
  12696. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, cr1, clockwise);
  12697. ctx.moveTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  12698. if (cr1 < cr) {
  12699. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12700. }
  12701. else {
  12702. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  12703. ctx.arc(x, y, radius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), !clockwise);
  12704. ctx.arc(x + ct1.cx, y + ct1.cy, cr1, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12705. }
  12706. }
  12707. else {
  12708. ctx.moveTo(x + xrs, y + yrs);
  12709. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  12710. }
  12711. if (!(innerRadius > e) || !(arc > e)) {
  12712. ctx.lineTo(x + xire, y + yire);
  12713. }
  12714. else if (cr0 > e) {
  12715. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -cr0, clockwise);
  12716. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -cr0, clockwise);
  12717. ctx.lineTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  12718. if (cr0 < icr) {
  12719. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12720. }
  12721. else {
  12722. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  12723. ctx.arc(x, y, innerRadius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), clockwise);
  12724. ctx.arc(x + ct1.cx, y + ct1.cy, cr0, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12725. }
  12726. }
  12727. else {
  12728. ctx.lineTo(x + xire, y + yire);
  12729. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  12730. }
  12731. }
  12732. ctx.closePath();
  12733. }
  12734. var SectorShape = (function () {
  12735. function SectorShape() {
  12736. this.cx = 0;
  12737. this.cy = 0;
  12738. this.r0 = 0;
  12739. this.r = 0;
  12740. this.startAngle = 0;
  12741. this.endAngle = Math.PI * 2;
  12742. this.clockwise = true;
  12743. this.cornerRadius = 0;
  12744. this.innerCornerRadius = 0;
  12745. }
  12746. return SectorShape;
  12747. }());
  12748. var Sector = (function (_super) {
  12749. __extends(Sector, _super);
  12750. function Sector(opts) {
  12751. return _super.call(this, opts) || this;
  12752. }
  12753. Sector.prototype.getDefaultShape = function () {
  12754. return new SectorShape();
  12755. };
  12756. Sector.prototype.buildPath = function (ctx, shape) {
  12757. buildPath$1(ctx, shape);
  12758. };
  12759. Sector.prototype.isZeroArea = function () {
  12760. return this.shape.startAngle === this.shape.endAngle
  12761. || this.shape.r === this.shape.r0;
  12762. };
  12763. return Sector;
  12764. }(Path));
  12765. Sector.prototype.type = 'sector';
  12766. var RingShape = (function () {
  12767. function RingShape() {
  12768. this.cx = 0;
  12769. this.cy = 0;
  12770. this.r = 0;
  12771. this.r0 = 0;
  12772. }
  12773. return RingShape;
  12774. }());
  12775. var Ring = (function (_super) {
  12776. __extends(Ring, _super);
  12777. function Ring(opts) {
  12778. return _super.call(this, opts) || this;
  12779. }
  12780. Ring.prototype.getDefaultShape = function () {
  12781. return new RingShape();
  12782. };
  12783. Ring.prototype.buildPath = function (ctx, shape) {
  12784. var x = shape.cx;
  12785. var y = shape.cy;
  12786. var PI2 = Math.PI * 2;
  12787. ctx.moveTo(x + shape.r, y);
  12788. ctx.arc(x, y, shape.r, 0, PI2, false);
  12789. ctx.moveTo(x + shape.r0, y);
  12790. ctx.arc(x, y, shape.r0, 0, PI2, true);
  12791. };
  12792. return Ring;
  12793. }(Path));
  12794. Ring.prototype.type = 'ring';
  12795. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  12796. var v0 = (p2 - p0) * 0.5;
  12797. var v1 = (p3 - p1) * 0.5;
  12798. return (2 * (p1 - p2) + v0 + v1) * t3
  12799. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  12800. + v0 * t + p1;
  12801. }
  12802. function smoothSpline(points, isLoop) {
  12803. var len = points.length;
  12804. var ret = [];
  12805. var distance$1 = 0;
  12806. for (var i = 1; i < len; i++) {
  12807. distance$1 += distance(points[i - 1], points[i]);
  12808. }
  12809. var segs = distance$1 / 2;
  12810. segs = segs < len ? len : segs;
  12811. for (var i = 0; i < segs; i++) {
  12812. var pos = i / (segs - 1) * (isLoop ? len : len - 1);
  12813. var idx = Math.floor(pos);
  12814. var w = pos - idx;
  12815. var p0 = void 0;
  12816. var p1 = points[idx % len];
  12817. var p2 = void 0;
  12818. var p3 = void 0;
  12819. if (!isLoop) {
  12820. p0 = points[idx === 0 ? idx : idx - 1];
  12821. p2 = points[idx > len - 2 ? len - 1 : idx + 1];
  12822. p3 = points[idx > len - 3 ? len - 1 : idx + 2];
  12823. }
  12824. else {
  12825. p0 = points[(idx - 1 + len) % len];
  12826. p2 = points[(idx + 1) % len];
  12827. p3 = points[(idx + 2) % len];
  12828. }
  12829. var w2 = w * w;
  12830. var w3 = w * w2;
  12831. ret.push([
  12832. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  12833. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  12834. ]);
  12835. }
  12836. return ret;
  12837. }
  12838. function smoothBezier(points, smooth, isLoop, constraint) {
  12839. var cps = [];
  12840. var v = [];
  12841. var v1 = [];
  12842. var v2 = [];
  12843. var prevPoint;
  12844. var nextPoint;
  12845. var min$1;
  12846. var max$1;
  12847. if (constraint) {
  12848. min$1 = [Infinity, Infinity];
  12849. max$1 = [-Infinity, -Infinity];
  12850. for (var i = 0, len = points.length; i < len; i++) {
  12851. min(min$1, min$1, points[i]);
  12852. max(max$1, max$1, points[i]);
  12853. }
  12854. min(min$1, min$1, constraint[0]);
  12855. max(max$1, max$1, constraint[1]);
  12856. }
  12857. for (var i = 0, len = points.length; i < len; i++) {
  12858. var point = points[i];
  12859. if (isLoop) {
  12860. prevPoint = points[i ? i - 1 : len - 1];
  12861. nextPoint = points[(i + 1) % len];
  12862. }
  12863. else {
  12864. if (i === 0 || i === len - 1) {
  12865. cps.push(clone$1(points[i]));
  12866. continue;
  12867. }
  12868. else {
  12869. prevPoint = points[i - 1];
  12870. nextPoint = points[i + 1];
  12871. }
  12872. }
  12873. sub(v, nextPoint, prevPoint);
  12874. scale(v, v, smooth);
  12875. var d0 = distance(point, prevPoint);
  12876. var d1 = distance(point, nextPoint);
  12877. var sum = d0 + d1;
  12878. if (sum !== 0) {
  12879. d0 /= sum;
  12880. d1 /= sum;
  12881. }
  12882. scale(v1, v, -d0);
  12883. scale(v2, v, d1);
  12884. var cp0 = add([], point, v1);
  12885. var cp1 = add([], point, v2);
  12886. if (constraint) {
  12887. max(cp0, cp0, min$1);
  12888. min(cp0, cp0, max$1);
  12889. max(cp1, cp1, min$1);
  12890. min(cp1, cp1, max$1);
  12891. }
  12892. cps.push(cp0);
  12893. cps.push(cp1);
  12894. }
  12895. if (isLoop) {
  12896. cps.push(cps.shift());
  12897. }
  12898. return cps;
  12899. }
  12900. function buildPath$2(ctx, shape, closePath) {
  12901. var smooth = shape.smooth;
  12902. var points = shape.points;
  12903. if (points && points.length >= 2) {
  12904. if (smooth && smooth !== 'spline') {
  12905. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  12906. ctx.moveTo(points[0][0], points[0][1]);
  12907. var len = points.length;
  12908. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  12909. var cp1 = controlPoints[i * 2];
  12910. var cp2 = controlPoints[i * 2 + 1];
  12911. var p = points[(i + 1) % len];
  12912. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  12913. }
  12914. }
  12915. else {
  12916. if (smooth === 'spline') {
  12917. points = smoothSpline(points, closePath);
  12918. }
  12919. ctx.moveTo(points[0][0], points[0][1]);
  12920. for (var i = 1, l = points.length; i < l; i++) {
  12921. ctx.lineTo(points[i][0], points[i][1]);
  12922. }
  12923. }
  12924. closePath && ctx.closePath();
  12925. }
  12926. }
  12927. var PolygonShape = (function () {
  12928. function PolygonShape() {
  12929. this.points = null;
  12930. this.smooth = 0;
  12931. this.smoothConstraint = null;
  12932. }
  12933. return PolygonShape;
  12934. }());
  12935. var Polygon = (function (_super) {
  12936. __extends(Polygon, _super);
  12937. function Polygon(opts) {
  12938. return _super.call(this, opts) || this;
  12939. }
  12940. Polygon.prototype.getDefaultShape = function () {
  12941. return new PolygonShape();
  12942. };
  12943. Polygon.prototype.buildPath = function (ctx, shape) {
  12944. buildPath$2(ctx, shape, true);
  12945. };
  12946. return Polygon;
  12947. }(Path));
  12948. Polygon.prototype.type = 'polygon';
  12949. var PolylineShape = (function () {
  12950. function PolylineShape() {
  12951. this.points = null;
  12952. this.percent = 1;
  12953. this.smooth = 0;
  12954. this.smoothConstraint = null;
  12955. }
  12956. return PolylineShape;
  12957. }());
  12958. var Polyline = (function (_super) {
  12959. __extends(Polyline, _super);
  12960. function Polyline(opts) {
  12961. return _super.call(this, opts) || this;
  12962. }
  12963. Polyline.prototype.getDefaultStyle = function () {
  12964. return {
  12965. stroke: '#000',
  12966. fill: null
  12967. };
  12968. };
  12969. Polyline.prototype.getDefaultShape = function () {
  12970. return new PolylineShape();
  12971. };
  12972. Polyline.prototype.buildPath = function (ctx, shape) {
  12973. buildPath$2(ctx, shape, false);
  12974. };
  12975. return Polyline;
  12976. }(Path));
  12977. Polyline.prototype.type = 'polyline';
  12978. var subPixelOptimizeOutputShape$1 = {};
  12979. var LineShape = (function () {
  12980. function LineShape() {
  12981. this.x1 = 0;
  12982. this.y1 = 0;
  12983. this.x2 = 0;
  12984. this.y2 = 0;
  12985. this.percent = 1;
  12986. }
  12987. return LineShape;
  12988. }());
  12989. var Line = (function (_super) {
  12990. __extends(Line, _super);
  12991. function Line(opts) {
  12992. return _super.call(this, opts) || this;
  12993. }
  12994. Line.prototype.getDefaultStyle = function () {
  12995. return {
  12996. stroke: '#000',
  12997. fill: null
  12998. };
  12999. };
  13000. Line.prototype.getDefaultShape = function () {
  13001. return new LineShape();
  13002. };
  13003. Line.prototype.buildPath = function (ctx, shape) {
  13004. var x1;
  13005. var y1;
  13006. var x2;
  13007. var y2;
  13008. if (this.subPixelOptimize) {
  13009. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13010. x1 = optimizedShape.x1;
  13011. y1 = optimizedShape.y1;
  13012. x2 = optimizedShape.x2;
  13013. y2 = optimizedShape.y2;
  13014. }
  13015. else {
  13016. x1 = shape.x1;
  13017. y1 = shape.y1;
  13018. x2 = shape.x2;
  13019. y2 = shape.y2;
  13020. }
  13021. var percent = shape.percent;
  13022. if (percent === 0) {
  13023. return;
  13024. }
  13025. ctx.moveTo(x1, y1);
  13026. if (percent < 1) {
  13027. x2 = x1 * (1 - percent) + x2 * percent;
  13028. y2 = y1 * (1 - percent) + y2 * percent;
  13029. }
  13030. ctx.lineTo(x2, y2);
  13031. };
  13032. Line.prototype.pointAt = function (p) {
  13033. var shape = this.shape;
  13034. return [
  13035. shape.x1 * (1 - p) + shape.x2 * p,
  13036. shape.y1 * (1 - p) + shape.y2 * p
  13037. ];
  13038. };
  13039. return Line;
  13040. }(Path));
  13041. Line.prototype.type = 'line';
  13042. var out = [];
  13043. var BezierCurveShape = (function () {
  13044. function BezierCurveShape() {
  13045. this.x1 = 0;
  13046. this.y1 = 0;
  13047. this.x2 = 0;
  13048. this.y2 = 0;
  13049. this.cpx1 = 0;
  13050. this.cpy1 = 0;
  13051. this.percent = 1;
  13052. }
  13053. return BezierCurveShape;
  13054. }());
  13055. function someVectorAt(shape, t, isTangent) {
  13056. var cpx2 = shape.cpx2;
  13057. var cpy2 = shape.cpy2;
  13058. if (cpx2 === null || cpy2 === null) {
  13059. return [
  13060. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13061. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13062. ];
  13063. }
  13064. else {
  13065. return [
  13066. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13067. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13068. ];
  13069. }
  13070. }
  13071. var BezierCurve = (function (_super) {
  13072. __extends(BezierCurve, _super);
  13073. function BezierCurve(opts) {
  13074. return _super.call(this, opts) || this;
  13075. }
  13076. BezierCurve.prototype.getDefaultStyle = function () {
  13077. return {
  13078. stroke: '#000',
  13079. fill: null
  13080. };
  13081. };
  13082. BezierCurve.prototype.getDefaultShape = function () {
  13083. return new BezierCurveShape();
  13084. };
  13085. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13086. var x1 = shape.x1;
  13087. var y1 = shape.y1;
  13088. var x2 = shape.x2;
  13089. var y2 = shape.y2;
  13090. var cpx1 = shape.cpx1;
  13091. var cpy1 = shape.cpy1;
  13092. var cpx2 = shape.cpx2;
  13093. var cpy2 = shape.cpy2;
  13094. var percent = shape.percent;
  13095. if (percent === 0) {
  13096. return;
  13097. }
  13098. ctx.moveTo(x1, y1);
  13099. if (cpx2 == null || cpy2 == null) {
  13100. if (percent < 1) {
  13101. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13102. cpx1 = out[1];
  13103. x2 = out[2];
  13104. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13105. cpy1 = out[1];
  13106. y2 = out[2];
  13107. }
  13108. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13109. }
  13110. else {
  13111. if (percent < 1) {
  13112. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13113. cpx1 = out[1];
  13114. cpx2 = out[2];
  13115. x2 = out[3];
  13116. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13117. cpy1 = out[1];
  13118. cpy2 = out[2];
  13119. y2 = out[3];
  13120. }
  13121. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13122. }
  13123. };
  13124. BezierCurve.prototype.pointAt = function (t) {
  13125. return someVectorAt(this.shape, t, false);
  13126. };
  13127. BezierCurve.prototype.tangentAt = function (t) {
  13128. var p = someVectorAt(this.shape, t, true);
  13129. return normalize(p, p);
  13130. };
  13131. return BezierCurve;
  13132. }(Path));
  13133. BezierCurve.prototype.type = 'bezier-curve';
  13134. var ArcShape = (function () {
  13135. function ArcShape() {
  13136. this.cx = 0;
  13137. this.cy = 0;
  13138. this.r = 0;
  13139. this.startAngle = 0;
  13140. this.endAngle = Math.PI * 2;
  13141. this.clockwise = true;
  13142. }
  13143. return ArcShape;
  13144. }());
  13145. var Arc = (function (_super) {
  13146. __extends(Arc, _super);
  13147. function Arc(opts) {
  13148. return _super.call(this, opts) || this;
  13149. }
  13150. Arc.prototype.getDefaultStyle = function () {
  13151. return {
  13152. stroke: '#000',
  13153. fill: null
  13154. };
  13155. };
  13156. Arc.prototype.getDefaultShape = function () {
  13157. return new ArcShape();
  13158. };
  13159. Arc.prototype.buildPath = function (ctx, shape) {
  13160. var x = shape.cx;
  13161. var y = shape.cy;
  13162. var r = Math.max(shape.r, 0);
  13163. var startAngle = shape.startAngle;
  13164. var endAngle = shape.endAngle;
  13165. var clockwise = shape.clockwise;
  13166. var unitX = Math.cos(startAngle);
  13167. var unitY = Math.sin(startAngle);
  13168. ctx.moveTo(unitX * r + x, unitY * r + y);
  13169. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13170. };
  13171. return Arc;
  13172. }(Path));
  13173. Arc.prototype.type = 'arc';
  13174. var CompoundPath = (function (_super) {
  13175. __extends(CompoundPath, _super);
  13176. function CompoundPath() {
  13177. var _this = _super !== null && _super.apply(this, arguments) || this;
  13178. _this.type = 'compound';
  13179. return _this;
  13180. }
  13181. CompoundPath.prototype._updatePathDirty = function () {
  13182. var paths = this.shape.paths;
  13183. var dirtyPath = this.shapeChanged();
  13184. for (var i = 0; i < paths.length; i++) {
  13185. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13186. }
  13187. if (dirtyPath) {
  13188. this.dirtyShape();
  13189. }
  13190. };
  13191. CompoundPath.prototype.beforeBrush = function () {
  13192. this._updatePathDirty();
  13193. var paths = this.shape.paths || [];
  13194. var scale = this.getGlobalScale();
  13195. for (var i = 0; i < paths.length; i++) {
  13196. if (!paths[i].path) {
  13197. paths[i].createPathProxy();
  13198. }
  13199. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13200. }
  13201. };
  13202. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13203. var paths = shape.paths || [];
  13204. for (var i = 0; i < paths.length; i++) {
  13205. paths[i].buildPath(ctx, paths[i].shape, true);
  13206. }
  13207. };
  13208. CompoundPath.prototype.afterBrush = function () {
  13209. var paths = this.shape.paths || [];
  13210. for (var i = 0; i < paths.length; i++) {
  13211. paths[i].pathUpdated();
  13212. }
  13213. };
  13214. CompoundPath.prototype.getBoundingRect = function () {
  13215. this._updatePathDirty.call(this);
  13216. return Path.prototype.getBoundingRect.call(this);
  13217. };
  13218. return CompoundPath;
  13219. }(Path));
  13220. var Gradient = (function () {
  13221. function Gradient(colorStops) {
  13222. this.colorStops = colorStops || [];
  13223. }
  13224. Gradient.prototype.addColorStop = function (offset, color) {
  13225. this.colorStops.push({
  13226. offset: offset,
  13227. color: color
  13228. });
  13229. };
  13230. return Gradient;
  13231. }());
  13232. var LinearGradient = (function (_super) {
  13233. __extends(LinearGradient, _super);
  13234. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13235. var _this = _super.call(this, colorStops) || this;
  13236. _this.x = x == null ? 0 : x;
  13237. _this.y = y == null ? 0 : y;
  13238. _this.x2 = x2 == null ? 1 : x2;
  13239. _this.y2 = y2 == null ? 0 : y2;
  13240. _this.type = 'linear';
  13241. _this.global = globalCoord || false;
  13242. return _this;
  13243. }
  13244. return LinearGradient;
  13245. }(Gradient));
  13246. var RadialGradient = (function (_super) {
  13247. __extends(RadialGradient, _super);
  13248. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13249. var _this = _super.call(this, colorStops) || this;
  13250. _this.x = x == null ? 0.5 : x;
  13251. _this.y = y == null ? 0.5 : y;
  13252. _this.r = r == null ? 0.5 : r;
  13253. _this.type = 'radial';
  13254. _this.global = globalCoord || false;
  13255. return _this;
  13256. }
  13257. return RadialGradient;
  13258. }(Gradient));
  13259. var extent = [0, 0];
  13260. var extent2 = [0, 0];
  13261. var minTv$1 = new Point();
  13262. var maxTv$1 = new Point();
  13263. var OrientedBoundingRect = (function () {
  13264. function OrientedBoundingRect(rect, transform) {
  13265. this._corners = [];
  13266. this._axes = [];
  13267. this._origin = [0, 0];
  13268. for (var i = 0; i < 4; i++) {
  13269. this._corners[i] = new Point();
  13270. }
  13271. for (var i = 0; i < 2; i++) {
  13272. this._axes[i] = new Point();
  13273. }
  13274. if (rect) {
  13275. this.fromBoundingRect(rect, transform);
  13276. }
  13277. }
  13278. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13279. var corners = this._corners;
  13280. var axes = this._axes;
  13281. var x = rect.x;
  13282. var y = rect.y;
  13283. var x2 = x + rect.width;
  13284. var y2 = y + rect.height;
  13285. corners[0].set(x, y);
  13286. corners[1].set(x2, y);
  13287. corners[2].set(x2, y2);
  13288. corners[3].set(x, y2);
  13289. if (transform) {
  13290. for (var i = 0; i < 4; i++) {
  13291. corners[i].transform(transform);
  13292. }
  13293. }
  13294. Point.sub(axes[0], corners[1], corners[0]);
  13295. Point.sub(axes[1], corners[3], corners[0]);
  13296. axes[0].normalize();
  13297. axes[1].normalize();
  13298. for (var i = 0; i < 2; i++) {
  13299. this._origin[i] = axes[i].dot(corners[0]);
  13300. }
  13301. };
  13302. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13303. var overlapped = true;
  13304. var noMtv = !mtv;
  13305. minTv$1.set(Infinity, Infinity);
  13306. maxTv$1.set(0, 0);
  13307. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13308. overlapped = false;
  13309. if (noMtv) {
  13310. return overlapped;
  13311. }
  13312. }
  13313. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13314. overlapped = false;
  13315. if (noMtv) {
  13316. return overlapped;
  13317. }
  13318. }
  13319. if (!noMtv) {
  13320. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13321. }
  13322. return overlapped;
  13323. };
  13324. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13325. var overlapped = true;
  13326. for (var i = 0; i < 2; i++) {
  13327. var axis = this._axes[i];
  13328. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13329. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13330. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13331. overlapped = false;
  13332. if (noMtv) {
  13333. return overlapped;
  13334. }
  13335. var dist0 = Math.abs(extent2[0] - extent[1]);
  13336. var dist1 = Math.abs(extent[0] - extent2[1]);
  13337. if (Math.min(dist0, dist1) > maxTv.len()) {
  13338. if (dist0 < dist1) {
  13339. Point.scale(maxTv, axis, -dist0 * inverse);
  13340. }
  13341. else {
  13342. Point.scale(maxTv, axis, dist1 * inverse);
  13343. }
  13344. }
  13345. }
  13346. else if (minTv) {
  13347. var dist0 = Math.abs(extent2[0] - extent[1]);
  13348. var dist1 = Math.abs(extent[0] - extent2[1]);
  13349. if (Math.min(dist0, dist1) < minTv.len()) {
  13350. if (dist0 < dist1) {
  13351. Point.scale(minTv, axis, dist0 * inverse);
  13352. }
  13353. else {
  13354. Point.scale(minTv, axis, -dist1 * inverse);
  13355. }
  13356. }
  13357. }
  13358. }
  13359. return overlapped;
  13360. };
  13361. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13362. var axis = this._axes[dim];
  13363. var origin = this._origin;
  13364. var proj = corners[0].dot(axis) + origin[dim];
  13365. var min = proj;
  13366. var max = proj;
  13367. for (var i = 1; i < corners.length; i++) {
  13368. var proj_1 = corners[i].dot(axis) + origin[dim];
  13369. min = Math.min(proj_1, min);
  13370. max = Math.max(proj_1, max);
  13371. }
  13372. out[0] = min;
  13373. out[1] = max;
  13374. };
  13375. return OrientedBoundingRect;
  13376. }());
  13377. var m = [];
  13378. var IncrementalDisplayable = (function (_super) {
  13379. __extends(IncrementalDisplayable, _super);
  13380. function IncrementalDisplayable() {
  13381. var _this = _super !== null && _super.apply(this, arguments) || this;
  13382. _this.notClear = true;
  13383. _this.incremental = true;
  13384. _this._displayables = [];
  13385. _this._temporaryDisplayables = [];
  13386. _this._cursor = 0;
  13387. return _this;
  13388. }
  13389. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13390. cb.call(context, this);
  13391. };
  13392. IncrementalDisplayable.prototype.useStyle = function () {
  13393. this.style = {};
  13394. };
  13395. IncrementalDisplayable.prototype.getCursor = function () {
  13396. return this._cursor;
  13397. };
  13398. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13399. this._cursor = this._displayables.length;
  13400. };
  13401. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13402. this._displayables = [];
  13403. this._temporaryDisplayables = [];
  13404. this._cursor = 0;
  13405. this.markRedraw();
  13406. this.notClear = false;
  13407. };
  13408. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13409. this._temporaryDisplayables = [];
  13410. };
  13411. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13412. if (notPersistent) {
  13413. this._temporaryDisplayables.push(displayable);
  13414. }
  13415. else {
  13416. this._displayables.push(displayable);
  13417. }
  13418. this.markRedraw();
  13419. };
  13420. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13421. notPersistent = notPersistent || false;
  13422. for (var i = 0; i < displayables.length; i++) {
  13423. this.addDisplayable(displayables[i], notPersistent);
  13424. }
  13425. };
  13426. IncrementalDisplayable.prototype.getDisplayables = function () {
  13427. return this._displayables;
  13428. };
  13429. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13430. return this._temporaryDisplayables;
  13431. };
  13432. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13433. for (var i = this._cursor; i < this._displayables.length; i++) {
  13434. cb && cb(this._displayables[i]);
  13435. }
  13436. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13437. cb && cb(this._temporaryDisplayables[i]);
  13438. }
  13439. };
  13440. IncrementalDisplayable.prototype.update = function () {
  13441. this.updateTransform();
  13442. for (var i = this._cursor; i < this._displayables.length; i++) {
  13443. var displayable = this._displayables[i];
  13444. displayable.parent = this;
  13445. displayable.update();
  13446. displayable.parent = null;
  13447. }
  13448. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13449. var displayable = this._temporaryDisplayables[i];
  13450. displayable.parent = this;
  13451. displayable.update();
  13452. displayable.parent = null;
  13453. }
  13454. };
  13455. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13456. if (!this._rect) {
  13457. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13458. for (var i = 0; i < this._displayables.length; i++) {
  13459. var displayable = this._displayables[i];
  13460. var childRect = displayable.getBoundingRect().clone();
  13461. if (displayable.needLocalTransform()) {
  13462. childRect.applyTransform(displayable.getLocalTransform(m));
  13463. }
  13464. rect.union(childRect);
  13465. }
  13466. this._rect = rect;
  13467. }
  13468. return this._rect;
  13469. };
  13470. IncrementalDisplayable.prototype.contain = function (x, y) {
  13471. var localPos = this.transformCoordToLocal(x, y);
  13472. var rect = this.getBoundingRect();
  13473. if (rect.contain(localPos[0], localPos[1])) {
  13474. for (var i = 0; i < this._displayables.length; i++) {
  13475. var displayable = this._displayables[i];
  13476. if (displayable.contain(x, y)) {
  13477. return true;
  13478. }
  13479. }
  13480. }
  13481. return false;
  13482. };
  13483. return IncrementalDisplayable;
  13484. }(Displayable));
  13485. var mathMax$4 = Math.max;
  13486. var mathMin$4 = Math.min;
  13487. var _customShapeMap = {};
  13488. /**
  13489. * Extend shape with parameters
  13490. */
  13491. function extendShape(opts) {
  13492. return Path.extend(opts);
  13493. }
  13494. var extendPathFromString = extendFromString;
  13495. /**
  13496. * Extend path
  13497. */
  13498. function extendPath(pathData, opts) {
  13499. return extendPathFromString(pathData, opts);
  13500. }
  13501. /**
  13502. * Register a user defined shape.
  13503. * The shape class can be fetched by `getShapeClass`
  13504. * This method will overwrite the registered shapes, including
  13505. * the registered built-in shapes, if using the same `name`.
  13506. * The shape can be used in `custom series` and
  13507. * `graphic component` by declaring `{type: name}`.
  13508. *
  13509. * @param name
  13510. * @param ShapeClass Can be generated by `extendShape`.
  13511. */
  13512. function registerShape(name, ShapeClass) {
  13513. _customShapeMap[name] = ShapeClass;
  13514. }
  13515. /**
  13516. * Find shape class registered by `registerShape`. Usually used in
  13517. * fetching user defined shape.
  13518. *
  13519. * [Caution]:
  13520. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  13521. * to use user registered shapes.
  13522. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  13523. * `registerShape` by default. That enables users to get both built-in
  13524. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  13525. * the built-in shapes by using names like 'circle', 'rect' via calling
  13526. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  13527. * in case that it is overwritten by users, except that some features, like
  13528. * `custom series`, `graphic component`, do it deliberately.
  13529. *
  13530. * (2) In the features like `custom series`, `graphic component`, the user input
  13531. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  13532. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  13533. * are reserved names, that is, if some user register a shape named `'image'`,
  13534. * the shape will not be used. If we intending to add some more reserved names
  13535. * in feature, that might bring break changes (disable some existing user shape
  13536. * names). But that case probably rearly happen. So we dont make more mechanism
  13537. * to resolve this issue here.
  13538. *
  13539. * @param name
  13540. * @return The shape class. If not found, return nothing.
  13541. */
  13542. function getShapeClass(name) {
  13543. if (_customShapeMap.hasOwnProperty(name)) {
  13544. return _customShapeMap[name];
  13545. }
  13546. }
  13547. /**
  13548. * Create a path element from path data string
  13549. * @param pathData
  13550. * @param opts
  13551. * @param rect
  13552. * @param layout 'center' or 'cover' default to be cover
  13553. */
  13554. function makePath(pathData, opts, rect, layout) {
  13555. var path = createFromString(pathData, opts);
  13556. if (rect) {
  13557. if (layout === 'center') {
  13558. rect = centerGraphic(rect, path.getBoundingRect());
  13559. }
  13560. resizePath(path, rect);
  13561. }
  13562. return path;
  13563. }
  13564. /**
  13565. * Create a image element from image url
  13566. * @param imageUrl image url
  13567. * @param opts options
  13568. * @param rect constrain rect
  13569. * @param layout 'center' or 'cover'. Default to be 'cover'
  13570. */
  13571. function makeImage(imageUrl, rect, layout) {
  13572. var zrImg = new ZRImage({
  13573. style: {
  13574. image: imageUrl,
  13575. x: rect.x,
  13576. y: rect.y,
  13577. width: rect.width,
  13578. height: rect.height
  13579. },
  13580. onload: function (img) {
  13581. if (layout === 'center') {
  13582. var boundingRect = {
  13583. width: img.width,
  13584. height: img.height
  13585. };
  13586. zrImg.setStyle(centerGraphic(rect, boundingRect));
  13587. }
  13588. }
  13589. });
  13590. return zrImg;
  13591. }
  13592. /**
  13593. * Get position of centered element in bounding box.
  13594. *
  13595. * @param rect element local bounding box
  13596. * @param boundingRect constraint bounding box
  13597. * @return element position containing x, y, width, and height
  13598. */
  13599. function centerGraphic(rect, boundingRect) {
  13600. // Set rect to center, keep width / height ratio.
  13601. var aspect = boundingRect.width / boundingRect.height;
  13602. var width = rect.height * aspect;
  13603. var height;
  13604. if (width <= rect.width) {
  13605. height = rect.height;
  13606. } else {
  13607. width = rect.width;
  13608. height = width / aspect;
  13609. }
  13610. var cx = rect.x + rect.width / 2;
  13611. var cy = rect.y + rect.height / 2;
  13612. return {
  13613. x: cx - width / 2,
  13614. y: cy - height / 2,
  13615. width: width,
  13616. height: height
  13617. };
  13618. }
  13619. var mergePath$1 = mergePath;
  13620. /**
  13621. * Resize a path to fit the rect
  13622. * @param path
  13623. * @param rect
  13624. */
  13625. function resizePath(path, rect) {
  13626. if (!path.applyTransform) {
  13627. return;
  13628. }
  13629. var pathRect = path.getBoundingRect();
  13630. var m = pathRect.calculateTransform(rect);
  13631. path.applyTransform(m);
  13632. }
  13633. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  13634. var isFrom = false;
  13635. var removeOpt;
  13636. if (typeof dataIndex === 'function') {
  13637. during = cb;
  13638. cb = dataIndex;
  13639. dataIndex = null;
  13640. } else if (isObject(dataIndex)) {
  13641. cb = dataIndex.cb;
  13642. during = dataIndex.during;
  13643. isFrom = dataIndex.isFrom;
  13644. removeOpt = dataIndex.removeOpt;
  13645. dataIndex = dataIndex.dataIndex;
  13646. }
  13647. var isUpdate = animationType === 'update';
  13648. var isRemove = animationType === 'remove';
  13649. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  13650. // If animation is enabled. Will use this animation config in payload.
  13651. // If animation is disabled. Just ignore it.
  13652. if (animatableModel && animatableModel.ecModel) {
  13653. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  13654. animationPayload = updatePayload && updatePayload.animation;
  13655. }
  13656. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  13657. if (!isRemove) {
  13658. // Must stop the remove animation.
  13659. el.stopAnimation('remove');
  13660. }
  13661. if (animationEnabled) {
  13662. var duration = void 0;
  13663. var animationEasing = void 0;
  13664. var animationDelay = void 0;
  13665. if (animationPayload) {
  13666. duration = animationPayload.duration || 0;
  13667. animationEasing = animationPayload.easing || 'cubicOut';
  13668. animationDelay = animationPayload.delay || 0;
  13669. } else if (isRemove) {
  13670. removeOpt = removeOpt || {};
  13671. duration = retrieve2(removeOpt.duration, 200);
  13672. animationEasing = retrieve2(removeOpt.easing, 'cubicOut');
  13673. animationDelay = 0;
  13674. } else {
  13675. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  13676. animationEasing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  13677. animationDelay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  13678. }
  13679. if (typeof animationDelay === 'function') {
  13680. animationDelay = animationDelay(dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  13681. }
  13682. if (typeof duration === 'function') {
  13683. duration = duration(dataIndex);
  13684. }
  13685. duration > 0 ? isFrom ? el.animateFrom(props, {
  13686. duration: duration,
  13687. delay: animationDelay || 0,
  13688. easing: animationEasing,
  13689. done: cb,
  13690. force: !!cb || !!during,
  13691. scope: animationType,
  13692. during: during
  13693. }) : el.animateTo(props, {
  13694. duration: duration,
  13695. delay: animationDelay || 0,
  13696. easing: animationEasing,
  13697. done: cb,
  13698. force: !!cb || !!during,
  13699. setToFinal: true,
  13700. scope: animationType,
  13701. during: during
  13702. }) : ( // FIXME:
  13703. // If `duration` is 0, only the animation on props
  13704. // can be stoped, other animation should be continued?
  13705. // But at present using duration 0 in `animateTo`, `animateFrom`
  13706. // might cause unexpected behavior.
  13707. el.stopAnimation(), // If `isFrom`, the props is the "from" props.
  13708. !isFrom && el.attr(props), cb && cb());
  13709. } else {
  13710. el.stopAnimation();
  13711. !isFrom && el.attr(props); // Call during once.
  13712. during && during(1);
  13713. cb && cb();
  13714. }
  13715. }
  13716. /**
  13717. * Update graphic element properties with or without animation according to the
  13718. * configuration in series.
  13719. *
  13720. * Caution: this method will stop previous animation.
  13721. * So do not use this method to one element twice before
  13722. * animation starts, unless you know what you are doing.
  13723. * @example
  13724. * graphic.updateProps(el, {
  13725. * position: [100, 100]
  13726. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  13727. * // Or
  13728. * graphic.updateProps(el, {
  13729. * position: [100, 100]
  13730. * }, seriesModel, function () { console.log('Animation done!'); });
  13731. */
  13732. function updateProps(el, props, // TODO: TYPE AnimatableModel
  13733. animatableModel, dataIndex, cb, during) {
  13734. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  13735. }
  13736. /**
  13737. * Init graphic element properties with or without animation according to the
  13738. * configuration in series.
  13739. *
  13740. * Caution: this method will stop previous animation.
  13741. * So do not use this method to one element twice before
  13742. * animation starts, unless you know what you are doing.
  13743. */
  13744. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  13745. animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during);
  13746. }
  13747. /**
  13748. * Remove graphic element
  13749. */
  13750. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  13751. // Don't do remove animation twice.
  13752. if (isElementRemoved(el)) {
  13753. return;
  13754. }
  13755. animateOrSetProps('remove', el, props, animatableModel, dataIndex, cb, during);
  13756. }
  13757. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  13758. el.removeTextContent();
  13759. el.removeTextGuideLine();
  13760. removeElement(el, {
  13761. style: {
  13762. opacity: 0
  13763. }
  13764. }, animatableModel, dataIndex, done);
  13765. }
  13766. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  13767. function doRemove() {
  13768. el.parent && el.parent.remove(el);
  13769. } // Hide label and labelLine first
  13770. // TODO Also use fade out animation?
  13771. if (!el.isGroup) {
  13772. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  13773. } else {
  13774. el.traverse(function (disp) {
  13775. if (!disp.isGroup) {
  13776. // Can invoke doRemove multiple times.
  13777. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  13778. }
  13779. });
  13780. }
  13781. }
  13782. /**
  13783. * If element is removed.
  13784. * It can determine if element is having remove animation.
  13785. */
  13786. function isElementRemoved(el) {
  13787. if (!el.__zr) {
  13788. return true;
  13789. }
  13790. for (var i = 0; i < el.animators.length; i++) {
  13791. var animator = el.animators[i];
  13792. if (animator.scope === 'remove') {
  13793. return true;
  13794. }
  13795. }
  13796. return false;
  13797. }
  13798. /**
  13799. * Get transform matrix of target (param target),
  13800. * in coordinate of its ancestor (param ancestor)
  13801. *
  13802. * @param target
  13803. * @param [ancestor]
  13804. */
  13805. function getTransform(target, ancestor) {
  13806. var mat = identity([]);
  13807. while (target && target !== ancestor) {
  13808. mul$1(mat, target.getLocalTransform(), mat);
  13809. target = target.parent;
  13810. }
  13811. return mat;
  13812. }
  13813. function isNotGroup(el) {
  13814. return !el.isGroup;
  13815. }
  13816. function isPath(el) {
  13817. return el.shape != null;
  13818. }
  13819. /**
  13820. * Apply group transition animation from g1 to g2.
  13821. * If no animatableModel, no animation.
  13822. */
  13823. function groupTransition(g1, g2, animatableModel) {
  13824. if (!g1 || !g2) {
  13825. return;
  13826. }
  13827. function getElMap(g) {
  13828. var elMap = {};
  13829. g.traverse(function (el) {
  13830. if (isNotGroup(el) && el.anid) {
  13831. elMap[el.anid] = el;
  13832. }
  13833. });
  13834. return elMap;
  13835. }
  13836. function getAnimatableProps(el) {
  13837. var obj = {
  13838. x: el.x,
  13839. y: el.y,
  13840. rotation: el.rotation
  13841. };
  13842. if (isPath(el)) {
  13843. obj.shape = extend({}, el.shape);
  13844. }
  13845. return obj;
  13846. }
  13847. var elMap1 = getElMap(g1);
  13848. g2.traverse(function (el) {
  13849. if (isNotGroup(el) && el.anid) {
  13850. var oldEl = elMap1[el.anid];
  13851. if (oldEl) {
  13852. var newProp = getAnimatableProps(el);
  13853. el.attr(getAnimatableProps(oldEl));
  13854. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  13855. }
  13856. }
  13857. });
  13858. }
  13859. function clipPointsByRect(points, rect) {
  13860. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  13861. // and when element have border.
  13862. return map(points, function (point) {
  13863. var x = point[0];
  13864. x = mathMax$4(x, rect.x);
  13865. x = mathMin$4(x, rect.x + rect.width);
  13866. var y = point[1];
  13867. y = mathMax$4(y, rect.y);
  13868. y = mathMin$4(y, rect.y + rect.height);
  13869. return [x, y];
  13870. });
  13871. }
  13872. /**
  13873. * Return a new clipped rect. If rect size are negative, return undefined.
  13874. */
  13875. function clipRectByRect(targetRect, rect) {
  13876. var x = mathMax$4(targetRect.x, rect.x);
  13877. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  13878. var y = mathMax$4(targetRect.y, rect.y);
  13879. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  13880. // should be painted. So return undefined.
  13881. if (x2 >= x && y2 >= y) {
  13882. return {
  13883. x: x,
  13884. y: y,
  13885. width: x2 - x,
  13886. height: y2 - y
  13887. };
  13888. }
  13889. }
  13890. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  13891. opt, rect) {
  13892. var innerOpts = extend({
  13893. rectHover: true
  13894. }, opt);
  13895. var style = innerOpts.style = {
  13896. strokeNoScale: true
  13897. };
  13898. rect = rect || {
  13899. x: -1,
  13900. y: -1,
  13901. width: 2,
  13902. height: 2
  13903. };
  13904. if (iconStr) {
  13905. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  13906. }
  13907. }
  13908. // by users, although we do not recommend that.
  13909. registerShape('circle', Circle);
  13910. registerShape('ellipse', Ellipse);
  13911. registerShape('sector', Sector);
  13912. registerShape('ring', Ring);
  13913. registerShape('polygon', Polygon);
  13914. registerShape('polyline', Polyline);
  13915. registerShape('rect', Rect);
  13916. registerShape('line', Line);
  13917. registerShape('bezierCurve', BezierCurve);
  13918. registerShape('arc', Arc);
  13919. var EMPTY_OBJ = {};
  13920. function setLabelText(label, labelTexts) {
  13921. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  13922. var stateName = SPECIAL_STATES[i];
  13923. var text = labelTexts[stateName];
  13924. var state = label.ensureState(stateName);
  13925. state.style = state.style || {};
  13926. state.style.text = text;
  13927. }
  13928. var oldStates = label.currentStates.slice();
  13929. label.clearStates(true);
  13930. label.setStyle({
  13931. text: labelTexts.normal
  13932. });
  13933. label.useStates(oldStates, true);
  13934. }
  13935. function getLabelText(opt, stateModels, interpolatedValue) {
  13936. var labelFetcher = opt.labelFetcher;
  13937. var labelDataIndex = opt.labelDataIndex;
  13938. var labelDimIndex = opt.labelDimIndex;
  13939. var normalModel = stateModels.normal;
  13940. var baseText;
  13941. if (labelFetcher) {
  13942. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  13943. interpolatedValue: interpolatedValue
  13944. } : null);
  13945. }
  13946. if (baseText == null) {
  13947. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  13948. }
  13949. var statesText = {
  13950. normal: baseText
  13951. };
  13952. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  13953. var stateName = SPECIAL_STATES[i];
  13954. var stateModel = stateModels[stateName];
  13955. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  13956. }
  13957. return statesText;
  13958. }
  13959. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  13960. ) {
  13961. opt = opt || EMPTY_OBJ;
  13962. var isSetOnText = targetEl instanceof ZRText;
  13963. var needsCreateText = false;
  13964. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  13965. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  13966. if (stateModel && stateModel.getShallow('show')) {
  13967. needsCreateText = true;
  13968. break;
  13969. }
  13970. }
  13971. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  13972. if (needsCreateText) {
  13973. if (!isSetOnText) {
  13974. // Reuse the previous
  13975. if (!textContent) {
  13976. textContent = new ZRText();
  13977. targetEl.setTextContent(textContent);
  13978. } // Use same state proxy
  13979. if (targetEl.stateProxy) {
  13980. textContent.stateProxy = targetEl.stateProxy;
  13981. }
  13982. }
  13983. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  13984. var normalModel = labelStatesModels.normal;
  13985. var showNormal = !!normalModel.getShallow('show');
  13986. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  13987. normalStyle.text = labelStatesTexts.normal;
  13988. if (!isSetOnText) {
  13989. // Always create new
  13990. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  13991. }
  13992. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  13993. var stateName = SPECIAL_STATES[i];
  13994. var stateModel = labelStatesModels[stateName];
  13995. if (stateModel) {
  13996. var stateObj = textContent.ensureState(stateName);
  13997. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  13998. if (stateShow !== showNormal) {
  13999. stateObj.ignore = !stateShow;
  14000. }
  14001. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14002. stateObj.style.text = labelStatesTexts[stateName];
  14003. if (!isSetOnText) {
  14004. var targetElEmphasisState = targetEl.ensureState(stateName);
  14005. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14006. }
  14007. }
  14008. } // PENDING: if there is many requirements that emphasis position
  14009. // need to be different from normal position, we might consider
  14010. // auto slient is those cases.
  14011. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14012. if (textContent.style.x != null) {
  14013. normalStyle.x = textContent.style.x;
  14014. }
  14015. if (textContent.style.y != null) {
  14016. normalStyle.y = textContent.style.y;
  14017. }
  14018. textContent.ignore = !showNormal; // Always create new style.
  14019. textContent.useStyle(normalStyle);
  14020. textContent.dirty();
  14021. if (opt.enableTextSetter) {
  14022. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14023. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14024. setLabelText(textContent, labelStatesTexts);
  14025. };
  14026. }
  14027. } else if (textContent) {
  14028. // Not display rich text.
  14029. textContent.ignore = true;
  14030. }
  14031. targetEl.dirty();
  14032. }
  14033. function getLabelStatesModels(itemModel, labelName) {
  14034. labelName = labelName || 'label';
  14035. var statesModels = {
  14036. normal: itemModel.getModel(labelName)
  14037. };
  14038. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14039. var stateName = SPECIAL_STATES[i];
  14040. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14041. }
  14042. return statesModels;
  14043. }
  14044. /**
  14045. * Set basic textStyle properties.
  14046. */
  14047. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14048. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14049. ) {
  14050. var textStyle = {};
  14051. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14052. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14053. return textStyle;
  14054. }
  14055. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14056. opt = opt || {};
  14057. var textConfig = {};
  14058. var labelPosition;
  14059. var labelRotate = textStyleModel.getShallow('rotate');
  14060. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14061. var labelOffset = textStyleModel.getShallow('offset');
  14062. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14063. // in bar series, and magric type should be considered.
  14064. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14065. if (labelPosition != null) {
  14066. textConfig.position = labelPosition;
  14067. }
  14068. if (labelOffset != null) {
  14069. textConfig.offset = labelOffset;
  14070. }
  14071. if (labelRotate != null) {
  14072. labelRotate *= Math.PI / 180;
  14073. textConfig.rotation = labelRotate;
  14074. }
  14075. if (labelDistance != null) {
  14076. textConfig.distance = labelDistance;
  14077. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14078. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14079. return textConfig;
  14080. }
  14081. /**
  14082. * The uniform entry of set text style, that is, retrieve style definitions
  14083. * from `model` and set to `textStyle` object.
  14084. *
  14085. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14086. * properties will be set. (Consider the states of normal and emphasis and
  14087. * default value can be adopted, merge would make the logic too complicated
  14088. * to manage.)
  14089. */
  14090. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14091. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14092. opt = opt || EMPTY_OBJ;
  14093. var ecModel = textStyleModel.ecModel;
  14094. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14095. // {
  14096. // data: [{
  14097. // value: 12,
  14098. // label: {
  14099. // rich: {
  14100. // // no 'a' here but using parent 'a'.
  14101. // }
  14102. // }
  14103. // }],
  14104. // rich: {
  14105. // a: { ... }
  14106. // }
  14107. // }
  14108. var richItemNames = getRichItemNames(textStyleModel);
  14109. var richResult;
  14110. if (richItemNames) {
  14111. richResult = {};
  14112. for (var name_1 in richItemNames) {
  14113. if (richItemNames.hasOwnProperty(name_1)) {
  14114. // Cascade is supported in rich.
  14115. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14116. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14117. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14118. // That might confuses users. So probably we should put `textStyleModel` as the
  14119. // root ancestor of the `richTextStyle`. But that would be a break change.
  14120. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14121. }
  14122. }
  14123. }
  14124. if (richResult) {
  14125. textStyle.rich = richResult;
  14126. }
  14127. var overflow = textStyleModel.get('overflow');
  14128. if (overflow) {
  14129. textStyle.overflow = overflow;
  14130. }
  14131. var margin = textStyleModel.get('minMargin');
  14132. if (margin != null) {
  14133. textStyle.margin = margin;
  14134. }
  14135. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14136. } // Consider case:
  14137. // {
  14138. // data: [{
  14139. // value: 12,
  14140. // label: {
  14141. // rich: {
  14142. // // no 'a' here but using parent 'a'.
  14143. // }
  14144. // }
  14145. // }],
  14146. // rich: {
  14147. // a: { ... }
  14148. // }
  14149. // }
  14150. // TODO TextStyleModel
  14151. function getRichItemNames(textStyleModel) {
  14152. // Use object to remove duplicated names.
  14153. var richItemNameMap;
  14154. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14155. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14156. if (rich) {
  14157. richItemNameMap = richItemNameMap || {};
  14158. var richKeys = keys(rich);
  14159. for (var i = 0; i < richKeys.length; i++) {
  14160. var richKey = richKeys[i];
  14161. richItemNameMap[richKey] = 1;
  14162. }
  14163. }
  14164. textStyleModel = textStyleModel.parentModel;
  14165. }
  14166. return richItemNameMap;
  14167. }
  14168. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14169. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  14170. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14171. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14172. // In merge mode, default value should not be given.
  14173. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14174. var inheritColor = opt && opt.inheritColor;
  14175. var fillColor = textStyleModel.getShallow('color');
  14176. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14177. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14178. if (fillColor === 'inherit' || fillColor === 'auto') {
  14179. if ("development" !== 'production') {
  14180. if (fillColor === 'auto') {
  14181. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14182. }
  14183. }
  14184. if (inheritColor) {
  14185. fillColor = inheritColor;
  14186. } else {
  14187. fillColor = null;
  14188. }
  14189. }
  14190. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14191. if ("development" !== 'production') {
  14192. if (strokeColor === 'auto') {
  14193. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14194. }
  14195. }
  14196. if (inheritColor) {
  14197. strokeColor = inheritColor;
  14198. } else {
  14199. strokeColor = null;
  14200. }
  14201. }
  14202. if (!isAttached) {
  14203. // Only use default global textStyle.color if text is individual.
  14204. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14205. fillColor = fillColor || globalTextStyle.color;
  14206. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14207. }
  14208. if (fillColor != null) {
  14209. textStyle.fill = fillColor;
  14210. }
  14211. if (strokeColor != null) {
  14212. textStyle.stroke = strokeColor;
  14213. }
  14214. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14215. if (textBorderWidth != null) {
  14216. textStyle.lineWidth = textBorderWidth;
  14217. }
  14218. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14219. if (textBorderType != null) {
  14220. textStyle.lineDash = textBorderType;
  14221. }
  14222. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14223. if (textBorderDashOffset != null) {
  14224. textStyle.lineDashOffset = textBorderDashOffset;
  14225. }
  14226. if (!isNotNormal && opacity == null && !inRich) {
  14227. opacity = opt && opt.defaultOpacity;
  14228. }
  14229. if (opacity != null) {
  14230. textStyle.opacity = opacity;
  14231. } // TODO
  14232. if (!isNotNormal && !isAttached) {
  14233. // Set default finally.
  14234. if (textStyle.fill == null && opt.inheritColor) {
  14235. textStyle.fill = opt.inheritColor;
  14236. }
  14237. } // Do not use `getFont` here, because merge should be supported, where
  14238. // part of these properties may be changed in emphasis style, and the
  14239. // others should remain their original value got from normal style.
  14240. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14241. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14242. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14243. if (val != null) {
  14244. textStyle[key] = val;
  14245. }
  14246. }
  14247. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14248. var key = TEXT_PROPS_SELF[i];
  14249. var val = textStyleModel.getShallow(key);
  14250. if (val != null) {
  14251. textStyle[key] = val;
  14252. }
  14253. }
  14254. if (textStyle.verticalAlign == null) {
  14255. var baseline = textStyleModel.getShallow('baseline');
  14256. if (baseline != null) {
  14257. textStyle.verticalAlign = baseline;
  14258. }
  14259. }
  14260. if (!isBlock || !opt.disableBox) {
  14261. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  14262. var key = TEXT_PROPS_BOX[i];
  14263. var val = textStyleModel.getShallow(key);
  14264. if (val != null) {
  14265. textStyle[key] = val;
  14266. }
  14267. }
  14268. var borderType = textStyleModel.getShallow('borderType');
  14269. if (borderType != null) {
  14270. textStyle.borderDash = borderType;
  14271. }
  14272. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  14273. if ("development" !== 'production') {
  14274. if (textStyle.backgroundColor === 'auto') {
  14275. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  14276. }
  14277. }
  14278. textStyle.backgroundColor = inheritColor;
  14279. }
  14280. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  14281. if ("development" !== 'production') {
  14282. if (textStyle.borderColor === 'auto') {
  14283. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  14284. }
  14285. }
  14286. textStyle.borderColor = inheritColor;
  14287. }
  14288. }
  14289. }
  14290. function getFont(opt, ecModel) {
  14291. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14292. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14293. 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(' '));
  14294. }
  14295. var labelInner = makeInner();
  14296. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  14297. if (!label) {
  14298. return;
  14299. }
  14300. var obj = labelInner(label);
  14301. obj.prevValue = obj.value;
  14302. obj.value = value;
  14303. var normalLabelModel = labelStatesModels.normal;
  14304. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  14305. if (obj.valueAnimation) {
  14306. obj.precision = normalLabelModel.get('precision');
  14307. obj.defaultInterpolatedText = getDefaultText;
  14308. obj.statesModels = labelStatesModels;
  14309. }
  14310. }
  14311. function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) {
  14312. var labelInnerStore = labelInner(textEl);
  14313. if (!labelInnerStore.valueAnimation) {
  14314. return;
  14315. }
  14316. var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText; // Consider the case that being animating, do not use the `obj.value`,
  14317. // Otherwise it will jump to the `obj.value` when this new animation started.
  14318. var currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue);
  14319. var targetValue = labelInnerStore.value;
  14320. function during(percent) {
  14321. var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent);
  14322. labelInnerStore.interpolatedValue = percent === 1 ? null : interpolated;
  14323. var labelText = getLabelText({
  14324. labelDataIndex: dataIndex,
  14325. labelFetcher: labelFetcher,
  14326. defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + ''
  14327. }, labelInnerStore.statesModels, interpolated);
  14328. setLabelText(textEl, labelText);
  14329. }
  14330. (currValue == null ? initProps : updateProps)(textEl, {}, animatableModel, dataIndex, null, during);
  14331. }
  14332. var PATH_COLOR = ['textStyle', 'color']; // TODO Performance improvement?
  14333. var tmpRichText = new ZRText();
  14334. var TextStyleMixin =
  14335. /** @class */
  14336. function () {
  14337. function TextStyleMixin() {}
  14338. /**
  14339. * Get color property or get color from option.textStyle.color
  14340. */
  14341. // TODO Callback
  14342. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  14343. var ecModel = this.ecModel;
  14344. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  14345. };
  14346. /**
  14347. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14348. * @return {string}
  14349. */
  14350. TextStyleMixin.prototype.getFont = function () {
  14351. return getFont({
  14352. fontStyle: this.getShallow('fontStyle'),
  14353. fontWeight: this.getShallow('fontWeight'),
  14354. fontSize: this.getShallow('fontSize'),
  14355. fontFamily: this.getShallow('fontFamily')
  14356. }, this.ecModel);
  14357. };
  14358. TextStyleMixin.prototype.getTextRect = function (text) {
  14359. tmpRichText.useStyle({
  14360. text: text,
  14361. fontStyle: this.getShallow('fontStyle'),
  14362. fontWeight: this.getShallow('fontWeight'),
  14363. fontSize: this.getShallow('fontSize'),
  14364. fontFamily: this.getShallow('fontFamily'),
  14365. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14366. padding: this.getShallow('padding'),
  14367. lineHeight: this.getShallow('lineHeight'),
  14368. rich: this.getShallow('rich')
  14369. });
  14370. tmpRichText.update();
  14371. return tmpRichText.getBoundingRect();
  14372. };
  14373. return TextStyleMixin;
  14374. }();
  14375. 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`.
  14376. // So do not transfer decal directly.
  14377. ];
  14378. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  14379. var LineStyleMixin =
  14380. /** @class */
  14381. function () {
  14382. function LineStyleMixin() {}
  14383. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  14384. return getLineStyle(this, excludes);
  14385. };
  14386. return LineStyleMixin;
  14387. }();
  14388. 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`.
  14389. // So do not transfer decal directly.
  14390. ];
  14391. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  14392. var ItemStyleMixin =
  14393. /** @class */
  14394. function () {
  14395. function ItemStyleMixin() {}
  14396. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  14397. return getItemStyle(this, excludes, includes);
  14398. };
  14399. return ItemStyleMixin;
  14400. }();
  14401. var Model =
  14402. /** @class */
  14403. function () {
  14404. function Model(option, parentModel, ecModel) {
  14405. this.parentModel = parentModel;
  14406. this.ecModel = ecModel;
  14407. this.option = option; // Simple optimization
  14408. // if (this.init) {
  14409. // if (arguments.length <= 4) {
  14410. // this.init(option, parentModel, ecModel, extraOpt);
  14411. // }
  14412. // else {
  14413. // this.init.apply(this, arguments);
  14414. // }
  14415. // }
  14416. }
  14417. Model.prototype.init = function (option, parentModel, ecModel) {
  14418. var rest = [];
  14419. for (var _i = 3; _i < arguments.length; _i++) {
  14420. rest[_i - 3] = arguments[_i];
  14421. }
  14422. };
  14423. /**
  14424. * Merge the input option to me.
  14425. */
  14426. Model.prototype.mergeOption = function (option, ecModel) {
  14427. merge(this.option, option, true);
  14428. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `ModelOption`
  14429. // TODO: TYPE strict key check?
  14430. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  14431. Model.prototype.get = function (path, ignoreParent) {
  14432. if (path == null) {
  14433. return this.option;
  14434. }
  14435. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  14436. };
  14437. Model.prototype.getShallow = function (key, ignoreParent) {
  14438. var option = this.option;
  14439. var val = option == null ? option : option[key];
  14440. if (val == null && !ignoreParent) {
  14441. var parentModel = this.parentModel;
  14442. if (parentModel) {
  14443. // FIXME:TS do not know how to make it works
  14444. val = parentModel.getShallow(key);
  14445. }
  14446. }
  14447. return val;
  14448. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `Model<ModelOption>`
  14449. // getModel(path: string | string[], parentModel?: Model): Model;
  14450. // TODO 'xxx.yyy.zzz' is deprecated
  14451. Model.prototype.getModel = function (path, parentModel) {
  14452. var hasPath = path != null;
  14453. var pathFinal = hasPath ? this.parsePath(path) : null;
  14454. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  14455. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  14456. return new Model(obj, parentModel, this.ecModel);
  14457. };
  14458. /**
  14459. * Squash option stack into one.
  14460. * parentModel will be removed after squashed.
  14461. *
  14462. * NOTE: resolveParentPath will not be applied here for simplicity. DON'T use this function
  14463. * if resolveParentPath is modified.
  14464. *
  14465. * @param deepMerge If do deep merge. Default to be false.
  14466. */
  14467. // squash(
  14468. // deepMerge?: boolean,
  14469. // handleCallback?: (func: () => object) => object
  14470. // ) {
  14471. // const optionStack = [];
  14472. // let model: Model = this;
  14473. // while (model) {
  14474. // if (model.option) {
  14475. // optionStack.push(model.option);
  14476. // }
  14477. // model = model.parentModel;
  14478. // }
  14479. // const newOption = {} as Opt;
  14480. // let option;
  14481. // while (option = optionStack.pop()) { // Top down merge
  14482. // if (isFunction(option) && handleCallback) {
  14483. // option = handleCallback(option);
  14484. // }
  14485. // if (deepMerge) {
  14486. // merge(newOption, option);
  14487. // }
  14488. // else {
  14489. // extend(newOption, option);
  14490. // }
  14491. // }
  14492. // // Remove parentModel
  14493. // this.option = newOption;
  14494. // this.parentModel = null;
  14495. // }
  14496. /**
  14497. * If model has option
  14498. */
  14499. Model.prototype.isEmpty = function () {
  14500. return this.option == null;
  14501. };
  14502. Model.prototype.restoreData = function () {}; // Pending
  14503. Model.prototype.clone = function () {
  14504. var Ctor = this.constructor;
  14505. return new Ctor(clone(this.option));
  14506. }; // setReadOnly(properties): void {
  14507. // clazzUtil.setReadOnly(this, properties);
  14508. // }
  14509. // If path is null/undefined, return null/undefined.
  14510. Model.prototype.parsePath = function (path) {
  14511. if (typeof path === 'string') {
  14512. return path.split('.');
  14513. }
  14514. return path;
  14515. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  14516. // Default to be a identity resolver.
  14517. // Can be modified to a different resolver.
  14518. Model.prototype.resolveParentPath = function (path) {
  14519. return path;
  14520. }; // FIXME:TS check whether put this method here
  14521. Model.prototype.isAnimationEnabled = function () {
  14522. if (!env.node && this.option) {
  14523. if (this.option.animation != null) {
  14524. return !!this.option.animation;
  14525. } else if (this.parentModel) {
  14526. return this.parentModel.isAnimationEnabled();
  14527. }
  14528. }
  14529. };
  14530. Model.prototype._doGet = function (pathArr, parentModel) {
  14531. var obj = this.option;
  14532. if (!pathArr) {
  14533. return obj;
  14534. }
  14535. for (var i = 0; i < pathArr.length; i++) {
  14536. // Ignore empty
  14537. if (!pathArr[i]) {
  14538. continue;
  14539. } // obj could be number/string/... (like 0)
  14540. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  14541. if (obj == null) {
  14542. break;
  14543. }
  14544. }
  14545. if (obj == null && parentModel) {
  14546. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  14547. }
  14548. return obj;
  14549. };
  14550. return Model;
  14551. }();
  14552. enableClassExtend(Model);
  14553. enableClassCheck(Model);
  14554. mixin(Model, LineStyleMixin);
  14555. mixin(Model, ItemStyleMixin);
  14556. mixin(Model, AreaStyleMixin);
  14557. mixin(Model, TextStyleMixin);
  14558. var base = Math.round(Math.random() * 10);
  14559. /**
  14560. * @public
  14561. * @param {string} type
  14562. * @return {string}
  14563. */
  14564. function getUID(type) {
  14565. // Considering the case of crossing js context,
  14566. // use Math.random to make id as unique as possible.
  14567. return [type || '', base++].join('_');
  14568. }
  14569. /**
  14570. * Implements `SubTypeDefaulterManager` for `target`.
  14571. */
  14572. function enableSubTypeDefaulter(target) {
  14573. var subTypeDefaulters = {};
  14574. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  14575. var componentTypeInfo = parseClassType(componentType);
  14576. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  14577. };
  14578. target.determineSubType = function (componentType, option) {
  14579. var type = option.type;
  14580. if (!type) {
  14581. var componentTypeMain = parseClassType(componentType).main;
  14582. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14583. type = subTypeDefaulters[componentTypeMain](option);
  14584. }
  14585. }
  14586. return type;
  14587. };
  14588. }
  14589. /**
  14590. * Implements `TopologicalTravelable<any>` for `entity`.
  14591. *
  14592. * Topological travel on Activity Network (Activity On Vertices).
  14593. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14594. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14595. * If there is circle dependencey, Error will be thrown.
  14596. */
  14597. function enableTopologicalTravel(entity, dependencyGetter) {
  14598. /**
  14599. * @param targetNameList Target Component type list.
  14600. * Can be ['aa', 'bb', 'aa.xx']
  14601. * @param fullNameList By which we can build dependency graph.
  14602. * @param callback Params: componentType, dependencies.
  14603. * @param context Scope of callback.
  14604. */
  14605. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14606. if (!targetNameList.length) {
  14607. return;
  14608. }
  14609. var result = makeDepndencyGraph(fullNameList);
  14610. var graph = result.graph;
  14611. var noEntryList = result.noEntryList;
  14612. var targetNameSet = {};
  14613. each(targetNameList, function (name) {
  14614. targetNameSet[name] = true;
  14615. });
  14616. while (noEntryList.length) {
  14617. var currComponentType = noEntryList.pop();
  14618. var currVertex = graph[currComponentType];
  14619. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14620. if (isInTargetNameSet) {
  14621. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14622. delete targetNameSet[currComponentType];
  14623. }
  14624. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  14625. }
  14626. each(targetNameSet, function () {
  14627. var errMsg = '';
  14628. if ("development" !== 'production') {
  14629. errMsg = makePrintable('Circle dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  14630. }
  14631. throw new Error(errMsg);
  14632. });
  14633. function removeEdge(succComponentType) {
  14634. graph[succComponentType].entryCount--;
  14635. if (graph[succComponentType].entryCount === 0) {
  14636. noEntryList.push(succComponentType);
  14637. }
  14638. } // Consider this case: legend depends on series, and we call
  14639. // chart.setOption({series: [...]}), where only series is in option.
  14640. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14641. // not be called, but only sereis.mergeOption is called. Thus legend
  14642. // have no chance to update its local record about series (like which
  14643. // name of series is available in legend).
  14644. function removeEdgeAndAdd(succComponentType) {
  14645. targetNameSet[succComponentType] = true;
  14646. removeEdge(succComponentType);
  14647. }
  14648. };
  14649. function makeDepndencyGraph(fullNameList) {
  14650. var graph = {};
  14651. var noEntryList = [];
  14652. each(fullNameList, function (name) {
  14653. var thisItem = createDependencyGraphItem(graph, name);
  14654. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14655. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14656. thisItem.entryCount = availableDeps.length;
  14657. if (thisItem.entryCount === 0) {
  14658. noEntryList.push(name);
  14659. }
  14660. each(availableDeps, function (dependentName) {
  14661. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14662. thisItem.predecessor.push(dependentName);
  14663. }
  14664. var thatItem = createDependencyGraphItem(graph, dependentName);
  14665. if (indexOf(thatItem.successor, dependentName) < 0) {
  14666. thatItem.successor.push(name);
  14667. }
  14668. });
  14669. });
  14670. return {
  14671. graph: graph,
  14672. noEntryList: noEntryList
  14673. };
  14674. }
  14675. function createDependencyGraphItem(graph, name) {
  14676. if (!graph[name]) {
  14677. graph[name] = {
  14678. predecessor: [],
  14679. successor: []
  14680. };
  14681. }
  14682. return graph[name];
  14683. }
  14684. function getAvailableDependencies(originalDeps, fullNameList) {
  14685. var availableDeps = [];
  14686. each(originalDeps, function (dep) {
  14687. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  14688. });
  14689. return availableDeps;
  14690. }
  14691. }
  14692. function inheritDefaultOption(superOption, subOption) {
  14693. // See also `model/Component.ts#getDefaultOption`
  14694. return merge(merge({}, superOption, true), subOption, true);
  14695. }
  14696. /*
  14697. * Licensed to the Apache Software Foundation (ASF) under one
  14698. * or more contributor license agreements. See the NOTICE file
  14699. * distributed with this work for additional information
  14700. * regarding copyright ownership. The ASF licenses this file
  14701. * to you under the Apache License, Version 2.0 (the
  14702. * "License"); you may not use this file except in compliance
  14703. * with the License. You may obtain a copy of the License at
  14704. *
  14705. * http://www.apache.org/licenses/LICENSE-2.0
  14706. *
  14707. * Unless required by applicable law or agreed to in writing,
  14708. * software distributed under the License is distributed on an
  14709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14710. * KIND, either express or implied. See the License for the
  14711. * specific language governing permissions and limitations
  14712. * under the License.
  14713. */
  14714. /**
  14715. * AUTO-GENERATED FILE. DO NOT MODIFY.
  14716. */
  14717. /*
  14718. * Licensed to the Apache Software Foundation (ASF) under one
  14719. * or more contributor license agreements. See the NOTICE file
  14720. * distributed with this work for additional information
  14721. * regarding copyright ownership. The ASF licenses this file
  14722. * to you under the Apache License, Version 2.0 (the
  14723. * "License"); you may not use this file except in compliance
  14724. * with the License. You may obtain a copy of the License at
  14725. *
  14726. * http://www.apache.org/licenses/LICENSE-2.0
  14727. *
  14728. * Unless required by applicable law or agreed to in writing,
  14729. * software distributed under the License is distributed on an
  14730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14731. * KIND, either express or implied. See the License for the
  14732. * specific language governing permissions and limitations
  14733. * under the License.
  14734. */
  14735. /**
  14736. * Language: English.
  14737. */
  14738. var langEN = {
  14739. time: {
  14740. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  14741. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  14742. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  14743. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  14744. },
  14745. legend: {
  14746. selector: {
  14747. all: 'All',
  14748. inverse: 'Inv'
  14749. }
  14750. },
  14751. toolbox: {
  14752. brush: {
  14753. title: {
  14754. rect: 'Box Select',
  14755. polygon: 'Lasso Select',
  14756. lineX: 'Horizontally Select',
  14757. lineY: 'Vertically Select',
  14758. keep: 'Keep Selections',
  14759. clear: 'Clear Selections'
  14760. }
  14761. },
  14762. dataView: {
  14763. title: 'Data View',
  14764. lang: ['Data View', 'Close', 'Refresh']
  14765. },
  14766. dataZoom: {
  14767. title: {
  14768. zoom: 'Zoom',
  14769. back: 'Zoom Reset'
  14770. }
  14771. },
  14772. magicType: {
  14773. title: {
  14774. line: 'Switch to Line Chart',
  14775. bar: 'Switch to Bar Chart',
  14776. stack: 'Stack',
  14777. tiled: 'Tile'
  14778. }
  14779. },
  14780. restore: {
  14781. title: 'Restore'
  14782. },
  14783. saveAsImage: {
  14784. title: 'Save as Image',
  14785. lang: ['Right Click to Save Image']
  14786. }
  14787. },
  14788. series: {
  14789. typeNames: {
  14790. pie: 'Pie chart',
  14791. bar: 'Bar chart',
  14792. line: 'Line chart',
  14793. scatter: 'Scatter plot',
  14794. effectScatter: 'Ripple scatter plot',
  14795. radar: 'Radar chart',
  14796. tree: 'Tree',
  14797. treemap: 'Treemap',
  14798. boxplot: 'Boxplot',
  14799. candlestick: 'Candlestick',
  14800. k: 'K line chart',
  14801. heatmap: 'Heat map',
  14802. map: 'Map',
  14803. parallel: 'Parallel coordinate map',
  14804. lines: 'Line graph',
  14805. graph: 'Relationship graph',
  14806. sankey: 'Sankey diagram',
  14807. funnel: 'Funnel chart',
  14808. gauge: 'Guage',
  14809. pictorialBar: 'Pictorial bar',
  14810. themeRiver: 'Theme River Map',
  14811. sunburst: 'Sunburst'
  14812. }
  14813. },
  14814. aria: {
  14815. general: {
  14816. withTitle: 'This is a chart about "{title}"',
  14817. withoutTitle: 'This is a chart'
  14818. },
  14819. series: {
  14820. single: {
  14821. prefix: '',
  14822. withName: ' with type {seriesType} named {seriesName}.',
  14823. withoutName: ' with type {seriesType}.'
  14824. },
  14825. multiple: {
  14826. prefix: '. It consists of {seriesCount} series count.',
  14827. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  14828. withoutName: ' The {seriesId} series is a {seriesType}.',
  14829. separator: {
  14830. middle: '',
  14831. end: ''
  14832. }
  14833. }
  14834. },
  14835. data: {
  14836. allData: 'The data is as follows: ',
  14837. partialData: 'The first {displayCnt} items are: ',
  14838. withName: 'the data for {name} is {value}',
  14839. withoutName: '{value}',
  14840. separator: {
  14841. middle: ', ',
  14842. end: '. '
  14843. }
  14844. }
  14845. }
  14846. };
  14847. /*
  14848. * Licensed to the Apache Software Foundation (ASF) under one
  14849. * or more contributor license agreements. See the NOTICE file
  14850. * distributed with this work for additional information
  14851. * regarding copyright ownership. The ASF licenses this file
  14852. * to you under the Apache License, Version 2.0 (the
  14853. * "License"); you may not use this file except in compliance
  14854. * with the License. You may obtain a copy of the License at
  14855. *
  14856. * http://www.apache.org/licenses/LICENSE-2.0
  14857. *
  14858. * Unless required by applicable law or agreed to in writing,
  14859. * software distributed under the License is distributed on an
  14860. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14861. * KIND, either express or implied. See the License for the
  14862. * specific language governing permissions and limitations
  14863. * under the License.
  14864. */
  14865. /**
  14866. * AUTO-GENERATED FILE. DO NOT MODIFY.
  14867. */
  14868. /*
  14869. * Licensed to the Apache Software Foundation (ASF) under one
  14870. * or more contributor license agreements. See the NOTICE file
  14871. * distributed with this work for additional information
  14872. * regarding copyright ownership. The ASF licenses this file
  14873. * to you under the Apache License, Version 2.0 (the
  14874. * "License"); you may not use this file except in compliance
  14875. * with the License. You may obtain a copy of the License at
  14876. *
  14877. * http://www.apache.org/licenses/LICENSE-2.0
  14878. *
  14879. * Unless required by applicable law or agreed to in writing,
  14880. * software distributed under the License is distributed on an
  14881. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14882. * KIND, either express or implied. See the License for the
  14883. * specific language governing permissions and limitations
  14884. * under the License.
  14885. */
  14886. var langZH = {
  14887. time: {
  14888. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  14889. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  14890. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  14891. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  14892. },
  14893. legend: {
  14894. selector: {
  14895. all: '全选',
  14896. inverse: '反选'
  14897. }
  14898. },
  14899. toolbox: {
  14900. brush: {
  14901. title: {
  14902. rect: '矩形选择',
  14903. polygon: '圈选',
  14904. lineX: '横向选择',
  14905. lineY: '纵向选择',
  14906. keep: '保持选择',
  14907. clear: '清除选择'
  14908. }
  14909. },
  14910. dataView: {
  14911. title: '数据视图',
  14912. lang: ['数据视图', '关闭', '刷新']
  14913. },
  14914. dataZoom: {
  14915. title: {
  14916. zoom: '区域缩放',
  14917. back: '区域缩放还原'
  14918. }
  14919. },
  14920. magicType: {
  14921. title: {
  14922. line: '切换为折线图',
  14923. bar: '切换为柱状图',
  14924. stack: '切换为堆叠',
  14925. tiled: '切换为平铺'
  14926. }
  14927. },
  14928. restore: {
  14929. title: '还原'
  14930. },
  14931. saveAsImage: {
  14932. title: '保存为图片',
  14933. lang: ['右键另存为图片']
  14934. }
  14935. },
  14936. series: {
  14937. typeNames: {
  14938. pie: '饼图',
  14939. bar: '柱状图',
  14940. line: '折线图',
  14941. scatter: '散点图',
  14942. effectScatter: '涟漪散点图',
  14943. radar: '雷达图',
  14944. tree: '树图',
  14945. treemap: '矩形树图',
  14946. boxplot: '箱型图',
  14947. candlestick: 'K线图',
  14948. k: 'K线图',
  14949. heatmap: '热力图',
  14950. map: '地图',
  14951. parallel: '平行坐标图',
  14952. lines: '线图',
  14953. graph: '关系图',
  14954. sankey: '桑基图',
  14955. funnel: '漏斗图',
  14956. gauge: '仪表盘图',
  14957. pictorialBar: '象形柱图',
  14958. themeRiver: '主题河流图',
  14959. sunburst: '旭日图'
  14960. }
  14961. },
  14962. aria: {
  14963. general: {
  14964. withTitle: '这是一个关于“{title}”的图表。',
  14965. withoutTitle: '这是一个图表,'
  14966. },
  14967. series: {
  14968. single: {
  14969. prefix: '',
  14970. withName: '图表类型是{seriesType},表示{seriesName}。',
  14971. withoutName: '图表类型是{seriesType}。'
  14972. },
  14973. multiple: {
  14974. prefix: '它由{seriesCount}个图表系列组成。',
  14975. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  14976. withoutName: '第{seriesId}个系列是一个{seriesType},',
  14977. separator: {
  14978. middle: ';',
  14979. end: '。'
  14980. }
  14981. }
  14982. },
  14983. data: {
  14984. allData: '其数据是——',
  14985. partialData: '其中,前{displayCnt}项是——',
  14986. withName: '{name}的数据是{value}',
  14987. withoutName: '{value}',
  14988. separator: {
  14989. middle: ',',
  14990. end: ''
  14991. }
  14992. }
  14993. }
  14994. };
  14995. var LOCALE_ZH = 'ZH';
  14996. var LOCALE_EN = 'EN';
  14997. var DEFAULT_LOCALE = LOCALE_EN;
  14998. var localeStorage = {};
  14999. var localeModels = {};
  15000. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15001. var langStr = (
  15002. /* eslint-disable-next-line */
  15003. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15004. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15005. }();
  15006. function registerLocale(locale, localeObj) {
  15007. locale = locale.toUpperCase();
  15008. localeModels[locale] = new Model(localeObj);
  15009. localeStorage[locale] = localeObj;
  15010. } // export function getLocale(locale: string) {
  15011. // return localeStorage[locale];
  15012. // }
  15013. function createLocaleObject(locale) {
  15014. if (isString(locale)) {
  15015. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15016. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15017. return clone(localeObj);
  15018. } else {
  15019. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15020. }
  15021. } else {
  15022. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15023. }
  15024. }
  15025. function getLocaleModel(lang) {
  15026. return localeModels[lang];
  15027. }
  15028. function getDefaultLocaleModel() {
  15029. return localeModels[DEFAULT_LOCALE];
  15030. } // Default locale
  15031. registerLocale(LOCALE_EN, langEN);
  15032. registerLocale(LOCALE_ZH, langZH);
  15033. var ONE_SECOND = 1000;
  15034. var ONE_MINUTE = ONE_SECOND * 60;
  15035. var ONE_HOUR = ONE_MINUTE * 60;
  15036. var ONE_DAY = ONE_HOUR * 24;
  15037. var ONE_YEAR = ONE_DAY * 365;
  15038. var defaultLeveledFormatter = {
  15039. year: '{yyyy}',
  15040. month: '{MMM}',
  15041. day: '{d}',
  15042. hour: '{HH}:{mm}',
  15043. minute: '{HH}:{mm}',
  15044. second: '{HH}:{mm}:{ss}',
  15045. millisecond: '{hh}:{mm}:{ss} {SSS}',
  15046. none: '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss} {SSS}'
  15047. };
  15048. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15049. var fullLeveledFormatter = {
  15050. year: '{yyyy}',
  15051. month: '{yyyy}-{MM}',
  15052. day: fullDayFormatter,
  15053. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15054. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15055. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15056. millisecond: defaultLeveledFormatter.none
  15057. };
  15058. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15059. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15060. function pad(str, len) {
  15061. str += '';
  15062. return '0000'.substr(0, len - str.length) + str;
  15063. }
  15064. function getPrimaryTimeUnit(timeUnit) {
  15065. switch (timeUnit) {
  15066. case 'half-year':
  15067. case 'quarter':
  15068. return 'month';
  15069. case 'week':
  15070. case 'half-week':
  15071. return 'day';
  15072. case 'half-day':
  15073. case 'quarter-day':
  15074. return 'hour';
  15075. default:
  15076. // year, minutes, second, milliseconds
  15077. return timeUnit;
  15078. }
  15079. }
  15080. function isPrimaryTimeUnit(timeUnit) {
  15081. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15082. }
  15083. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15084. switch (timeUnit) {
  15085. case 'year':
  15086. case 'month':
  15087. return 'day';
  15088. case 'millisecond':
  15089. return 'millisecond';
  15090. default:
  15091. // Also for day, hour, minute, second
  15092. return 'second';
  15093. }
  15094. }
  15095. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15096. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15097. time, template, isUTC, lang) {
  15098. var date = parseDate(time);
  15099. var y = date[fullYearGetterName(isUTC)]();
  15100. var M = date[monthGetterName(isUTC)]() + 1;
  15101. var q = Math.floor((M - 1) / 4) + 1;
  15102. var d = date[dateGetterName(isUTC)]();
  15103. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15104. var H = date[hoursGetterName(isUTC)]();
  15105. var h = (H - 1) % 12 + 1;
  15106. var m = date[minutesGetterName(isUTC)]();
  15107. var s = date[secondsGetterName(isUTC)]();
  15108. var S = date[millisecondsGetterName(isUTC)]();
  15109. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15110. var timeModel = localeModel.getModel('time');
  15111. var month = timeModel.get('month');
  15112. var monthAbbr = timeModel.get('monthAbbr');
  15113. var dayOfWeek = timeModel.get('dayOfWeek');
  15114. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15115. 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 + '');
  15116. }
  15117. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15118. var template = null;
  15119. if (typeof formatter === 'string') {
  15120. // Single formatter for all units at all levels
  15121. template = formatter;
  15122. } else if (typeof formatter === 'function') {
  15123. // Callback formatter
  15124. template = formatter(tick.value, idx, {
  15125. level: tick.level
  15126. });
  15127. } else {
  15128. var defaults$1 = extend({}, defaultLeveledFormatter);
  15129. if (tick.level > 0) {
  15130. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15131. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15132. }
  15133. }
  15134. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15135. : defaults(formatter, defaults$1) : defaults$1;
  15136. var unit = getUnitFromValue(tick.value, isUTC);
  15137. if (mergedFormatter[unit]) {
  15138. template = mergedFormatter[unit];
  15139. } else if (mergedFormatter.inherit) {
  15140. // Unit formatter is not defined and should inherit from bigger units
  15141. var targetId = timeUnits.indexOf(unit);
  15142. for (var i = targetId - 1; i >= 0; --i) {
  15143. if (mergedFormatter[unit]) {
  15144. template = mergedFormatter[unit];
  15145. break;
  15146. }
  15147. }
  15148. template = template || defaults$1.none;
  15149. }
  15150. if (isArray(template)) {
  15151. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15152. levelId = Math.min(levelId, template.length - 1);
  15153. template = template[levelId];
  15154. }
  15155. }
  15156. return format(new Date(tick.value), template, isUTC, lang);
  15157. }
  15158. function getUnitFromValue(value, isUTC) {
  15159. var date = parseDate(value);
  15160. var M = date[monthGetterName(isUTC)]() + 1;
  15161. var d = date[dateGetterName(isUTC)]();
  15162. var h = date[hoursGetterName(isUTC)]();
  15163. var m = date[minutesGetterName(isUTC)]();
  15164. var s = date[secondsGetterName(isUTC)]();
  15165. var S = date[millisecondsGetterName(isUTC)]();
  15166. var isSecond = S === 0;
  15167. var isMinute = isSecond && s === 0;
  15168. var isHour = isMinute && m === 0;
  15169. var isDay = isHour && h === 0;
  15170. var isMonth = isDay && d === 1;
  15171. var isYear = isMonth && M === 1;
  15172. if (isYear) {
  15173. return 'year';
  15174. } else if (isMonth) {
  15175. return 'month';
  15176. } else if (isDay) {
  15177. return 'day';
  15178. } else if (isHour) {
  15179. return 'hour';
  15180. } else if (isMinute) {
  15181. return 'minute';
  15182. } else if (isSecond) {
  15183. return 'second';
  15184. } else {
  15185. return 'millisecond';
  15186. }
  15187. }
  15188. function getUnitValue(value, unit, isUTC) {
  15189. var date = typeof value === 'number' ? parseDate(value) : value;
  15190. unit = unit || getUnitFromValue(value, isUTC);
  15191. switch (unit) {
  15192. case 'year':
  15193. return date[fullYearGetterName(isUTC)]();
  15194. case 'half-year':
  15195. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15196. case 'quarter':
  15197. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15198. case 'month':
  15199. return date[monthGetterName(isUTC)]();
  15200. case 'day':
  15201. return date[dateGetterName(isUTC)]();
  15202. case 'half-day':
  15203. return date[hoursGetterName(isUTC)]() / 24;
  15204. case 'hour':
  15205. return date[hoursGetterName(isUTC)]();
  15206. case 'minute':
  15207. return date[minutesGetterName(isUTC)]();
  15208. case 'second':
  15209. return date[secondsGetterName(isUTC)]();
  15210. case 'millisecond':
  15211. return date[millisecondsGetterName(isUTC)]();
  15212. }
  15213. }
  15214. function fullYearGetterName(isUTC) {
  15215. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15216. }
  15217. function monthGetterName(isUTC) {
  15218. return isUTC ? 'getUTCMonth' : 'getMonth';
  15219. }
  15220. function dateGetterName(isUTC) {
  15221. return isUTC ? 'getUTCDate' : 'getDate';
  15222. }
  15223. function hoursGetterName(isUTC) {
  15224. return isUTC ? 'getUTCHours' : 'getHours';
  15225. }
  15226. function minutesGetterName(isUTC) {
  15227. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15228. }
  15229. function secondsGetterName(isUTC) {
  15230. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15231. }
  15232. function millisecondsGetterName(isUTC) {
  15233. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15234. }
  15235. function fullYearSetterName(isUTC) {
  15236. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15237. }
  15238. function monthSetterName(isUTC) {
  15239. return isUTC ? 'setUTCMonth' : 'setMonth';
  15240. }
  15241. function dateSetterName(isUTC) {
  15242. return isUTC ? 'setUTCDate' : 'setDate';
  15243. }
  15244. function hoursSetterName(isUTC) {
  15245. return isUTC ? 'setUTCHours' : 'setHours';
  15246. }
  15247. function minutesSetterName(isUTC) {
  15248. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15249. }
  15250. function secondsSetterName(isUTC) {
  15251. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15252. }
  15253. function millisecondsSetterName(isUTC) {
  15254. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15255. }
  15256. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15257. deprecateLog('getTextRect is deprecated.');
  15258. var textEl = new ZRText({
  15259. style: {
  15260. text: text,
  15261. font: font,
  15262. align: align,
  15263. verticalAlign: verticalAlign,
  15264. padding: padding,
  15265. rich: rich,
  15266. overflow: truncate ? 'truncate' : null,
  15267. lineHeight: lineHeight
  15268. }
  15269. });
  15270. return textEl.getBoundingRect();
  15271. }
  15272. /**
  15273. * Add a comma each three digit.
  15274. */
  15275. function addCommas(x) {
  15276. if (!isNumeric(x)) {
  15277. return isString(x) ? x : '-';
  15278. }
  15279. var parts = (x + '').split('.');
  15280. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15281. }
  15282. function toCamelCase(str, upperCaseFirst) {
  15283. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15284. return group1.toUpperCase();
  15285. });
  15286. if (upperCaseFirst && str) {
  15287. str = str.charAt(0).toUpperCase() + str.slice(1);
  15288. }
  15289. return str;
  15290. }
  15291. var normalizeCssArray$1 = normalizeCssArray;
  15292. var replaceReg = /([&<>"'])/g;
  15293. var replaceMap = {
  15294. '&': '&amp;',
  15295. '<': '&lt;',
  15296. '>': '&gt;',
  15297. '"': '&quot;',
  15298. '\'': '&#39;'
  15299. };
  15300. function encodeHTML(source) {
  15301. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  15302. return replaceMap[c];
  15303. });
  15304. }
  15305. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15306. var wrapVar = function (varName, seriesIdx) {
  15307. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15308. };
  15309. /**
  15310. * Template formatter
  15311. * @param {Array.<Object>|Object} paramsList
  15312. */
  15313. function formatTpl(tpl, paramsList, encode) {
  15314. if (!isArray(paramsList)) {
  15315. paramsList = [paramsList];
  15316. }
  15317. var seriesLen = paramsList.length;
  15318. if (!seriesLen) {
  15319. return '';
  15320. }
  15321. var $vars = paramsList[0].$vars || [];
  15322. for (var i = 0; i < $vars.length; i++) {
  15323. var alias = TPL_VAR_ALIAS[i];
  15324. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15325. }
  15326. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15327. for (var k = 0; k < $vars.length; k++) {
  15328. var val = paramsList[seriesIdx][$vars[k]];
  15329. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  15330. }
  15331. }
  15332. return tpl;
  15333. }
  15334. function getTooltipMarker(inOpt, extraCssText) {
  15335. var opt = isString(inOpt) ? {
  15336. color: inOpt,
  15337. extraCssText: extraCssText
  15338. } : inOpt || {};
  15339. var color = opt.color;
  15340. var type = opt.type;
  15341. extraCssText = opt.extraCssText;
  15342. var renderMode = opt.renderMode || 'html';
  15343. if (!color) {
  15344. return '';
  15345. }
  15346. if (renderMode === 'html') {
  15347. 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
  15348. + 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>';
  15349. } else {
  15350. // Should better not to auto generate style name by auto-increment number here.
  15351. // Because this util is usually called in tooltip formatter, which is probably
  15352. // called repeatly when mouse move and the auto-increment number increases fast.
  15353. // Users can make their own style name by theirselves, make it unique and readable.
  15354. var markerId = opt.markerId || 'markerX';
  15355. return {
  15356. renderMode: renderMode,
  15357. content: '{' + markerId + '|} ',
  15358. style: type === 'subItem' ? {
  15359. width: 4,
  15360. height: 4,
  15361. borderRadius: 2,
  15362. backgroundColor: color
  15363. } : {
  15364. width: 10,
  15365. height: 10,
  15366. borderRadius: 5,
  15367. backgroundColor: color
  15368. }
  15369. };
  15370. }
  15371. }
  15372. /**
  15373. * @deprecated Use `time/format` instead.
  15374. * ISO Date format
  15375. * @param {string} tpl
  15376. * @param {number} value
  15377. * @param {boolean} [isUTC=false] Default in local time.
  15378. * see `module:echarts/scale/Time`
  15379. * and `module:echarts/util/number#parseDate`.
  15380. * @inner
  15381. */
  15382. function formatTime(tpl, value, isUTC) {
  15383. if ("development" !== 'production') {
  15384. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  15385. }
  15386. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  15387. tpl = 'MM-dd\nyyyy';
  15388. }
  15389. var date = parseDate(value);
  15390. var utc = isUTC ? 'UTC' : '';
  15391. var y = date['get' + utc + 'FullYear']();
  15392. var M = date['get' + utc + 'Month']() + 1;
  15393. var d = date['get' + utc + 'Date']();
  15394. var h = date['get' + utc + 'Hours']();
  15395. var m = date['get' + utc + 'Minutes']();
  15396. var s = date['get' + utc + 'Seconds']();
  15397. var S = date['get' + utc + 'Milliseconds']();
  15398. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  15399. return tpl;
  15400. }
  15401. /**
  15402. * Capital first
  15403. * @param {string} str
  15404. * @return {string}
  15405. */
  15406. function capitalFirst(str) {
  15407. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15408. }
  15409. /**
  15410. * @return Never be null/undefined.
  15411. */
  15412. function convertToColorString(color, defaultColor) {
  15413. defaultColor = defaultColor || 'transparent';
  15414. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  15415. }
  15416. var each$1 = each;
  15417. /**
  15418. * @public
  15419. */
  15420. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  15421. /**
  15422. * @public
  15423. */
  15424. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  15425. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15426. var x = 0;
  15427. var y = 0;
  15428. if (maxWidth == null) {
  15429. maxWidth = Infinity;
  15430. }
  15431. if (maxHeight == null) {
  15432. maxHeight = Infinity;
  15433. }
  15434. var currentLineMaxSize = 0;
  15435. group.eachChild(function (child, idx) {
  15436. var rect = child.getBoundingRect();
  15437. var nextChild = group.childAt(idx + 1);
  15438. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15439. var nextX;
  15440. var nextY;
  15441. if (orient === 'horizontal') {
  15442. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  15443. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  15444. // FIXME compare before adding gap?
  15445. if (nextX > maxWidth || child.newline) {
  15446. x = 0;
  15447. nextX = moveX;
  15448. y += currentLineMaxSize + gap;
  15449. currentLineMaxSize = rect.height;
  15450. } else {
  15451. // FIXME: consider rect.y is not `0`?
  15452. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15453. }
  15454. } else {
  15455. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  15456. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  15457. if (nextY > maxHeight || child.newline) {
  15458. x += currentLineMaxSize + gap;
  15459. y = 0;
  15460. nextY = moveY;
  15461. currentLineMaxSize = rect.width;
  15462. } else {
  15463. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15464. }
  15465. }
  15466. if (child.newline) {
  15467. return;
  15468. }
  15469. child.x = x;
  15470. child.y = y;
  15471. child.markRedraw();
  15472. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  15473. });
  15474. }
  15475. /**
  15476. * VBox layouting
  15477. * @param {module:zrender/graphic/Group} group
  15478. * @param {number} gap
  15479. * @param {number} [width=Infinity]
  15480. * @param {number} [height=Infinity]
  15481. */
  15482. var vbox = curry(boxLayout, 'vertical');
  15483. /**
  15484. * HBox layouting
  15485. * @param {module:zrender/graphic/Group} group
  15486. * @param {number} gap
  15487. * @param {number} [width=Infinity]
  15488. * @param {number} [height=Infinity]
  15489. */
  15490. var hbox = curry(boxLayout, 'horizontal');
  15491. /**
  15492. * Parse position info.
  15493. */
  15494. function getLayoutRect(positionInfo, containerRect, margin) {
  15495. margin = normalizeCssArray$1(margin || 0);
  15496. var containerWidth = containerRect.width;
  15497. var containerHeight = containerRect.height;
  15498. var left = parsePercent$1(positionInfo.left, containerWidth);
  15499. var top = parsePercent$1(positionInfo.top, containerHeight);
  15500. var right = parsePercent$1(positionInfo.right, containerWidth);
  15501. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15502. var width = parsePercent$1(positionInfo.width, containerWidth);
  15503. var height = parsePercent$1(positionInfo.height, containerHeight);
  15504. var verticalMargin = margin[2] + margin[0];
  15505. var horizontalMargin = margin[1] + margin[3];
  15506. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  15507. if (isNaN(width)) {
  15508. width = containerWidth - right - horizontalMargin - left;
  15509. }
  15510. if (isNaN(height)) {
  15511. height = containerHeight - bottom - verticalMargin - top;
  15512. }
  15513. if (aspect != null) {
  15514. // If width and height are not given
  15515. // 1. Graph should not exceeds the container
  15516. // 2. Aspect must be keeped
  15517. // 3. Graph should take the space as more as possible
  15518. // FIXME
  15519. // Margin is not considered, because there is no case that both
  15520. // using margin and aspect so far.
  15521. if (isNaN(width) && isNaN(height)) {
  15522. if (aspect > containerWidth / containerHeight) {
  15523. width = containerWidth * 0.8;
  15524. } else {
  15525. height = containerHeight * 0.8;
  15526. }
  15527. } // Calculate width or height with given aspect
  15528. if (isNaN(width)) {
  15529. width = aspect * height;
  15530. }
  15531. if (isNaN(height)) {
  15532. height = width / aspect;
  15533. }
  15534. } // If left is not specified, calculate left from right and width
  15535. if (isNaN(left)) {
  15536. left = containerWidth - right - width - horizontalMargin;
  15537. }
  15538. if (isNaN(top)) {
  15539. top = containerHeight - bottom - height - verticalMargin;
  15540. } // Align left and top
  15541. switch (positionInfo.left || positionInfo.right) {
  15542. case 'center':
  15543. left = containerWidth / 2 - width / 2 - margin[3];
  15544. break;
  15545. case 'right':
  15546. left = containerWidth - width - horizontalMargin;
  15547. break;
  15548. }
  15549. switch (positionInfo.top || positionInfo.bottom) {
  15550. case 'middle':
  15551. case 'center':
  15552. top = containerHeight / 2 - height / 2 - margin[0];
  15553. break;
  15554. case 'bottom':
  15555. top = containerHeight - height - verticalMargin;
  15556. break;
  15557. } // If something is wrong and left, top, width, height are calculated as NaN
  15558. left = left || 0;
  15559. top = top || 0;
  15560. if (isNaN(width)) {
  15561. // Width may be NaN if only one value is given except width
  15562. width = containerWidth - horizontalMargin - left - (right || 0);
  15563. }
  15564. if (isNaN(height)) {
  15565. // Height may be NaN if only one value is given except height
  15566. height = containerHeight - verticalMargin - top - (bottom || 0);
  15567. }
  15568. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15569. rect.margin = margin;
  15570. return rect;
  15571. }
  15572. function fetchLayoutMode(ins) {
  15573. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  15574. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  15575. type: layoutMode
  15576. } : null;
  15577. }
  15578. /**
  15579. * Consider Case:
  15580. * When default option has {left: 0, width: 100}, and we set {right: 0}
  15581. * through setOption or media query, using normal zrUtil.merge will cause
  15582. * {right: 0} does not take effect.
  15583. *
  15584. * @example
  15585. * ComponentModel.extend({
  15586. * init: function () {
  15587. * ...
  15588. * let inputPositionParams = layout.getLayoutParams(option);
  15589. * this.mergeOption(inputPositionParams);
  15590. * },
  15591. * mergeOption: function (newOption) {
  15592. * newOption && zrUtil.merge(thisOption, newOption, true);
  15593. * layout.mergeLayoutParam(thisOption, newOption);
  15594. * }
  15595. * });
  15596. *
  15597. * @param targetOption
  15598. * @param newOption
  15599. * @param opt
  15600. */
  15601. function mergeLayoutParam(targetOption, newOption, opt) {
  15602. var ignoreSize = opt && opt.ignoreSize;
  15603. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15604. var hResult = merge(HV_NAMES[0], 0);
  15605. var vResult = merge(HV_NAMES[1], 1);
  15606. copy(HV_NAMES[0], targetOption, hResult);
  15607. copy(HV_NAMES[1], targetOption, vResult);
  15608. function merge(names, hvIdx) {
  15609. var newParams = {};
  15610. var newValueCount = 0;
  15611. var merged = {};
  15612. var mergedValueCount = 0;
  15613. var enoughParamNumber = 2;
  15614. each$1(names, function (name) {
  15615. merged[name] = targetOption[name];
  15616. });
  15617. each$1(names, function (name) {
  15618. // Consider case: newOption.width is null, which is
  15619. // set by user for removing width setting.
  15620. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15621. hasValue(newParams, name) && newValueCount++;
  15622. hasValue(merged, name) && mergedValueCount++;
  15623. });
  15624. if (ignoreSize[hvIdx]) {
  15625. // Only one of left/right is premitted to exist.
  15626. if (hasValue(newOption, names[1])) {
  15627. merged[names[2]] = null;
  15628. } else if (hasValue(newOption, names[2])) {
  15629. merged[names[1]] = null;
  15630. }
  15631. return merged;
  15632. } // Case: newOption: {width: ..., right: ...},
  15633. // or targetOption: {right: ...} and newOption: {width: ...},
  15634. // There is no conflict when merged only has params count
  15635. // little than enoughParamNumber.
  15636. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15637. return merged;
  15638. } // Case: newOption: {width: ..., right: ...},
  15639. // Than we can make sure user only want those two, and ignore
  15640. // all origin params in targetOption.
  15641. else if (newValueCount >= enoughParamNumber) {
  15642. return newParams;
  15643. } else {
  15644. // Chose another param from targetOption by priority.
  15645. for (var i = 0; i < names.length; i++) {
  15646. var name_1 = names[i];
  15647. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  15648. newParams[name_1] = targetOption[name_1];
  15649. break;
  15650. }
  15651. }
  15652. return newParams;
  15653. }
  15654. }
  15655. function hasProp(obj, name) {
  15656. return obj.hasOwnProperty(name);
  15657. }
  15658. function hasValue(obj, name) {
  15659. return obj[name] != null && obj[name] !== 'auto';
  15660. }
  15661. function copy(names, target, source) {
  15662. each$1(names, function (name) {
  15663. target[name] = source[name];
  15664. });
  15665. }
  15666. }
  15667. /**
  15668. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15669. */
  15670. function getLayoutParams(source) {
  15671. return copyLayoutParams({}, source);
  15672. }
  15673. /**
  15674. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15675. * @param {Object} source
  15676. * @return {Object} Result contains those props.
  15677. */
  15678. function copyLayoutParams(target, source) {
  15679. source && target && each$1(LOCATION_PARAMS, function (name) {
  15680. source.hasOwnProperty(name) && (target[name] = source[name]);
  15681. });
  15682. return target;
  15683. }
  15684. var inner = makeInner();
  15685. var ComponentModel =
  15686. /** @class */
  15687. function (_super) {
  15688. __extends(ComponentModel, _super);
  15689. function ComponentModel(option, parentModel, ecModel) {
  15690. var _this = _super.call(this, option, parentModel, ecModel) || this;
  15691. _this.uid = getUID('ec_cpt_model');
  15692. return _this;
  15693. }
  15694. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  15695. this.mergeDefaultAndTheme(option, ecModel);
  15696. };
  15697. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  15698. var layoutMode = fetchLayoutMode(this);
  15699. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  15700. var themeModel = ecModel.getTheme();
  15701. merge(option, themeModel.get(this.mainType));
  15702. merge(option, this.getDefaultOption());
  15703. if (layoutMode) {
  15704. mergeLayoutParam(option, inputPositionParams, layoutMode);
  15705. }
  15706. };
  15707. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  15708. merge(this.option, option, true);
  15709. var layoutMode = fetchLayoutMode(this);
  15710. if (layoutMode) {
  15711. mergeLayoutParam(this.option, option, layoutMode);
  15712. }
  15713. };
  15714. /**
  15715. * Called immediately after `init` or `mergeOption` of this instance called.
  15716. */
  15717. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  15718. /**
  15719. * [How to declare defaultOption]:
  15720. *
  15721. * (A) If using class declaration in typescript (since echarts 5):
  15722. * ```ts
  15723. * import {ComponentOption} from '../model/option';
  15724. * export interface XxxOption extends ComponentOption {
  15725. * aaa: number
  15726. * }
  15727. * export class XxxModel extends Component {
  15728. * static type = 'xxx';
  15729. * static defaultOption: XxxOption = {
  15730. * aaa: 123
  15731. * }
  15732. * }
  15733. * Component.registerClass(XxxModel);
  15734. * ```
  15735. * ```ts
  15736. * import {inheritDefaultOption} from '../util/component';
  15737. * import {XxxModel, XxxOption} from './XxxModel';
  15738. * export interface XxxSubOption extends XxxOption {
  15739. * bbb: number
  15740. * }
  15741. * class XxxSubModel extends XxxModel {
  15742. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  15743. * bbb: 456
  15744. * })
  15745. * fn() {
  15746. * let opt = this.getDefaultOption();
  15747. * // opt is {aaa: 123, bbb: 456}
  15748. * }
  15749. * }
  15750. * ```
  15751. *
  15752. * (B) If using class extend (previous approach in echarts 3 & 4):
  15753. * ```js
  15754. * let XxxComponent = Component.extend({
  15755. * defaultOption: {
  15756. * xx: 123
  15757. * }
  15758. * })
  15759. * ```
  15760. * ```js
  15761. * let XxxSubComponent = XxxComponent.extend({
  15762. * defaultOption: {
  15763. * yy: 456
  15764. * },
  15765. * fn: function () {
  15766. * let opt = this.getDefaultOption();
  15767. * // opt is {xx: 123, yy: 456}
  15768. * }
  15769. * })
  15770. * ```
  15771. */
  15772. ComponentModel.prototype.getDefaultOption = function () {
  15773. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  15774. // in legacy env and auto merge defaultOption. So if using class
  15775. // declaration, defaultOption should be merged manually.
  15776. if (!isExtendedClass(ctor)) {
  15777. // When using ts class, defaultOption must be declared as static.
  15778. return ctor.defaultOption;
  15779. } // FIXME: remove this approach?
  15780. var fields = inner(this);
  15781. if (!fields.defaultOption) {
  15782. var optList = [];
  15783. var clz = ctor;
  15784. while (clz) {
  15785. var opt = clz.prototype.defaultOption;
  15786. opt && optList.push(opt);
  15787. clz = clz.superClass;
  15788. }
  15789. var defaultOption = {};
  15790. for (var i = optList.length - 1; i >= 0; i--) {
  15791. defaultOption = merge(defaultOption, optList[i], true);
  15792. }
  15793. fields.defaultOption = defaultOption;
  15794. }
  15795. return fields.defaultOption;
  15796. };
  15797. /**
  15798. * Notice: always force to input param `useDefault` in case that forget to consider it.
  15799. * The same behavior as `modelUtil.parseFinder`.
  15800. *
  15801. * @param useDefault In many cases like series refer axis and axis refer grid,
  15802. * If axis index / axis id not specified, use the first target as default.
  15803. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  15804. */
  15805. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  15806. var indexKey = mainType + 'Index';
  15807. var idKey = mainType + 'Id';
  15808. return queryReferringComponents(this.ecModel, mainType, {
  15809. index: this.get(indexKey, true),
  15810. id: this.get(idKey, true)
  15811. }, opt);
  15812. };
  15813. ComponentModel.prototype.getBoxLayoutParams = function () {
  15814. // Consider itself having box layout configs.
  15815. var boxLayoutModel = this;
  15816. return {
  15817. left: boxLayoutModel.get('left'),
  15818. top: boxLayoutModel.get('top'),
  15819. right: boxLayoutModel.get('right'),
  15820. bottom: boxLayoutModel.get('bottom'),
  15821. width: boxLayoutModel.get('width'),
  15822. height: boxLayoutModel.get('height')
  15823. };
  15824. };
  15825. ComponentModel.protoInitialize = function () {
  15826. var proto = ComponentModel.prototype;
  15827. proto.type = 'component';
  15828. proto.id = '';
  15829. proto.name = '';
  15830. proto.mainType = '';
  15831. proto.subType = '';
  15832. proto.componentIndex = 0;
  15833. }();
  15834. return ComponentModel;
  15835. }(Model);
  15836. mountExtend(ComponentModel, Model);
  15837. enableClassManagement(ComponentModel);
  15838. enableSubTypeDefaulter(ComponentModel);
  15839. enableTopologicalTravel(ComponentModel, getDependencies);
  15840. function getDependencies(componentType) {
  15841. var deps = [];
  15842. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  15843. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  15844. }); // Ensure main type.
  15845. deps = map(deps, function (type) {
  15846. return parseClassType(type).main;
  15847. }); // Hack dataset for convenience.
  15848. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  15849. deps.unshift('dataset');
  15850. }
  15851. return deps;
  15852. }
  15853. /*
  15854. * Licensed to the Apache Software Foundation (ASF) under one
  15855. * or more contributor license agreements. See the NOTICE file
  15856. * distributed with this work for additional information
  15857. * regarding copyright ownership. The ASF licenses this file
  15858. * to you under the Apache License, Version 2.0 (the
  15859. * "License"); you may not use this file except in compliance
  15860. * with the License. You may obtain a copy of the License at
  15861. *
  15862. * http://www.apache.org/licenses/LICENSE-2.0
  15863. *
  15864. * Unless required by applicable law or agreed to in writing,
  15865. * software distributed under the License is distributed on an
  15866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15867. * KIND, either express or implied. See the License for the
  15868. * specific language governing permissions and limitations
  15869. * under the License.
  15870. */
  15871. /**
  15872. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15873. */
  15874. /*
  15875. * Licensed to the Apache Software Foundation (ASF) under one
  15876. * or more contributor license agreements. See the NOTICE file
  15877. * distributed with this work for additional information
  15878. * regarding copyright ownership. The ASF licenses this file
  15879. * to you under the Apache License, Version 2.0 (the
  15880. * "License"); you may not use this file except in compliance
  15881. * with the License. You may obtain a copy of the License at
  15882. *
  15883. * http://www.apache.org/licenses/LICENSE-2.0
  15884. *
  15885. * Unless required by applicable law or agreed to in writing,
  15886. * software distributed under the License is distributed on an
  15887. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15888. * KIND, either express or implied. See the License for the
  15889. * specific language governing permissions and limitations
  15890. * under the License.
  15891. */
  15892. var platform = ''; // Navigator not exists in node
  15893. if (typeof navigator !== 'undefined') {
  15894. /* global navigator */
  15895. platform = navigator.platform || '';
  15896. }
  15897. var decalColor = 'rgba(0, 0, 0, 0.2)';
  15898. var globalDefault = {
  15899. darkMode: 'auto',
  15900. // backgroundColor: 'rgba(0,0,0,0)',
  15901. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  15902. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  15903. // Light colors:
  15904. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  15905. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  15906. // Dark colors:
  15907. // color: [
  15908. // '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  15909. // '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  15910. // ],
  15911. color: [// '#51689b', '#ce5c5c', '#fbc357', '#8fbf8f', '#659d84', '#fb8e6a', '#c77288', '#786090', '#91c4c5', '#6890ba'
  15912. '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  15913. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  15914. aria: {
  15915. decal: {
  15916. decals: [{
  15917. color: decalColor,
  15918. dashArrayX: [1, 0],
  15919. dashArrayY: [2, 5],
  15920. symbolSize: 1,
  15921. rotation: Math.PI / 6
  15922. }, {
  15923. color: decalColor,
  15924. symbol: 'circle',
  15925. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  15926. dashArrayY: [6, 0],
  15927. symbolSize: 0.8
  15928. }, {
  15929. color: decalColor,
  15930. dashArrayX: [1, 0],
  15931. dashArrayY: [4, 3],
  15932. rotation: -Math.PI / 4
  15933. }, {
  15934. color: decalColor,
  15935. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  15936. dashArrayY: [6, 0]
  15937. }, {
  15938. color: decalColor,
  15939. dashArrayX: [[1, 0], [1, 6]],
  15940. dashArrayY: [1, 0, 6, 0],
  15941. rotation: Math.PI / 4
  15942. }, {
  15943. color: decalColor,
  15944. symbol: 'triangle',
  15945. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  15946. dashArrayY: [7, 2],
  15947. symbolSize: 0.75
  15948. }]
  15949. }
  15950. },
  15951. // If xAxis and yAxis declared, grid is created by default.
  15952. // grid: {},
  15953. textStyle: {
  15954. // color: '#000',
  15955. // decoration: 'none',
  15956. // PENDING
  15957. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  15958. // fontFamily: 'Arial, Verdana, sans-serif',
  15959. fontSize: 12,
  15960. fontStyle: 'normal',
  15961. fontWeight: 'normal'
  15962. },
  15963. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  15964. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  15965. // Default is source-over
  15966. blendMode: null,
  15967. stateAnimation: {
  15968. duration: 300,
  15969. easing: 'cubicOut'
  15970. },
  15971. animation: 'auto',
  15972. animationDuration: 1000,
  15973. animationDurationUpdate: 500,
  15974. animationEasing: 'cubicInOut',
  15975. animationEasingUpdate: 'cubicInOut',
  15976. animationThreshold: 2000,
  15977. // Configuration for progressive/incremental rendering
  15978. progressiveThreshold: 3000,
  15979. progressive: 400,
  15980. // Threshold of if use single hover layer to optimize.
  15981. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  15982. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  15983. // which is unexpected.
  15984. // see example <echarts/test/heatmap-large.html>.
  15985. hoverLayerThreshold: 3000,
  15986. // See: module:echarts/scale/Time
  15987. useUTC: false
  15988. };
  15989. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'seriesName']);
  15990. var SOURCE_FORMAT_ORIGINAL = 'original';
  15991. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  15992. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  15993. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  15994. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  15995. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  15996. var SERIES_LAYOUT_BY_COLUMN = 'column';
  15997. var SERIES_LAYOUT_BY_ROW = 'row';
  15998. var BE_ORDINAL = {
  15999. Must: 1,
  16000. Might: 2,
  16001. Not: 3 // Other cases
  16002. };
  16003. var innerGlobalModel = makeInner();
  16004. /**
  16005. * MUST be called before mergeOption of all series.
  16006. */
  16007. function resetSourceDefaulter(ecModel) {
  16008. // `datasetMap` is used to make default encode.
  16009. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16010. }
  16011. /**
  16012. * [The strategy of the arrengment of data dimensions for dataset]:
  16013. * "value way": all axes are non-category axes. So series one by one take
  16014. * several (the number is coordSysDims.length) dimensions from dataset.
  16015. * The result of data arrengment of data dimensions like:
  16016. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16017. * "category way": at least one axis is category axis. So the the first data
  16018. * dimension is always mapped to the first category axis and shared by
  16019. * all of the series. The other data dimensions are taken by series like
  16020. * "value way" does.
  16021. * The result of data arrengment of data dimensions like:
  16022. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16023. *
  16024. * @return encode Never be `null/undefined`.
  16025. */
  16026. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16027. var encode = {};
  16028. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16029. if (!datasetModel || !coordDimensions) {
  16030. return encode;
  16031. }
  16032. var encodeItemName = [];
  16033. var encodeSeriesName = [];
  16034. var ecModel = seriesModel.ecModel;
  16035. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16036. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16037. var baseCategoryDimIndex;
  16038. var categoryWayValueDimStart;
  16039. coordDimensions = coordDimensions.slice();
  16040. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16041. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16042. name: coordDimInfoLoose
  16043. };
  16044. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16045. baseCategoryDimIndex = coordDimIdx;
  16046. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16047. }
  16048. encode[coordDimInfo.name] = [];
  16049. });
  16050. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16051. categoryWayDim: categoryWayValueDimStart,
  16052. valueWayDim: 0
  16053. }); // TODO
  16054. // Auto detect first time axis and do arrangement.
  16055. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16056. var coordDimName = coordDimInfo.name;
  16057. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  16058. if (baseCategoryDimIndex == null) {
  16059. var start = datasetRecord.valueWayDim;
  16060. pushDim(encode[coordDimName], start, count);
  16061. pushDim(encodeSeriesName, start, count);
  16062. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  16063. // especially when encode x y specified.
  16064. // consider: when mutiple series share one dimension
  16065. // category axis, series name should better use
  16066. // the other dimsion name. On the other hand, use
  16067. // both dimensions name.
  16068. } // In category way, the first category axis.
  16069. else if (baseCategoryDimIndex === coordDimIdx) {
  16070. pushDim(encode[coordDimName], 0, count);
  16071. pushDim(encodeItemName, 0, count);
  16072. } // In category way, the other axis.
  16073. else {
  16074. var start = datasetRecord.categoryWayDim;
  16075. pushDim(encode[coordDimName], start, count);
  16076. pushDim(encodeSeriesName, start, count);
  16077. datasetRecord.categoryWayDim += count;
  16078. }
  16079. });
  16080. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16081. for (var i = 0; i < idxCount; i++) {
  16082. dimIdxArr.push(idxFrom + i);
  16083. }
  16084. }
  16085. function getDataDimCountOnCoordDim(coordDimInfo) {
  16086. var dimsDef = coordDimInfo.dimsDef;
  16087. return dimsDef ? dimsDef.length : 1;
  16088. }
  16089. encodeItemName.length && (encode.itemName = encodeItemName);
  16090. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16091. return encode;
  16092. }
  16093. /**
  16094. * Work for data like [{name: ..., value: ...}, ...].
  16095. *
  16096. * @return encode Never be `null/undefined`.
  16097. */
  16098. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16099. var encode = {};
  16100. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16101. if (!datasetModel) {
  16102. return encode;
  16103. }
  16104. var sourceFormat = source.sourceFormat;
  16105. var dimensionsDefine = source.dimensionsDefine;
  16106. var potentialNameDimIndex;
  16107. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16108. each(dimensionsDefine, function (dim, idx) {
  16109. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16110. potentialNameDimIndex = idx;
  16111. }
  16112. });
  16113. }
  16114. var idxResult = function () {
  16115. var idxRes0 = {};
  16116. var idxRes1 = {};
  16117. var guessRecords = []; // 5 is an experience value.
  16118. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16119. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16120. guessRecords.push(guessResult);
  16121. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16122. // and then find a name dim with the priority:
  16123. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16124. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16125. idxRes0.v = i;
  16126. }
  16127. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16128. idxRes0.n = i;
  16129. }
  16130. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16131. return idxRes0;
  16132. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16133. // find the first BE_ORDINAL.Might as the value dim,
  16134. // and then find a name dim with the priority:
  16135. // "other dim" > "the value dim itself".
  16136. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16137. // treated as number.
  16138. if (!isPureNumber) {
  16139. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16140. idxRes1.v = i;
  16141. }
  16142. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16143. idxRes1.n = i;
  16144. }
  16145. }
  16146. }
  16147. function fulfilled(idxResult) {
  16148. return idxResult.v != null && idxResult.n != null;
  16149. }
  16150. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16151. }();
  16152. if (idxResult) {
  16153. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  16154. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  16155. // So we dont set encodeLabel here.
  16156. encode.itemName = [nameDimIndex];
  16157. encode.seriesName = [nameDimIndex];
  16158. }
  16159. return encode;
  16160. }
  16161. /**
  16162. * @return If return null/undefined, indicate that should not use datasetModel.
  16163. */
  16164. function querySeriesUpstreamDatasetModel(seriesModel) {
  16165. // Caution: consider the scenario:
  16166. // A dataset is declared and a series is not expected to use the dataset,
  16167. // and at the beginning `setOption({series: { noData })` (just prepare other
  16168. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16169. // the user should set an empty array to avoid that dataset is used by default.
  16170. var thisData = seriesModel.get('data', true);
  16171. if (!thisData) {
  16172. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16173. index: seriesModel.get('datasetIndex', true),
  16174. id: seriesModel.get('datasetId', true)
  16175. }, SINGLE_REFERRING).models[0];
  16176. }
  16177. }
  16178. /**
  16179. * @return Always return an array event empty.
  16180. */
  16181. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16182. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  16183. // Otherwise, no reference.
  16184. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16185. return [];
  16186. }
  16187. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16188. index: datasetModel.get('fromDatasetIndex', true),
  16189. id: datasetModel.get('fromDatasetId', true)
  16190. }, SINGLE_REFERRING).models;
  16191. }
  16192. /**
  16193. * The rule should not be complex, otherwise user might not
  16194. * be able to known where the data is wrong.
  16195. * The code is ugly, but how to make it neat?
  16196. */
  16197. function guessOrdinal(source, dimIndex) {
  16198. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  16199. } // dimIndex may be overflow source data.
  16200. // return {BE_ORDINAL}
  16201. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  16202. var result; // Experience value.
  16203. var maxLoop = 5;
  16204. if (isTypedArray(data)) {
  16205. return BE_ORDINAL.Not;
  16206. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16207. // always exists in source.
  16208. var dimName;
  16209. var dimType;
  16210. if (dimensionsDefine) {
  16211. var dimDefItem = dimensionsDefine[dimIndex];
  16212. if (isObject(dimDefItem)) {
  16213. dimName = dimDefItem.name;
  16214. dimType = dimDefItem.type;
  16215. } else if (isString(dimDefItem)) {
  16216. dimName = dimDefItem;
  16217. }
  16218. }
  16219. if (dimType != null) {
  16220. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  16221. }
  16222. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16223. var dataArrayRows = data;
  16224. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16225. var sample = dataArrayRows[dimIndex];
  16226. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16227. if ((result = detectValue(sample[startIndex + i])) != null) {
  16228. return result;
  16229. }
  16230. }
  16231. } else {
  16232. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  16233. var row = dataArrayRows[startIndex + i];
  16234. if (row && (result = detectValue(row[dimIndex])) != null) {
  16235. return result;
  16236. }
  16237. }
  16238. }
  16239. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16240. var dataObjectRows = data;
  16241. if (!dimName) {
  16242. return BE_ORDINAL.Not;
  16243. }
  16244. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  16245. var item = dataObjectRows[i];
  16246. if (item && (result = detectValue(item[dimName])) != null) {
  16247. return result;
  16248. }
  16249. }
  16250. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16251. var dataKeyedColumns = data;
  16252. if (!dimName) {
  16253. return BE_ORDINAL.Not;
  16254. }
  16255. var sample = dataKeyedColumns[dimName];
  16256. if (!sample || isTypedArray(sample)) {
  16257. return BE_ORDINAL.Not;
  16258. }
  16259. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16260. if ((result = detectValue(sample[i])) != null) {
  16261. return result;
  16262. }
  16263. }
  16264. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16265. var dataOriginal = data;
  16266. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  16267. var item = dataOriginal[i];
  16268. var val = getDataItemValue(item);
  16269. if (!isArray(val)) {
  16270. return BE_ORDINAL.Not;
  16271. }
  16272. if ((result = detectValue(val[dimIndex])) != null) {
  16273. return result;
  16274. }
  16275. }
  16276. }
  16277. function detectValue(val) {
  16278. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  16279. // `isFinit('')` get `true`.
  16280. if (val != null && isFinite(val) && val !== '') {
  16281. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  16282. } else if (beStr && val !== '-') {
  16283. return BE_ORDINAL.Must;
  16284. }
  16285. }
  16286. return BE_ORDINAL.Not;
  16287. }
  16288. var internalOptionCreatorMap = createHashMap();
  16289. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  16290. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  16291. if (!internalOptionCreator) {
  16292. return newCmptOptionList;
  16293. }
  16294. var internalOptions = internalOptionCreator(ecModel);
  16295. if (!internalOptions) {
  16296. return newCmptOptionList;
  16297. }
  16298. if ("development" !== 'production') {
  16299. for (var i = 0; i < internalOptions.length; i++) {
  16300. assert(isComponentIdInternal(internalOptions[i]));
  16301. }
  16302. }
  16303. return newCmptOptionList.concat(internalOptions);
  16304. }
  16305. var innerColor = makeInner();
  16306. var innerDecal = makeInner();
  16307. var PaletteMixin =
  16308. /** @class */
  16309. function () {
  16310. function PaletteMixin() {}
  16311. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  16312. var defaultPalette = normalizeToArray(this.get('color', true));
  16313. var layeredPalette = this.get('colorLayer', true);
  16314. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  16315. };
  16316. PaletteMixin.prototype.clearColorPalette = function () {
  16317. clearPalette(this, innerColor);
  16318. };
  16319. return PaletteMixin;
  16320. }();
  16321. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  16322. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  16323. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  16324. }
  16325. function getNearestPalette(palettes, requestColorNum) {
  16326. var paletteNum = palettes.length; // TODO palettes must be in order
  16327. for (var i = 0; i < paletteNum; i++) {
  16328. if (palettes[i].length > requestColorNum) {
  16329. return palettes[i];
  16330. }
  16331. }
  16332. return palettes[paletteNum - 1];
  16333. }
  16334. /**
  16335. * @param name MUST NOT be null/undefined. Otherwise call this function
  16336. * twise with the same parameters will get different result.
  16337. * @param scope default this.
  16338. * @return Can be null/undefined
  16339. */
  16340. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  16341. scope = scope || that;
  16342. var scopeFields = inner(scope);
  16343. var paletteIdx = scopeFields.paletteIdx || 0;
  16344. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16345. if (paletteNameMap.hasOwnProperty(name)) {
  16346. return paletteNameMap[name];
  16347. }
  16348. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  16349. palette = palette || defaultPalette;
  16350. if (!palette || !palette.length) {
  16351. return;
  16352. }
  16353. var pickedPaletteItem = palette[paletteIdx];
  16354. if (name) {
  16355. paletteNameMap[name] = pickedPaletteItem;
  16356. }
  16357. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  16358. return pickedPaletteItem;
  16359. }
  16360. function clearPalette(that, inner) {
  16361. inner(that).paletteIdx = 0;
  16362. inner(that).paletteNameMap = {};
  16363. }
  16364. // Internal method names:
  16365. // -----------------------
  16366. var reCreateSeriesIndices;
  16367. var assertSeriesInitialized;
  16368. var initBase;
  16369. var OPTION_INNER_KEY = '\0_ec_inner';
  16370. var OPTION_INNER_VALUE = 1;
  16371. var GlobalModel =
  16372. /** @class */
  16373. function (_super) {
  16374. __extends(GlobalModel, _super);
  16375. function GlobalModel() {
  16376. return _super !== null && _super.apply(this, arguments) || this;
  16377. }
  16378. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  16379. theme = theme || {};
  16380. this.option = null; // Mark as not initialized.
  16381. this._theme = new Model(theme);
  16382. this._locale = new Model(locale);
  16383. this._optionManager = optionManager;
  16384. };
  16385. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  16386. if ("development" !== 'production') {
  16387. assert(option != null, 'option is null/undefined');
  16388. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  16389. }
  16390. var innerOpt = normalizeSetOptionInput(opts);
  16391. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  16392. this._resetOption(null, innerOpt);
  16393. };
  16394. /**
  16395. * @param type null/undefined: reset all.
  16396. * 'recreate': force recreate all.
  16397. * 'timeline': only reset timeline option
  16398. * 'media': only reset media query option
  16399. * @return Whether option changed.
  16400. */
  16401. GlobalModel.prototype.resetOption = function (type, opt) {
  16402. return this._resetOption(type, normalizeSetOptionInput(opt));
  16403. };
  16404. GlobalModel.prototype._resetOption = function (type, opt) {
  16405. var optionChanged = false;
  16406. var optionManager = this._optionManager;
  16407. if (!type || type === 'recreate') {
  16408. var baseOption = optionManager.mountOption(type === 'recreate');
  16409. if (!this.option || type === 'recreate') {
  16410. initBase(this, baseOption);
  16411. } else {
  16412. this.restoreData();
  16413. this._mergeOption(baseOption, opt);
  16414. }
  16415. optionChanged = true;
  16416. }
  16417. if (type === 'timeline' || type === 'media') {
  16418. this.restoreData();
  16419. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  16420. // it should better not have the same props with `MediaUnit['option']`.
  16421. // Becuase either `option2` or `MediaUnit['option']` will be always merged to "current option"
  16422. // rather than original "baseOption". If they both override a prop, the result might be
  16423. // unexpected when media state changed after `setOption` called.
  16424. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  16425. // (`{baseOption, media}`) in `setOption`.
  16426. // For `timeline`, the case is the same.
  16427. if (!type || type === 'recreate' || type === 'timeline') {
  16428. var timelineOption = optionManager.getTimelineOption(this);
  16429. if (timelineOption) {
  16430. optionChanged = true;
  16431. this._mergeOption(timelineOption, opt);
  16432. }
  16433. }
  16434. if (!type || type === 'recreate' || type === 'media') {
  16435. var mediaOptions = optionManager.getMediaOption(this);
  16436. if (mediaOptions.length) {
  16437. each(mediaOptions, function (mediaOption) {
  16438. optionChanged = true;
  16439. this._mergeOption(mediaOption, opt);
  16440. }, this);
  16441. }
  16442. }
  16443. return optionChanged;
  16444. };
  16445. GlobalModel.prototype.mergeOption = function (option) {
  16446. this._mergeOption(option, null);
  16447. };
  16448. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  16449. var option = this.option;
  16450. var componentsMap = this._componentsMap;
  16451. var componentsCount = this._componentsCount;
  16452. var newCmptTypes = [];
  16453. var newCmptTypeMap = createHashMap();
  16454. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  16455. resetSourceDefaulter(this); // If no component class, merge directly.
  16456. // For example: color, animaiton options, etc.
  16457. each(newOption, function (componentOption, mainType) {
  16458. if (componentOption == null) {
  16459. return;
  16460. }
  16461. if (!ComponentModel.hasClass(mainType)) {
  16462. // globalSettingTask.dirty();
  16463. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  16464. } else if (mainType) {
  16465. newCmptTypes.push(mainType);
  16466. newCmptTypeMap.set(mainType, true);
  16467. }
  16468. });
  16469. if (replaceMergeMainTypeMap) {
  16470. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  16471. // we trade it as it is declared in option as `{xxx: []}`. Because:
  16472. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  16473. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  16474. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  16475. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  16476. newCmptTypes.push(mainTypeInReplaceMerge);
  16477. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  16478. }
  16479. });
  16480. }
  16481. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  16482. function visitComponent(mainType) {
  16483. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  16484. var oldCmptList = componentsMap.get(mainType);
  16485. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  16486. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  16487. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  16488. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  16489. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  16490. // components, which is probably incorrect logic.
  16491. option[mainType] = null;
  16492. componentsMap.set(mainType, null);
  16493. componentsCount.set(mainType, 0);
  16494. var optionsByMainType = [];
  16495. var cmptsByMainType = [];
  16496. var cmptsCountByMainType = 0;
  16497. each(mappingResult, function (resultItem, index) {
  16498. var componentModel = resultItem.existing;
  16499. var newCmptOption = resultItem.newOption;
  16500. if (!newCmptOption) {
  16501. if (componentModel) {
  16502. // Consider where is no new option and should be merged using {},
  16503. // see removeEdgeAndAdd in topologicalTravel and
  16504. // ComponentModel.getAllClassMainTypes.
  16505. componentModel.mergeOption({}, this);
  16506. componentModel.optionUpdated({}, false);
  16507. } // If no both `resultItem.exist` and `resultItem.option`,
  16508. // either it is in `replaceMerge` and not matched by any id,
  16509. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  16510. } else {
  16511. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, true);
  16512. if (componentModel && componentModel.constructor === ComponentModelClass) {
  16513. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  16514. componentModel.mergeOption(newCmptOption, this);
  16515. componentModel.optionUpdated(newCmptOption, false);
  16516. } else {
  16517. // PENDING Global as parent ?
  16518. var extraOpt = extend({
  16519. componentIndex: index
  16520. }, resultItem.keyInfo);
  16521. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  16522. extend(componentModel, extraOpt);
  16523. if (resultItem.brandNew) {
  16524. componentModel.__requireNewView = true;
  16525. }
  16526. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  16527. // newCmptOption has been used as componentModel.option
  16528. // and may be merged with theme and default, so pass null
  16529. // to avoid confusion.
  16530. componentModel.optionUpdated(null, true);
  16531. }
  16532. }
  16533. if (componentModel) {
  16534. optionsByMainType.push(componentModel.option);
  16535. cmptsByMainType.push(componentModel);
  16536. cmptsCountByMainType++;
  16537. } else {
  16538. // Always do assign to avoid elided item in array.
  16539. optionsByMainType.push(void 0);
  16540. cmptsByMainType.push(void 0);
  16541. }
  16542. }, this);
  16543. option[mainType] = optionsByMainType;
  16544. componentsMap.set(mainType, cmptsByMainType);
  16545. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  16546. if (mainType === 'series') {
  16547. reCreateSeriesIndices(this);
  16548. }
  16549. } // If no series declared, ensure `_seriesIndices` initialized.
  16550. if (!this._seriesIndices) {
  16551. reCreateSeriesIndices(this);
  16552. }
  16553. };
  16554. /**
  16555. * Get option for output (cloned option and inner info removed)
  16556. */
  16557. GlobalModel.prototype.getOption = function () {
  16558. var option = clone(this.option);
  16559. each(option, function (optInMainType, mainType) {
  16560. if (ComponentModel.hasClass(mainType)) {
  16561. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  16562. // Inner cmpts might not be at last since ec5.0, but still
  16563. // compatible for users: if inner cmpt at last, splice the returned array.
  16564. var realLen = opts.length;
  16565. var metNonInner = false;
  16566. for (var i = realLen - 1; i >= 0; i--) {
  16567. // Remove options with inner id.
  16568. if (opts[i] && !isComponentIdInternal(opts[i])) {
  16569. metNonInner = true;
  16570. } else {
  16571. opts[i] = null;
  16572. !metNonInner && realLen--;
  16573. }
  16574. }
  16575. opts.length = realLen;
  16576. option[mainType] = opts;
  16577. }
  16578. });
  16579. delete option[OPTION_INNER_KEY];
  16580. return option;
  16581. };
  16582. GlobalModel.prototype.getTheme = function () {
  16583. return this._theme;
  16584. };
  16585. GlobalModel.prototype.getLocaleModel = function () {
  16586. return this._locale;
  16587. };
  16588. GlobalModel.prototype.getLocale = function (localePosition) {
  16589. var locale = this.getLocaleModel();
  16590. return locale.get(localePosition);
  16591. };
  16592. GlobalModel.prototype.setUpdatePayload = function (payload) {
  16593. this._payload = payload;
  16594. };
  16595. GlobalModel.prototype.getUpdatePayload = function () {
  16596. return this._payload;
  16597. };
  16598. /**
  16599. * @param idx If not specified, return the first one.
  16600. */
  16601. GlobalModel.prototype.getComponent = function (mainType, idx) {
  16602. var list = this._componentsMap.get(mainType);
  16603. if (list) {
  16604. var cmpt = list[idx || 0];
  16605. if (cmpt) {
  16606. return cmpt;
  16607. } else if (idx == null) {
  16608. for (var i = 0; i < list.length; i++) {
  16609. if (list[i]) {
  16610. return list[i];
  16611. }
  16612. }
  16613. }
  16614. }
  16615. };
  16616. /**
  16617. * @return Never be null/undefined.
  16618. */
  16619. GlobalModel.prototype.queryComponents = function (condition) {
  16620. var mainType = condition.mainType;
  16621. if (!mainType) {
  16622. return [];
  16623. }
  16624. var index = condition.index;
  16625. var id = condition.id;
  16626. var name = condition.name;
  16627. var cmpts = this._componentsMap.get(mainType);
  16628. if (!cmpts || !cmpts.length) {
  16629. return [];
  16630. }
  16631. var result;
  16632. if (index != null) {
  16633. result = [];
  16634. each(normalizeToArray(index), function (idx) {
  16635. cmpts[idx] && result.push(cmpts[idx]);
  16636. });
  16637. } else if (id != null) {
  16638. result = queryByIdOrName('id', id, cmpts);
  16639. } else if (name != null) {
  16640. result = queryByIdOrName('name', name, cmpts);
  16641. } else {
  16642. // Return all non-empty components in that mainType
  16643. result = filter(cmpts, function (cmpt) {
  16644. return !!cmpt;
  16645. });
  16646. }
  16647. return filterBySubType(result, condition);
  16648. };
  16649. /**
  16650. * The interface is different from queryComponents,
  16651. * which is convenient for inner usage.
  16652. *
  16653. * @usage
  16654. * let result = findComponents(
  16655. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  16656. * );
  16657. * let result = findComponents(
  16658. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  16659. * );
  16660. * let result = findComponents(
  16661. * {mainType: 'series',
  16662. * filter: function (model, index) {...}}
  16663. * );
  16664. * // result like [component0, componnet1, ...]
  16665. */
  16666. GlobalModel.prototype.findComponents = function (condition) {
  16667. var query = condition.query;
  16668. var mainType = condition.mainType;
  16669. var queryCond = getQueryCond(query);
  16670. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  16671. : filter(this._componentsMap.get(mainType), function (cmpt) {
  16672. return !!cmpt;
  16673. });
  16674. return doFilter(filterBySubType(result, condition));
  16675. function getQueryCond(q) {
  16676. var indexAttr = mainType + 'Index';
  16677. var idAttr = mainType + 'Id';
  16678. var nameAttr = mainType + 'Name';
  16679. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  16680. mainType: mainType,
  16681. // subType will be filtered finally.
  16682. index: q[indexAttr],
  16683. id: q[idAttr],
  16684. name: q[nameAttr]
  16685. } : null;
  16686. }
  16687. function doFilter(res) {
  16688. return condition.filter ? filter(res, condition.filter) : res;
  16689. }
  16690. };
  16691. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  16692. var componentsMap = this._componentsMap;
  16693. if (isFunction(mainType)) {
  16694. var ctxForAll_1 = cb;
  16695. var cbForAll_1 = mainType;
  16696. componentsMap.each(function (cmpts, componentType) {
  16697. for (var i = 0; cmpts && i < cmpts.length; i++) {
  16698. var cmpt = cmpts[i];
  16699. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  16700. }
  16701. });
  16702. } else {
  16703. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  16704. for (var i = 0; cmpts && i < cmpts.length; i++) {
  16705. var cmpt = cmpts[i];
  16706. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  16707. }
  16708. }
  16709. };
  16710. /**
  16711. * Get series list before filtered by name.
  16712. */
  16713. GlobalModel.prototype.getSeriesByName = function (name) {
  16714. var nameStr = convertOptionIdName(name, null);
  16715. return filter(this._componentsMap.get('series'), function (oneSeries) {
  16716. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  16717. });
  16718. };
  16719. /**
  16720. * Get series list before filtered by index.
  16721. */
  16722. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  16723. return this._componentsMap.get('series')[seriesIndex];
  16724. };
  16725. /**
  16726. * Get series list before filtered by type.
  16727. * FIXME: rename to getRawSeriesByType?
  16728. */
  16729. GlobalModel.prototype.getSeriesByType = function (subType) {
  16730. return filter(this._componentsMap.get('series'), function (oneSeries) {
  16731. return !!oneSeries && oneSeries.subType === subType;
  16732. });
  16733. };
  16734. /**
  16735. * Get all series before filtered.
  16736. */
  16737. GlobalModel.prototype.getSeries = function () {
  16738. return filter(this._componentsMap.get('series').slice(), function (oneSeries) {
  16739. return !!oneSeries;
  16740. });
  16741. };
  16742. /**
  16743. * Count series before filtered.
  16744. */
  16745. GlobalModel.prototype.getSeriesCount = function () {
  16746. return this._componentsCount.get('series');
  16747. };
  16748. /**
  16749. * After filtering, series may be different
  16750. * frome raw series.
  16751. */
  16752. GlobalModel.prototype.eachSeries = function (cb, context) {
  16753. assertSeriesInitialized(this);
  16754. each(this._seriesIndices, function (rawSeriesIndex) {
  16755. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16756. cb.call(context, series, rawSeriesIndex);
  16757. }, this);
  16758. };
  16759. /**
  16760. * Iterate raw series before filtered.
  16761. *
  16762. * @param {Function} cb
  16763. * @param {*} context
  16764. */
  16765. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  16766. each(this._componentsMap.get('series'), function (series) {
  16767. series && cb.call(context, series, series.componentIndex);
  16768. });
  16769. };
  16770. /**
  16771. * After filtering, series may be different.
  16772. * frome raw series.
  16773. */
  16774. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  16775. assertSeriesInitialized(this);
  16776. each(this._seriesIndices, function (rawSeriesIndex) {
  16777. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16778. if (series.subType === subType) {
  16779. cb.call(context, series, rawSeriesIndex);
  16780. }
  16781. }, this);
  16782. };
  16783. /**
  16784. * Iterate raw series before filtered of given type.
  16785. */
  16786. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  16787. return each(this.getSeriesByType(subType), cb, context);
  16788. };
  16789. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  16790. assertSeriesInitialized(this);
  16791. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  16792. };
  16793. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  16794. return (this._seriesIndices || []).slice();
  16795. };
  16796. GlobalModel.prototype.filterSeries = function (cb, context) {
  16797. assertSeriesInitialized(this);
  16798. var newSeriesIndices = [];
  16799. each(this._seriesIndices, function (seriesRawIdx) {
  16800. var series = this._componentsMap.get('series')[seriesRawIdx];
  16801. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  16802. }, this);
  16803. this._seriesIndices = newSeriesIndices;
  16804. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  16805. };
  16806. GlobalModel.prototype.restoreData = function (payload) {
  16807. reCreateSeriesIndices(this);
  16808. var componentsMap = this._componentsMap;
  16809. var componentTypes = [];
  16810. componentsMap.each(function (components, componentType) {
  16811. if (ComponentModel.hasClass(componentType)) {
  16812. componentTypes.push(componentType);
  16813. }
  16814. });
  16815. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  16816. each(componentsMap.get(componentType), function (component) {
  16817. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  16818. component.restoreData();
  16819. }
  16820. });
  16821. });
  16822. };
  16823. GlobalModel.internalField = function () {
  16824. reCreateSeriesIndices = function (ecModel) {
  16825. var seriesIndices = ecModel._seriesIndices = [];
  16826. each(ecModel._componentsMap.get('series'), function (series) {
  16827. // series may have been removed by `replaceMerge`.
  16828. series && seriesIndices.push(series.componentIndex);
  16829. });
  16830. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  16831. };
  16832. assertSeriesInitialized = function (ecModel) {
  16833. // Components that use _seriesIndices should depends on series component,
  16834. // which make sure that their initialization is after series.
  16835. if ("development" !== 'production') {
  16836. if (!ecModel._seriesIndices) {
  16837. throw new Error('Option should contains series.');
  16838. }
  16839. }
  16840. };
  16841. initBase = function (ecModel, baseOption) {
  16842. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  16843. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  16844. ecModel.option = {};
  16845. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  16846. // before series initialized.
  16847. ecModel._componentsMap = createHashMap({
  16848. series: []
  16849. });
  16850. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  16851. // performed before theme and globalDefault merge.
  16852. var airaOption = baseOption.aria;
  16853. if (isObject(airaOption) && airaOption.enabled == null) {
  16854. airaOption.enabled = true;
  16855. }
  16856. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  16857. merge(baseOption, globalDefault, false);
  16858. ecModel._mergeOption(baseOption, null);
  16859. };
  16860. }();
  16861. return GlobalModel;
  16862. }(Model);
  16863. function isNotTargetSeries(seriesModel, payload) {
  16864. if (payload) {
  16865. var index = payload.seriesIndex;
  16866. var id = payload.seriesId;
  16867. var name_1 = payload.seriesName;
  16868. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  16869. }
  16870. }
  16871. function mergeTheme(option, theme) {
  16872. // PENDING
  16873. // NOT use `colorLayer` in theme if option has `color`
  16874. var notMergeColorLayer = option.color && !option.colorLayer;
  16875. each(theme, function (themeItem, name) {
  16876. if (name === 'colorLayer' && notMergeColorLayer) {
  16877. return;
  16878. } // If it is component model mainType, the model handles that merge later.
  16879. // otherwise, merge them here.
  16880. if (!ComponentModel.hasClass(name)) {
  16881. if (typeof themeItem === 'object') {
  16882. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  16883. } else {
  16884. if (option[name] == null) {
  16885. option[name] = themeItem;
  16886. }
  16887. }
  16888. }
  16889. });
  16890. }
  16891. function queryByIdOrName(attr, idOrName, cmpts) {
  16892. // Here is a break from echarts4: string and number are
  16893. // treated as equal.
  16894. if (isArray(idOrName)) {
  16895. var keyMap_1 = createHashMap();
  16896. each(idOrName, function (idOrNameItem) {
  16897. if (idOrNameItem != null) {
  16898. var idName = convertOptionIdName(idOrNameItem, null);
  16899. idName != null && keyMap_1.set(idOrNameItem, true);
  16900. }
  16901. });
  16902. return filter(cmpts, function (cmpt) {
  16903. return cmpt && keyMap_1.get(cmpt[attr]);
  16904. });
  16905. } else {
  16906. var idName_1 = convertOptionIdName(idOrName, null);
  16907. return filter(cmpts, function (cmpt) {
  16908. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  16909. });
  16910. }
  16911. }
  16912. function filterBySubType(components, condition) {
  16913. // Using hasOwnProperty for restrict. Consider
  16914. // subType is undefined in user payload.
  16915. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  16916. return cmpt && cmpt.subType === condition.subType;
  16917. }) : components;
  16918. }
  16919. function normalizeSetOptionInput(opts) {
  16920. var replaceMergeMainTypeMap = createHashMap();
  16921. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  16922. if ("development" !== 'production') {
  16923. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  16924. }
  16925. replaceMergeMainTypeMap.set(mainType, true);
  16926. });
  16927. return {
  16928. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  16929. };
  16930. }
  16931. mixin(GlobalModel, PaletteMixin);
  16932. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  16933. 'getOption', // 'getViewOfComponentModel',
  16934. // 'getViewOfSeriesModel',
  16935. 'getId', 'updateLabelLayout'];
  16936. var ExtensionAPI =
  16937. /** @class */
  16938. function () {
  16939. function ExtensionAPI(ecInstance) {
  16940. each(availableMethods, function (methodName) {
  16941. this[methodName] = bind(ecInstance[methodName], ecInstance);
  16942. }, this);
  16943. }
  16944. return ExtensionAPI;
  16945. }();
  16946. var coordinateSystemCreators = {};
  16947. var CoordinateSystemManager =
  16948. /** @class */
  16949. function () {
  16950. function CoordinateSystemManager() {
  16951. this._coordinateSystems = [];
  16952. }
  16953. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  16954. var coordinateSystems = [];
  16955. each(coordinateSystemCreators, function (creater, type) {
  16956. var list = creater.create(ecModel, api);
  16957. coordinateSystems = coordinateSystems.concat(list || []);
  16958. });
  16959. this._coordinateSystems = coordinateSystems;
  16960. };
  16961. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  16962. each(this._coordinateSystems, function (coordSys) {
  16963. coordSys.update && coordSys.update(ecModel, api);
  16964. });
  16965. };
  16966. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  16967. return this._coordinateSystems.slice();
  16968. };
  16969. CoordinateSystemManager.register = function (type, creator) {
  16970. coordinateSystemCreators[type] = creator;
  16971. };
  16972. CoordinateSystemManager.get = function (type) {
  16973. return coordinateSystemCreators[type];
  16974. };
  16975. return CoordinateSystemManager;
  16976. }();
  16977. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  16978. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  16979. /**
  16980. * TERM EXPLANATIONS:
  16981. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  16982. */
  16983. var OptionManager =
  16984. /** @class */
  16985. function () {
  16986. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  16987. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  16988. // rawOption cloned and backuped when timeline changed, which does no
  16989. // good to performance. What's more, that both timeline and setOption
  16990. // method supply 'notMerge' brings complex and some problems.
  16991. // Consider this case:
  16992. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  16993. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  16994. function OptionManager(api) {
  16995. this._timelineOptions = [];
  16996. this._mediaList = [];
  16997. /**
  16998. * -1, means default.
  16999. * empty means no media.
  17000. */
  17001. this._currentMediaIndices = [];
  17002. this._api = api;
  17003. }
  17004. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17005. if (rawOption) {
  17006. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17007. each(normalizeToArray(rawOption.series), function (series) {
  17008. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17009. });
  17010. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17011. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17012. });
  17013. } // Caution: some series modify option data, if do not clone,
  17014. // it should ensure that the repeat modify correctly
  17015. // (create a new object when modify itself).
  17016. rawOption = clone(rawOption); // FIXME
  17017. // If some property is set in timeline options or media option but
  17018. // not set in baseOption, a warning should be given.
  17019. var optionBackup = this._optionBackup;
  17020. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17021. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  17022. if (optionBackup) {
  17023. // FIXME
  17024. // the restore merge solution is essentially incorrect.
  17025. // the mapping can not be 100% consistent with ecModel, which probably brings
  17026. // potential bug!
  17027. // The first merge is delayed, becuase in most cases, users do not call `setOption` twice.
  17028. // let fakeCmptsMap = this._fakeCmptsMap;
  17029. // if (!fakeCmptsMap) {
  17030. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17031. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17032. // }
  17033. // mergeToBackupOption(
  17034. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17035. // );
  17036. // For simplicity, timeline options and media options do not support merge,
  17037. // that is, if you `setOption` twice and both has timeline options, the latter
  17038. // timeline opitons will not be merged to the formers, but just substitude them.
  17039. if (newParsedOption.timelineOptions.length) {
  17040. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17041. }
  17042. if (newParsedOption.mediaList.length) {
  17043. optionBackup.mediaList = newParsedOption.mediaList;
  17044. }
  17045. if (newParsedOption.mediaDefault) {
  17046. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17047. }
  17048. } else {
  17049. this._optionBackup = newParsedOption;
  17050. }
  17051. };
  17052. OptionManager.prototype.mountOption = function (isRecreate) {
  17053. var optionBackup = this._optionBackup;
  17054. this._timelineOptions = optionBackup.timelineOptions;
  17055. this._mediaList = optionBackup.mediaList;
  17056. this._mediaDefault = optionBackup.mediaDefault;
  17057. this._currentMediaIndices = [];
  17058. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  17059. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17060. // each time `setOption` called, can be only used in `isRecreate`, because
  17061. // its reliability is under suspicion. In other cases option merge is
  17062. // performed by `model.mergeOption`.
  17063. ? optionBackup.baseOption : this._newBaseOption);
  17064. };
  17065. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17066. var option;
  17067. var timelineOptions = this._timelineOptions;
  17068. if (timelineOptions.length) {
  17069. // getTimelineOption can only be called after ecModel inited,
  17070. // so we can get currentIndex from timelineModel.
  17071. var timelineModel = ecModel.getComponent('timeline');
  17072. if (timelineModel) {
  17073. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  17074. timelineOptions[timelineModel.getCurrentIndex()]);
  17075. }
  17076. }
  17077. return option;
  17078. };
  17079. OptionManager.prototype.getMediaOption = function (ecModel) {
  17080. var ecWidth = this._api.getWidth();
  17081. var ecHeight = this._api.getHeight();
  17082. var mediaList = this._mediaList;
  17083. var mediaDefault = this._mediaDefault;
  17084. var indices = [];
  17085. var result = []; // No media defined.
  17086. if (!mediaList.length && !mediaDefault) {
  17087. return result;
  17088. } // Multi media may be applied, the latter defined media has higher priority.
  17089. for (var i = 0, len = mediaList.length; i < len; i++) {
  17090. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17091. indices.push(i);
  17092. }
  17093. } // FIXME
  17094. // Whether mediaDefault should force users to provide? Otherwise
  17095. // the change by media query can not be recorvered.
  17096. if (!indices.length && mediaDefault) {
  17097. indices = [-1];
  17098. }
  17099. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17100. result = map(indices, function (index) {
  17101. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  17102. });
  17103. } // Otherwise return nothing.
  17104. this._currentMediaIndices = indices;
  17105. return result;
  17106. };
  17107. return OptionManager;
  17108. }();
  17109. /**
  17110. * [RAW_OPTION_PATTERNS]
  17111. * (Note: "series: []" represents all other props in `ECUnitOption`)
  17112. *
  17113. * (1) No prop "baseOption" declared:
  17114. * Root option is used as "baseOption" (except prop "options" and "media").
  17115. * ```js
  17116. * option = {
  17117. * series: [],
  17118. * timeline: {},
  17119. * options: [],
  17120. * };
  17121. * option = {
  17122. * series: [],
  17123. * media: {},
  17124. * };
  17125. * option = {
  17126. * series: [],
  17127. * timeline: {},
  17128. * options: [],
  17129. * media: {},
  17130. * }
  17131. * ```
  17132. *
  17133. * (2) Prop "baseOption" declared:
  17134. * If "baseOption" declared, `ECUnitOption` props can only be declared
  17135. * inside "baseOption" except prop "timeline" (compat ec2).
  17136. * ```js
  17137. * option = {
  17138. * baseOption: {
  17139. * timeline: {},
  17140. * series: [],
  17141. * },
  17142. * options: []
  17143. * };
  17144. * option = {
  17145. * baseOption: {
  17146. * series: [],
  17147. * },
  17148. * media: []
  17149. * };
  17150. * option = {
  17151. * baseOption: {
  17152. * timeline: {},
  17153. * series: [],
  17154. * },
  17155. * options: []
  17156. * media: []
  17157. * };
  17158. * option = {
  17159. * // ec3 compat ec2: allow (only) `timeline` declared
  17160. * // outside baseOption. Keep this setting for compat.
  17161. * timeline: {},
  17162. * baseOption: {
  17163. * series: [],
  17164. * },
  17165. * options: [],
  17166. * media: []
  17167. * };
  17168. * ```
  17169. */
  17170. function parseRawOption( // `rawOption` May be modified
  17171. rawOption, optionPreprocessorFuncs, isNew) {
  17172. var mediaList = [];
  17173. var mediaDefault;
  17174. var baseOption;
  17175. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  17176. var timelineOnRoot = rawOption.timeline;
  17177. var timelineOptionsOnRoot = rawOption.options;
  17178. var mediaOnRoot = rawOption.media;
  17179. var hasMedia = !!rawOption.media;
  17180. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  17181. if (declaredBaseOption) {
  17182. baseOption = declaredBaseOption; // For merge option.
  17183. if (!baseOption.timeline) {
  17184. baseOption.timeline = timelineOnRoot;
  17185. }
  17186. } // For convenience, enable to use the root option as the `baseOption`:
  17187. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  17188. else {
  17189. if (hasTimeline || hasMedia) {
  17190. rawOption.options = rawOption.media = null;
  17191. }
  17192. baseOption = rawOption;
  17193. }
  17194. if (hasMedia) {
  17195. if (isArray(mediaOnRoot)) {
  17196. each(mediaOnRoot, function (singleMedia) {
  17197. if ("development" !== 'production') {
  17198. // Real case of wrong config.
  17199. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  17200. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  17201. }
  17202. }
  17203. if (singleMedia && singleMedia.option) {
  17204. if (singleMedia.query) {
  17205. mediaList.push(singleMedia);
  17206. } else if (!mediaDefault) {
  17207. // Use the first media default.
  17208. mediaDefault = singleMedia;
  17209. }
  17210. }
  17211. });
  17212. } else {
  17213. if ("development" !== 'production') {
  17214. // Real case of wrong config.
  17215. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  17216. }
  17217. }
  17218. }
  17219. doPreprocess(baseOption);
  17220. each(timelineOptionsOnRoot, function (option) {
  17221. return doPreprocess(option);
  17222. });
  17223. each(mediaList, function (media) {
  17224. return doPreprocess(media.option);
  17225. });
  17226. function doPreprocess(option) {
  17227. each(optionPreprocessorFuncs, function (preProcess) {
  17228. preProcess(option, isNew);
  17229. });
  17230. }
  17231. return {
  17232. baseOption: baseOption,
  17233. timelineOptions: timelineOptionsOnRoot || [],
  17234. mediaDefault: mediaDefault,
  17235. mediaList: mediaList
  17236. };
  17237. }
  17238. /**
  17239. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17240. * Support: width, height, aspectRatio
  17241. * Can use max or min as prefix.
  17242. */
  17243. function applyMediaQuery(query, ecWidth, ecHeight) {
  17244. var realMap = {
  17245. width: ecWidth,
  17246. height: ecHeight,
  17247. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17248. };
  17249. var applicatable = true;
  17250. each(query, function (value, attr) {
  17251. var matched = attr.match(QUERY_REG);
  17252. if (!matched || !matched[1] || !matched[2]) {
  17253. return;
  17254. }
  17255. var operator = matched[1];
  17256. var realAttr = matched[2].toLowerCase();
  17257. if (!compare(realMap[realAttr], value, operator)) {
  17258. applicatable = false;
  17259. }
  17260. });
  17261. return applicatable;
  17262. }
  17263. function compare(real, expect, operator) {
  17264. if (operator === 'min') {
  17265. return real >= expect;
  17266. } else if (operator === 'max') {
  17267. return real <= expect;
  17268. } else {
  17269. // Equals
  17270. return real === expect;
  17271. }
  17272. }
  17273. function indicesEquals(indices1, indices2) {
  17274. // indices is always order by asc and has only finite number.
  17275. return indices1.join(',') === indices2.join(',');
  17276. }
  17277. var each$2 = each;
  17278. var isObject$1 = isObject;
  17279. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  17280. function compatEC2ItemStyle(opt) {
  17281. var itemStyleOpt = opt && opt.itemStyle;
  17282. if (!itemStyleOpt) {
  17283. return;
  17284. }
  17285. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17286. var styleName = POSSIBLE_STYLES[i];
  17287. var normalItemStyleOpt = itemStyleOpt.normal;
  17288. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17289. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  17290. if ("development" !== 'production') {
  17291. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  17292. }
  17293. opt[styleName] = opt[styleName] || {};
  17294. if (!opt[styleName].normal) {
  17295. opt[styleName].normal = normalItemStyleOpt[styleName];
  17296. } else {
  17297. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  17298. }
  17299. normalItemStyleOpt[styleName] = null;
  17300. }
  17301. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  17302. if ("development" !== 'production') {
  17303. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  17304. }
  17305. opt[styleName] = opt[styleName] || {};
  17306. if (!opt[styleName].emphasis) {
  17307. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  17308. } else {
  17309. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  17310. }
  17311. emphasisItemStyleOpt[styleName] = null;
  17312. }
  17313. }
  17314. }
  17315. function convertNormalEmphasis(opt, optType, useExtend) {
  17316. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  17317. var normalOpt = opt[optType].normal;
  17318. var emphasisOpt = opt[optType].emphasis;
  17319. if (normalOpt) {
  17320. if ("development" !== 'production') {
  17321. // eslint-disable-next-line max-len
  17322. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  17323. } // Timeline controlStyle has other properties besides normal and emphasis
  17324. if (useExtend) {
  17325. opt[optType].normal = opt[optType].emphasis = null;
  17326. defaults(opt[optType], normalOpt);
  17327. } else {
  17328. opt[optType] = normalOpt;
  17329. }
  17330. }
  17331. if (emphasisOpt) {
  17332. if ("development" !== 'production') {
  17333. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  17334. }
  17335. opt.emphasis = opt.emphasis || {};
  17336. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  17337. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  17338. if (emphasisOpt.focus) {
  17339. opt.emphasis.focus = emphasisOpt.focus;
  17340. }
  17341. if (emphasisOpt.blurScope) {
  17342. opt.emphasis.blurScope = emphasisOpt.blurScope;
  17343. }
  17344. }
  17345. }
  17346. }
  17347. function removeEC3NormalStatus(opt) {
  17348. convertNormalEmphasis(opt, 'itemStyle');
  17349. convertNormalEmphasis(opt, 'lineStyle');
  17350. convertNormalEmphasis(opt, 'areaStyle');
  17351. convertNormalEmphasis(opt, 'label');
  17352. convertNormalEmphasis(opt, 'labelLine'); // treemap
  17353. convertNormalEmphasis(opt, 'upperLabel'); // graph
  17354. convertNormalEmphasis(opt, 'edgeLabel');
  17355. }
  17356. function compatTextStyle(opt, propName) {
  17357. // Check whether is not object (string\null\undefined ...)
  17358. var labelOptSingle = isObject$1(opt) && opt[propName];
  17359. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  17360. if (textStyle) {
  17361. if ("development" !== 'production') {
  17362. // eslint-disable-next-line max-len
  17363. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  17364. }
  17365. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  17366. var textPropName = TEXT_STYLE_OPTIONS[i];
  17367. if (textStyle.hasOwnProperty(textPropName)) {
  17368. labelOptSingle[textPropName] = textStyle[textPropName];
  17369. }
  17370. }
  17371. }
  17372. }
  17373. function compatEC3CommonStyles(opt) {
  17374. if (opt) {
  17375. removeEC3NormalStatus(opt);
  17376. compatTextStyle(opt, 'label');
  17377. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  17378. }
  17379. }
  17380. function processSeries(seriesOpt) {
  17381. if (!isObject$1(seriesOpt)) {
  17382. return;
  17383. }
  17384. compatEC2ItemStyle(seriesOpt);
  17385. removeEC3NormalStatus(seriesOpt);
  17386. compatTextStyle(seriesOpt, 'label'); // treemap
  17387. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  17388. compatTextStyle(seriesOpt, 'edgeLabel');
  17389. if (seriesOpt.emphasis) {
  17390. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  17391. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  17392. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  17393. }
  17394. var markPoint = seriesOpt.markPoint;
  17395. if (markPoint) {
  17396. compatEC2ItemStyle(markPoint);
  17397. compatEC3CommonStyles(markPoint);
  17398. }
  17399. var markLine = seriesOpt.markLine;
  17400. if (markLine) {
  17401. compatEC2ItemStyle(markLine);
  17402. compatEC3CommonStyles(markLine);
  17403. }
  17404. var markArea = seriesOpt.markArea;
  17405. if (markArea) {
  17406. compatEC3CommonStyles(markArea);
  17407. }
  17408. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  17409. // then the backward compat based on option type will not be performed.
  17410. if (seriesOpt.type === 'graph') {
  17411. data = data || seriesOpt.nodes;
  17412. var edgeData = seriesOpt.links || seriesOpt.edges;
  17413. if (edgeData && !isTypedArray(edgeData)) {
  17414. for (var i = 0; i < edgeData.length; i++) {
  17415. compatEC3CommonStyles(edgeData[i]);
  17416. }
  17417. }
  17418. each(seriesOpt.categories, function (opt) {
  17419. removeEC3NormalStatus(opt);
  17420. });
  17421. }
  17422. if (data && !isTypedArray(data)) {
  17423. for (var i = 0; i < data.length; i++) {
  17424. compatEC3CommonStyles(data[i]);
  17425. }
  17426. } // mark point data
  17427. markPoint = seriesOpt.markPoint;
  17428. if (markPoint && markPoint.data) {
  17429. var mpData = markPoint.data;
  17430. for (var i = 0; i < mpData.length; i++) {
  17431. compatEC3CommonStyles(mpData[i]);
  17432. }
  17433. } // mark line data
  17434. markLine = seriesOpt.markLine;
  17435. if (markLine && markLine.data) {
  17436. var mlData = markLine.data;
  17437. for (var i = 0; i < mlData.length; i++) {
  17438. if (isArray(mlData[i])) {
  17439. compatEC3CommonStyles(mlData[i][0]);
  17440. compatEC3CommonStyles(mlData[i][1]);
  17441. } else {
  17442. compatEC3CommonStyles(mlData[i]);
  17443. }
  17444. }
  17445. } // Series
  17446. if (seriesOpt.type === 'gauge') {
  17447. compatTextStyle(seriesOpt, 'axisLabel');
  17448. compatTextStyle(seriesOpt, 'title');
  17449. compatTextStyle(seriesOpt, 'detail');
  17450. } else if (seriesOpt.type === 'treemap') {
  17451. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  17452. each(seriesOpt.levels, function (opt) {
  17453. removeEC3NormalStatus(opt);
  17454. });
  17455. } else if (seriesOpt.type === 'tree') {
  17456. removeEC3NormalStatus(seriesOpt.leaves);
  17457. } // sunburst starts from ec4, so it does not need to compat levels.
  17458. }
  17459. function toArr(o) {
  17460. return isArray(o) ? o : o ? [o] : [];
  17461. }
  17462. function toObj(o) {
  17463. return (isArray(o) ? o[0] : o) || {};
  17464. }
  17465. function globalCompatStyle(option, isTheme) {
  17466. each$2(toArr(option.series), function (seriesOpt) {
  17467. isObject$1(seriesOpt) && processSeries(seriesOpt);
  17468. });
  17469. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  17470. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  17471. each$2(axes, function (axisName) {
  17472. each$2(toArr(option[axisName]), function (axisOpt) {
  17473. if (axisOpt) {
  17474. compatTextStyle(axisOpt, 'axisLabel');
  17475. compatTextStyle(axisOpt.axisPointer, 'label');
  17476. }
  17477. });
  17478. });
  17479. each$2(toArr(option.parallel), function (parallelOpt) {
  17480. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  17481. compatTextStyle(parallelAxisDefault, 'axisLabel');
  17482. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  17483. });
  17484. each$2(toArr(option.calendar), function (calendarOpt) {
  17485. convertNormalEmphasis(calendarOpt, 'itemStyle');
  17486. compatTextStyle(calendarOpt, 'dayLabel');
  17487. compatTextStyle(calendarOpt, 'monthLabel');
  17488. compatTextStyle(calendarOpt, 'yearLabel');
  17489. }); // radar.name.textStyle
  17490. each$2(toArr(option.radar), function (radarOpt) {
  17491. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  17492. if (radarOpt.name && radarOpt.axisName == null) {
  17493. radarOpt.axisName = radarOpt.name;
  17494. delete radarOpt.name;
  17495. if ("development" !== 'production') {
  17496. deprecateLog('name property in radar component has been changed to axisName');
  17497. }
  17498. }
  17499. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  17500. radarOpt.axisNameGap = radarOpt.nameGap;
  17501. delete radarOpt.nameGap;
  17502. if ("development" !== 'production') {
  17503. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  17504. }
  17505. }
  17506. });
  17507. each$2(toArr(option.geo), function (geoOpt) {
  17508. if (isObject$1(geoOpt)) {
  17509. compatEC3CommonStyles(geoOpt);
  17510. each$2(toArr(geoOpt.regions), function (regionObj) {
  17511. compatEC3CommonStyles(regionObj);
  17512. });
  17513. }
  17514. });
  17515. each$2(toArr(option.timeline), function (timelineOpt) {
  17516. compatEC3CommonStyles(timelineOpt);
  17517. convertNormalEmphasis(timelineOpt, 'label');
  17518. convertNormalEmphasis(timelineOpt, 'itemStyle');
  17519. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  17520. var data = timelineOpt.data;
  17521. isArray(data) && each(data, function (item) {
  17522. if (isObject(item)) {
  17523. convertNormalEmphasis(item, 'label');
  17524. convertNormalEmphasis(item, 'itemStyle');
  17525. }
  17526. });
  17527. });
  17528. each$2(toArr(option.toolbox), function (toolboxOpt) {
  17529. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  17530. each$2(toolboxOpt.feature, function (featureOpt) {
  17531. convertNormalEmphasis(featureOpt, 'iconStyle');
  17532. });
  17533. });
  17534. compatTextStyle(toObj(option.axisPointer), 'label');
  17535. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  17536. // storedLogs = {};
  17537. }
  17538. function get(opt, path) {
  17539. var pathArr = path.split(',');
  17540. var obj = opt;
  17541. for (var i = 0; i < pathArr.length; i++) {
  17542. obj = obj && obj[pathArr[i]];
  17543. if (obj == null) {
  17544. break;
  17545. }
  17546. }
  17547. return obj;
  17548. }
  17549. function set$1(opt, path, val, overwrite) {
  17550. var pathArr = path.split(',');
  17551. var obj = opt;
  17552. var key;
  17553. var i = 0;
  17554. for (; i < pathArr.length - 1; i++) {
  17555. key = pathArr[i];
  17556. if (obj[key] == null) {
  17557. obj[key] = {};
  17558. }
  17559. obj = obj[key];
  17560. }
  17561. if (overwrite || obj[pathArr[i]] == null) {
  17562. obj[pathArr[i]] = val;
  17563. }
  17564. }
  17565. function compatLayoutProperties(option) {
  17566. option && each(LAYOUT_PROPERTIES, function (prop) {
  17567. if (prop[0] in option && !(prop[1] in option)) {
  17568. option[prop[1]] = option[prop[0]];
  17569. }
  17570. });
  17571. }
  17572. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  17573. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  17574. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  17575. function compatBarItemStyle(option) {
  17576. var itemStyle = option && option.itemStyle;
  17577. if (itemStyle) {
  17578. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  17579. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  17580. var newName = BAR_ITEM_STYLE_MAP[i][0];
  17581. if (itemStyle[oldName] != null) {
  17582. itemStyle[newName] = itemStyle[oldName];
  17583. if ("development" !== 'production') {
  17584. deprecateReplaceLog(oldName, newName);
  17585. }
  17586. }
  17587. }
  17588. }
  17589. }
  17590. function compatPieLabel(option) {
  17591. if (!option) {
  17592. return;
  17593. }
  17594. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  17595. if ("development" !== 'production') {
  17596. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  17597. }
  17598. option.edgeDistance = option.margin;
  17599. }
  17600. }
  17601. function compatSunburstState(option) {
  17602. if (!option) {
  17603. return;
  17604. }
  17605. if (option.downplay && !option.blur) {
  17606. option.blur = option.downplay;
  17607. if ("development" !== 'production') {
  17608. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  17609. }
  17610. }
  17611. }
  17612. function compatGraphFocus(option) {
  17613. if (!option) {
  17614. return;
  17615. }
  17616. if (option.focusNodeAdjacency != null) {
  17617. option.emphasis = option.emphasis || {};
  17618. if (option.emphasis.focus == null) {
  17619. if ("development" !== 'production') {
  17620. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  17621. }
  17622. option.emphasis.focus = 'adjacency';
  17623. }
  17624. }
  17625. }
  17626. function traverseTree(data, cb) {
  17627. if (data) {
  17628. for (var i = 0; i < data.length; i++) {
  17629. cb(data[i]);
  17630. data[i] && traverseTree(data[i].children, cb);
  17631. }
  17632. }
  17633. }
  17634. function globalBackwardCompat(option, isTheme) {
  17635. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  17636. option.series = normalizeToArray(option.series);
  17637. each(option.series, function (seriesOpt) {
  17638. if (!isObject(seriesOpt)) {
  17639. return;
  17640. }
  17641. var seriesType = seriesOpt.type;
  17642. if (seriesType === 'line') {
  17643. if (seriesOpt.clipOverflow != null) {
  17644. seriesOpt.clip = seriesOpt.clipOverflow;
  17645. if ("development" !== 'production') {
  17646. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  17647. }
  17648. }
  17649. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  17650. if (seriesOpt.clockWise != null) {
  17651. seriesOpt.clockwise = seriesOpt.clockWise;
  17652. if ("development" !== 'production') {
  17653. deprecateReplaceLog('clockWise', 'clockwise');
  17654. }
  17655. }
  17656. compatPieLabel(seriesOpt.label);
  17657. var data = seriesOpt.data;
  17658. if (data && !isTypedArray(data)) {
  17659. for (var i = 0; i < data.length; i++) {
  17660. compatPieLabel(data[i]);
  17661. }
  17662. }
  17663. if (seriesOpt.hoverOffset != null) {
  17664. seriesOpt.emphasis = seriesOpt.emphasis || {};
  17665. if (seriesOpt.emphasis.scaleSize = null) {
  17666. if ("development" !== 'production') {
  17667. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  17668. }
  17669. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  17670. }
  17671. }
  17672. } else if (seriesType === 'gauge') {
  17673. var pointerColor = get(seriesOpt, 'pointer.color');
  17674. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  17675. } else if (seriesType === 'bar') {
  17676. compatBarItemStyle(seriesOpt);
  17677. compatBarItemStyle(seriesOpt.backgroundStyle);
  17678. compatBarItemStyle(seriesOpt.emphasis);
  17679. var data = seriesOpt.data;
  17680. if (data && !isTypedArray(data)) {
  17681. for (var i = 0; i < data.length; i++) {
  17682. if (typeof data[i] === 'object') {
  17683. compatBarItemStyle(data[i]);
  17684. compatBarItemStyle(data[i] && data[i].emphasis);
  17685. }
  17686. }
  17687. }
  17688. } else if (seriesType === 'sunburst') {
  17689. var highlightPolicy = seriesOpt.highlightPolicy;
  17690. if (highlightPolicy) {
  17691. seriesOpt.emphasis = seriesOpt.emphasis || {};
  17692. if (!seriesOpt.emphasis.focus) {
  17693. seriesOpt.emphasis.focus = highlightPolicy;
  17694. if ("development" !== 'production') {
  17695. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  17696. }
  17697. }
  17698. }
  17699. compatSunburstState(seriesOpt);
  17700. traverseTree(seriesOpt.data, compatSunburstState);
  17701. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  17702. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  17703. } else if (seriesType === 'map') {
  17704. if (seriesOpt.mapType && !seriesOpt.map) {
  17705. if ("development" !== 'production') {
  17706. deprecateReplaceLog('mapType', 'map', 'map');
  17707. }
  17708. seriesOpt.map = seriesOpt.mapType;
  17709. }
  17710. if (seriesOpt.mapLocation) {
  17711. if ("development" !== 'production') {
  17712. deprecateLog('`mapLocation` is not used anymore.');
  17713. }
  17714. defaults(seriesOpt, seriesOpt.mapLocation);
  17715. }
  17716. }
  17717. if (seriesOpt.hoverAnimation != null) {
  17718. seriesOpt.emphasis = seriesOpt.emphasis || {};
  17719. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  17720. if ("development" !== 'production') {
  17721. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  17722. }
  17723. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  17724. }
  17725. }
  17726. compatLayoutProperties(seriesOpt);
  17727. }); // dataRange has changed to visualMap
  17728. if (option.dataRange) {
  17729. option.visualMap = option.dataRange;
  17730. }
  17731. each(COMPATITABLE_COMPONENTS, function (componentName) {
  17732. var options = option[componentName];
  17733. if (options) {
  17734. if (!isArray(options)) {
  17735. options = [options];
  17736. }
  17737. each(options, function (option) {
  17738. compatLayoutProperties(option);
  17739. });
  17740. }
  17741. });
  17742. }
  17743. // data processing stage is blocked in stream.
  17744. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  17745. // (2) Only register once when import repeatly.
  17746. // Should be executed after series filtered and before stack calculation.
  17747. function dataStack(ecModel) {
  17748. var stackInfoMap = createHashMap();
  17749. ecModel.eachSeries(function (seriesModel) {
  17750. var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack.
  17751. if (stack) {
  17752. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  17753. var data = seriesModel.getData();
  17754. var stackInfo = {
  17755. // Used for calculate axis extent automatically.
  17756. // TODO: Type getCalculationInfo return more specific type?
  17757. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  17758. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  17759. stackedDimension: data.getCalculationInfo('stackedDimension'),
  17760. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  17761. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  17762. data: data,
  17763. seriesModel: seriesModel
  17764. }; // If stacked on axis that do not support data stack.
  17765. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  17766. return;
  17767. }
  17768. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  17769. stackInfoList.push(stackInfo);
  17770. }
  17771. });
  17772. stackInfoMap.each(calculateStack);
  17773. }
  17774. function calculateStack(stackInfoList) {
  17775. each(stackInfoList, function (targetStackInfo, idxInStack) {
  17776. var resultVal = [];
  17777. var resultNaN = [NaN, NaN];
  17778. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  17779. var targetData = targetStackInfo.data;
  17780. var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes
  17781. // depending on legend selection.
  17782. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  17783. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  17784. // should also be NaN, to draw a appropriate belt area.
  17785. if (isNaN(sum)) {
  17786. return resultNaN;
  17787. }
  17788. var byValue;
  17789. var stackedDataRawIndex;
  17790. if (isStackedByIndex) {
  17791. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  17792. } else {
  17793. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  17794. } // If stackOver is NaN, chart view will render point on value start.
  17795. var stackedOver = NaN;
  17796. for (var j = idxInStack - 1; j >= 0; j--) {
  17797. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  17798. if (!isStackedByIndex) {
  17799. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  17800. }
  17801. if (stackedDataRawIndex >= 0) {
  17802. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  17803. if (sum >= 0 && val > 0 || // Positive stack
  17804. sum <= 0 && val < 0 // Negative stack
  17805. ) {
  17806. sum += val;
  17807. stackedOver = val;
  17808. break;
  17809. }
  17810. }
  17811. }
  17812. resultVal[0] = sum;
  17813. resultVal[1] = stackedOver;
  17814. return resultVal;
  17815. });
  17816. targetData.hostModel.setData(newData); // Update for consequent calculation
  17817. targetStackInfo.data = newData;
  17818. });
  17819. }
  17820. var SourceImpl =
  17821. /** @class */
  17822. function () {
  17823. // readonly frozen: boolean;
  17824. function SourceImpl(fields) {
  17825. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  17826. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  17827. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17828. this.startIndex = fields.startIndex || 0;
  17829. this.dimensionsDefine = fields.dimensionsDefine;
  17830. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  17831. this.encodeDefine = fields.encodeDefine;
  17832. this.metaRawOption = fields.metaRawOption;
  17833. }
  17834. return SourceImpl;
  17835. }();
  17836. function isSourceInstance(val) {
  17837. return val instanceof SourceImpl;
  17838. }
  17839. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  17840. sourceFormat, encodeDefine // can be null
  17841. ) {
  17842. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  17843. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  17844. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  17845. var source = new SourceImpl({
  17846. data: sourceData,
  17847. sourceFormat: sourceFormat,
  17848. seriesLayoutBy: seriesLayoutBy,
  17849. dimensionsDefine: determined.dimensionsDefine,
  17850. startIndex: determined.startIndex,
  17851. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  17852. encodeDefine: makeEncodeDefine(encodeDefine),
  17853. metaRawOption: clone(thisMetaRawOption)
  17854. });
  17855. return source;
  17856. }
  17857. /**
  17858. * Wrap original series data for some compatibility cases.
  17859. */
  17860. function createSourceFromSeriesDataOption(data) {
  17861. return new SourceImpl({
  17862. data: data,
  17863. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  17864. });
  17865. }
  17866. /**
  17867. * Clone source but excludes source data.
  17868. */
  17869. function cloneSourceShallow(source) {
  17870. return new SourceImpl({
  17871. data: source.data,
  17872. sourceFormat: source.sourceFormat,
  17873. seriesLayoutBy: source.seriesLayoutBy,
  17874. dimensionsDefine: clone(source.dimensionsDefine),
  17875. startIndex: source.startIndex,
  17876. dimensionsDetectedCount: source.dimensionsDetectedCount,
  17877. encodeDefine: makeEncodeDefine(source.encodeDefine)
  17878. });
  17879. }
  17880. function makeEncodeDefine(encodeDefine) {
  17881. // null means user not specify `series.encode`.
  17882. return encodeDefine ? createHashMap(encodeDefine) : null;
  17883. }
  17884. /**
  17885. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  17886. */
  17887. function detectSourceFormat(data) {
  17888. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17889. if (isTypedArray(data)) {
  17890. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17891. } else if (isArray(data)) {
  17892. // FIXME Whether tolerate null in top level array?
  17893. if (data.length === 0) {
  17894. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17895. }
  17896. for (var i = 0, len = data.length; i < len; i++) {
  17897. var item = data[i];
  17898. if (item == null) {
  17899. continue;
  17900. } else if (isArray(item)) {
  17901. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17902. break;
  17903. } else if (isObject(item)) {
  17904. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17905. break;
  17906. }
  17907. }
  17908. } else if (isObject(data)) {
  17909. for (var key in data) {
  17910. if (hasOwn(data, key) && isArrayLike(data[key])) {
  17911. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17912. break;
  17913. }
  17914. }
  17915. }
  17916. return sourceFormat;
  17917. }
  17918. /**
  17919. * Determine the source definitions from data standalone dimensions definitions
  17920. * are not specified.
  17921. */
  17922. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  17923. // {
  17924. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  17925. // }
  17926. // in `dataset` or `series`
  17927. dimensionsDefine) {
  17928. var dimensionsDetectedCount;
  17929. var startIndex; // PEDING: could data be null/undefined here?
  17930. // currently, if `dataset.source` not specified, error thrown.
  17931. // if `series.data` not specified, nothing rendered without error thrown.
  17932. // Should test these cases.
  17933. if (!data) {
  17934. return {
  17935. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  17936. startIndex: startIndex,
  17937. dimensionsDetectedCount: dimensionsDetectedCount
  17938. };
  17939. }
  17940. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17941. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  17942. // Caution: consider a line with 5 string and 1 number,
  17943. // it still can not be sure it is a head, because the
  17944. // 5 string may be 5 values of category columns.
  17945. if (sourceHeader === 'auto' || sourceHeader == null) {
  17946. arrayRowsTravelFirst(function (val) {
  17947. // '-' is regarded as null/undefined.
  17948. if (val != null && val !== '-') {
  17949. if (isString(val)) {
  17950. startIndex == null && (startIndex = 1);
  17951. } else {
  17952. startIndex = 0;
  17953. }
  17954. } // 10 is an experience number, avoid long loop.
  17955. }, seriesLayoutBy, dataArrayRows, 10);
  17956. } else {
  17957. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  17958. }
  17959. if (!dimensionsDefine && startIndex === 1) {
  17960. dimensionsDefine = [];
  17961. arrayRowsTravelFirst(function (val, index) {
  17962. dimensionsDefine[index] = val != null ? val + '' : '';
  17963. }, seriesLayoutBy, dataArrayRows, Infinity);
  17964. }
  17965. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  17966. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17967. if (!dimensionsDefine) {
  17968. dimensionsDefine = objectRowsCollectDimensions(data);
  17969. }
  17970. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17971. if (!dimensionsDefine) {
  17972. dimensionsDefine = [];
  17973. each(data, function (colArr, key) {
  17974. dimensionsDefine.push(key);
  17975. });
  17976. }
  17977. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17978. var value0 = getDataItemValue(data[0]);
  17979. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  17980. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17981. if ("development" !== 'production') {
  17982. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17983. }
  17984. }
  17985. return {
  17986. startIndex: startIndex,
  17987. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  17988. dimensionsDetectedCount: dimensionsDetectedCount
  17989. };
  17990. }
  17991. function objectRowsCollectDimensions(data) {
  17992. var firstIndex = 0;
  17993. var obj;
  17994. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17995. if (obj) {
  17996. var dimensions_1 = [];
  17997. each(obj, function (value, key) {
  17998. dimensions_1.push(key);
  17999. });
  18000. return dimensions_1;
  18001. }
  18002. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18003. // which is reasonable. But dimension name is duplicated.
  18004. // Returns undefined or an array contains only object without null/undefiend or string.
  18005. function normalizeDimensionsOption(dimensionsDefine) {
  18006. if (!dimensionsDefine) {
  18007. // The meaning of null/undefined is different from empty array.
  18008. return;
  18009. }
  18010. var nameMap = createHashMap();
  18011. return map(dimensionsDefine, function (rawItem, index) {
  18012. rawItem = isObject(rawItem) ? rawItem : {
  18013. name: rawItem
  18014. }; // Other fields will be discarded.
  18015. var item = {
  18016. name: rawItem.name,
  18017. displayName: rawItem.displayName,
  18018. type: rawItem.type
  18019. }; // User can set null in dimensions.
  18020. // We dont auto specify name, othewise a given name may
  18021. // cause it be refered unexpectedly.
  18022. if (item.name == null) {
  18023. return item;
  18024. } // Also consider number form like 2012.
  18025. item.name += ''; // User may also specify displayName.
  18026. // displayName will always exists except user not
  18027. // specified or dim name is not specified or detected.
  18028. // (A auto generated dim name will not be used as
  18029. // displayName).
  18030. if (item.displayName == null) {
  18031. item.displayName = item.name;
  18032. }
  18033. var exist = nameMap.get(item.name);
  18034. if (!exist) {
  18035. nameMap.set(item.name, {
  18036. count: 1
  18037. });
  18038. } else {
  18039. item.name += '-' + exist.count++;
  18040. }
  18041. return item;
  18042. });
  18043. }
  18044. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18045. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18046. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18047. cb(data[i] ? data[i][0] : null, i);
  18048. }
  18049. } else {
  18050. var value0 = data[0] || [];
  18051. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18052. cb(value0[i], i);
  18053. }
  18054. }
  18055. }
  18056. /*
  18057. * Licensed to the Apache Software Foundation (ASF) under one
  18058. * or more contributor license agreements. See the NOTICE file
  18059. * distributed with this work for additional information
  18060. * regarding copyright ownership. The ASF licenses this file
  18061. * to you under the Apache License, Version 2.0 (the
  18062. * "License"); you may not use this file except in compliance
  18063. * with the License. You may obtain a copy of the License at
  18064. *
  18065. * http://www.apache.org/licenses/LICENSE-2.0
  18066. *
  18067. * Unless required by applicable law or agreed to in writing,
  18068. * software distributed under the License is distributed on an
  18069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18070. * KIND, either express or implied. See the License for the
  18071. * specific language governing permissions and limitations
  18072. * under the License.
  18073. */
  18074. /**
  18075. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18076. */
  18077. /*
  18078. * Licensed to the Apache Software Foundation (ASF) under one
  18079. * or more contributor license agreements. See the NOTICE file
  18080. * distributed with this work for additional information
  18081. * regarding copyright ownership. The ASF licenses this file
  18082. * to you under the Apache License, Version 2.0 (the
  18083. * "License"); you may not use this file except in compliance
  18084. * with the License. You may obtain a copy of the License at
  18085. *
  18086. * http://www.apache.org/licenses/LICENSE-2.0
  18087. *
  18088. * Unless required by applicable law or agreed to in writing,
  18089. * software distributed under the License is distributed on an
  18090. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18091. * KIND, either express or implied. See the License for the
  18092. * specific language governing permissions and limitations
  18093. * under the License.
  18094. */
  18095. var _a, _b, _c; // TODO
  18096. var providerMethods;
  18097. var mountMethods;
  18098. /**
  18099. * If normal array used, mutable chunk size is supported.
  18100. * If typed array used, chunk size must be fixed.
  18101. */
  18102. var DefaultDataProvider =
  18103. /** @class */
  18104. function () {
  18105. function DefaultDataProvider(sourceParam, dimSize) {
  18106. // let source: Source;
  18107. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  18108. this._source = source;
  18109. var data = this._data = source.data; // Typed array. TODO IE10+?
  18110. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18111. if ("development" !== 'production') {
  18112. if (dimSize == null) {
  18113. throw new Error('Typed array data must specify dimension size');
  18114. }
  18115. }
  18116. this._offset = 0;
  18117. this._dimSize = dimSize;
  18118. this._data = data;
  18119. }
  18120. mountMethods(this, data, source);
  18121. }
  18122. DefaultDataProvider.prototype.getSource = function () {
  18123. return this._source;
  18124. };
  18125. DefaultDataProvider.prototype.count = function () {
  18126. return 0;
  18127. };
  18128. DefaultDataProvider.prototype.getItem = function (idx, out) {
  18129. return;
  18130. };
  18131. DefaultDataProvider.prototype.appendData = function (newData) {};
  18132. DefaultDataProvider.prototype.clean = function () {};
  18133. DefaultDataProvider.protoInitialize = function () {
  18134. // PENDING: To avoid potential incompat (e.g., prototype
  18135. // is visited somewhere), still init them on prototype.
  18136. var proto = DefaultDataProvider.prototype;
  18137. proto.pure = false;
  18138. proto.persistent = true;
  18139. }();
  18140. DefaultDataProvider.internalField = function () {
  18141. var _a;
  18142. mountMethods = function (provider, data, source) {
  18143. var sourceFormat = source.sourceFormat;
  18144. var seriesLayoutBy = source.seriesLayoutBy;
  18145. var startIndex = source.startIndex;
  18146. var dimsDef = source.dimensionsDefine;
  18147. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18148. if ("development" !== 'production') {
  18149. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18150. }
  18151. extend(provider, methods);
  18152. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18153. provider.getItem = getItemForTypedArray;
  18154. provider.count = countForTypedArray;
  18155. provider.fillStorage = fillStorageForTypedArray;
  18156. } else {
  18157. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  18158. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  18159. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  18160. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  18161. }
  18162. };
  18163. var getItemForTypedArray = function (idx, out) {
  18164. idx = idx - this._offset;
  18165. out = out || [];
  18166. var data = this._data;
  18167. var dimSize = this._dimSize;
  18168. var offset = dimSize * idx;
  18169. for (var i = 0; i < dimSize; i++) {
  18170. out[i] = data[offset + i];
  18171. }
  18172. return out;
  18173. };
  18174. var fillStorageForTypedArray = function (start, end, storage, extent) {
  18175. var data = this._data;
  18176. var dimSize = this._dimSize;
  18177. for (var dim = 0; dim < dimSize; dim++) {
  18178. var dimExtent = extent[dim];
  18179. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  18180. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  18181. var count = end - start;
  18182. var arr = storage[dim];
  18183. for (var i = 0; i < count; i++) {
  18184. // appendData with TypedArray will always do replace in provider.
  18185. var val = data[i * dimSize + dim];
  18186. arr[start + i] = val;
  18187. val < min && (min = val);
  18188. val > max && (max = val);
  18189. }
  18190. dimExtent[0] = min;
  18191. dimExtent[1] = max;
  18192. }
  18193. };
  18194. var countForTypedArray = function () {
  18195. return this._data ? this._data.length / this._dimSize : 0;
  18196. };
  18197. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  18198. pure: true,
  18199. appendData: appendDataSimply
  18200. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  18201. pure: true,
  18202. appendData: function () {
  18203. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18204. }
  18205. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  18206. pure: true,
  18207. appendData: appendDataSimply
  18208. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  18209. pure: true,
  18210. appendData: function (newData) {
  18211. var data = this._data;
  18212. each(newData, function (newCol, key) {
  18213. var oldCol = data[key] || (data[key] = []);
  18214. for (var i = 0; i < (newCol || []).length; i++) {
  18215. oldCol.push(newCol[i]);
  18216. }
  18217. });
  18218. }
  18219. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  18220. appendData: appendDataSimply
  18221. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  18222. persistent: false,
  18223. pure: true,
  18224. appendData: function (newData) {
  18225. if ("development" !== 'production') {
  18226. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  18227. }
  18228. this._data = newData;
  18229. },
  18230. // Clean self if data is already used.
  18231. clean: function () {
  18232. // PENDING
  18233. this._offset += this.count();
  18234. this._data = null;
  18235. }
  18236. }, _a);
  18237. function appendDataSimply(newData) {
  18238. for (var i = 0; i < newData.length; i++) {
  18239. this._data.push(newData[i]);
  18240. }
  18241. }
  18242. }();
  18243. return DefaultDataProvider;
  18244. }();
  18245. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  18246. return rawData[idx];
  18247. };
  18248. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  18249. return rawData[idx + startIndex];
  18250. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx) {
  18251. idx += startIndex;
  18252. var item = [];
  18253. var data = rawData;
  18254. for (var i = 0; i < data.length; i++) {
  18255. var row = data[i];
  18256. item.push(row ? row[idx] : null);
  18257. }
  18258. return item;
  18259. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx) {
  18260. var item = [];
  18261. for (var i = 0; i < dimsDef.length; i++) {
  18262. var dimName = dimsDef[i].name;
  18263. if ("development" !== 'production') {
  18264. if (dimName == null) {
  18265. throw new Error();
  18266. }
  18267. }
  18268. var col = rawData[dimName];
  18269. item.push(col ? col[idx] : null);
  18270. }
  18271. return item;
  18272. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  18273. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  18274. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18275. if ("development" !== 'production') {
  18276. assert(method, 'Do not suppport get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18277. }
  18278. return method;
  18279. }
  18280. var countSimply = function (rawData, startIndex, dimsDef) {
  18281. return rawData.length;
  18282. };
  18283. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  18284. return Math.max(0, rawData.length - startIndex);
  18285. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  18286. var row = rawData[0];
  18287. return row ? Math.max(0, row.length - startIndex) : 0;
  18288. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  18289. var dimName = dimsDef[0].name;
  18290. if ("development" !== 'production') {
  18291. if (dimName == null) {
  18292. throw new Error();
  18293. }
  18294. }
  18295. var col = rawData[dimName];
  18296. return col ? col.length : 0;
  18297. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  18298. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  18299. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18300. if ("development" !== 'production') {
  18301. assert(method, 'Do not suppport count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18302. }
  18303. return method;
  18304. }
  18305. var getRawValueSimply = function (dataItem, dimIndex, dimName) {
  18306. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18307. };
  18308. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, dimName) {
  18309. return dimIndex != null ? dataItem[dimName] : dataItem;
  18310. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, dimName) {
  18311. // FIXME: In some case (markpoint in geo (geo-map.html)),
  18312. // dataItem is {coord: [...]}
  18313. var value = getDataItemValue(dataItem);
  18314. return dimIndex == null || !(value instanceof Array) ? value : value[dimIndex];
  18315. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  18316. function getRawSourceValueGetter(sourceFormat) {
  18317. var method = rawSourceValueGetterMap[sourceFormat];
  18318. if ("development" !== 'production') {
  18319. assert(method, 'Do not suppport get value on "' + sourceFormat + '".');
  18320. }
  18321. return method;
  18322. }
  18323. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  18324. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  18325. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18326. // Consider persistent.
  18327. // Caution: why use raw value to display on label or tooltip?
  18328. // A reason is to avoid format. For example time value we do not know
  18329. // how to format is expected. More over, if stack is used, calculated
  18330. // value may be 0.91000000001, which have brings trouble to display.
  18331. // TODO: consider how to treat null/undefined/NaN when display?
  18332. function retrieveRawValue(data, dataIndex, dim // If dimIndex is null/undefined, return OptionDataItem.
  18333. // Otherwise, return OptionDataValue.
  18334. ) {
  18335. if (!data) {
  18336. return;
  18337. } // Consider data may be not persistent.
  18338. var dataItem = data.getRawDataItem(dataIndex);
  18339. if (dataItem == null) {
  18340. return;
  18341. }
  18342. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18343. var dimName;
  18344. var dimIndex;
  18345. var dimInfo = data.getDimensionInfo(dim);
  18346. if (dimInfo) {
  18347. dimName = dimInfo.name;
  18348. dimIndex = dimInfo.index;
  18349. }
  18350. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, dimName);
  18351. }
  18352. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18353. var DataFormatMixin =
  18354. /** @class */
  18355. function () {
  18356. function DataFormatMixin() {}
  18357. /**
  18358. * Get params for formatter
  18359. */
  18360. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  18361. var data = this.getData(dataType);
  18362. var rawValue = this.getRawValue(dataIndex, dataType);
  18363. var rawDataIndex = data.getRawIndex(dataIndex);
  18364. var name = data.getName(dataIndex);
  18365. var itemOpt = data.getRawDataItem(dataIndex);
  18366. var style = data.getItemVisual(dataIndex, 'style');
  18367. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  18368. var borderColor = style && style.stroke;
  18369. var mainType = this.mainType;
  18370. var isSeries = mainType === 'series';
  18371. var userOutput = data.userOutput;
  18372. return {
  18373. componentType: mainType,
  18374. componentSubType: this.subType,
  18375. componentIndex: this.componentIndex,
  18376. seriesType: isSeries ? this.subType : null,
  18377. seriesIndex: this.seriesIndex,
  18378. seriesId: isSeries ? this.id : null,
  18379. seriesName: isSeries ? this.name : null,
  18380. name: name,
  18381. dataIndex: rawDataIndex,
  18382. data: itemOpt,
  18383. dataType: dataType,
  18384. value: rawValue,
  18385. color: color,
  18386. borderColor: borderColor,
  18387. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  18388. encode: userOutput ? userOutput.encode : null,
  18389. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18390. $vars: ['seriesName', 'name', 'value']
  18391. };
  18392. };
  18393. /**
  18394. * Format label
  18395. * @param dataIndex
  18396. * @param status 'normal' by default
  18397. * @param dataType
  18398. * @param labelDimIndex Only used in some chart that
  18399. * use formatter in different dimensions, like radar.
  18400. * @param formatter Formatter given outside.
  18401. * @return return null/undefined if no formatter
  18402. */
  18403. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  18404. status = status || 'normal';
  18405. var data = this.getData(dataType);
  18406. var params = this.getDataParams(dataIndex, dataType);
  18407. if (extendParams) {
  18408. params.value = extendParams.interpolatedValue;
  18409. }
  18410. if (labelDimIndex != null && isArray(params.value)) {
  18411. params.value = params.value[labelDimIndex];
  18412. }
  18413. if (!formatter) {
  18414. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  18415. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  18416. }
  18417. if (typeof formatter === 'function') {
  18418. params.status = status;
  18419. params.dimensionIndex = labelDimIndex;
  18420. return formatter(params);
  18421. } else if (typeof formatter === 'string') {
  18422. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  18423. // Do not support '}' in dim name util have to.
  18424. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  18425. var len = dimStr.length;
  18426. var dimLoose = dimStr.charAt(0) === '[' && dimStr.charAt(len - 1) === ']' ? +dimStr.slice(1, len - 1) // Also support: '[]' => 0
  18427. : dimStr;
  18428. var val = retrieveRawValue(data, dataIndex, dimLoose);
  18429. if (extendParams && isArray(extendParams.interpolatedValue)) {
  18430. var dimInfo = data.getDimensionInfo(dimLoose);
  18431. if (dimInfo) {
  18432. val = extendParams.interpolatedValue[dimInfo.index];
  18433. }
  18434. }
  18435. return val != null ? val + '' : '';
  18436. });
  18437. }
  18438. };
  18439. /**
  18440. * Get raw value in option
  18441. */
  18442. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  18443. return retrieveRawValue(this.getData(dataType), idx);
  18444. };
  18445. /**
  18446. * Should be implemented.
  18447. * @param {number} dataIndex
  18448. * @param {boolean} [multipleSeries=false]
  18449. * @param {string} [dataType]
  18450. */
  18451. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  18452. // Empty function
  18453. return;
  18454. };
  18455. return DataFormatMixin;
  18456. }();
  18457. /**
  18458. * @param {Object} define
  18459. * @return See the return of `createTask`.
  18460. */
  18461. function createTask(define) {
  18462. return new Task(define);
  18463. }
  18464. var Task =
  18465. /** @class */
  18466. function () {
  18467. function Task(define) {
  18468. define = define || {};
  18469. this._reset = define.reset;
  18470. this._plan = define.plan;
  18471. this._count = define.count;
  18472. this._onDirty = define.onDirty;
  18473. this._dirty = true;
  18474. }
  18475. /**
  18476. * @param step Specified step.
  18477. * @param skip Skip customer perform call.
  18478. * @param modBy Sampling window size.
  18479. * @param modDataCount Sampling count.
  18480. * @return whether unfinished.
  18481. */
  18482. Task.prototype.perform = function (performArgs) {
  18483. var upTask = this._upstream;
  18484. var skip = performArgs && performArgs.skip; // TODO some refactor.
  18485. // Pull data. Must pull data each time, because context.data
  18486. // may be updated by Series.setData.
  18487. if (this._dirty && upTask) {
  18488. var context = this.context;
  18489. context.data = context.outputData = upTask.context.outputData;
  18490. }
  18491. if (this.__pipeline) {
  18492. this.__pipeline.currentTask = this;
  18493. }
  18494. var planResult;
  18495. if (this._plan && !skip) {
  18496. planResult = this._plan(this.context);
  18497. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  18498. // elements uniformed distributed when progress, especially when moving or zooming.
  18499. var lastModBy = normalizeModBy(this._modBy);
  18500. var lastModDataCount = this._modDataCount || 0;
  18501. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  18502. var modDataCount = performArgs && performArgs.modDataCount || 0;
  18503. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  18504. planResult = 'reset';
  18505. }
  18506. function normalizeModBy(val) {
  18507. !(val >= 1) && (val = 1); // jshint ignore:line
  18508. return val;
  18509. }
  18510. var forceFirstProgress;
  18511. if (this._dirty || planResult === 'reset') {
  18512. this._dirty = false;
  18513. forceFirstProgress = this._doReset(skip);
  18514. }
  18515. this._modBy = modBy;
  18516. this._modDataCount = modDataCount;
  18517. var step = performArgs && performArgs.step;
  18518. if (upTask) {
  18519. if ("development" !== 'production') {
  18520. assert(upTask._outputDueEnd != null);
  18521. }
  18522. this._dueEnd = upTask._outputDueEnd;
  18523. } // DataTask or overallTask
  18524. else {
  18525. if ("development" !== 'production') {
  18526. assert(!this._progress || this._count);
  18527. }
  18528. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18529. } // Note: Stubs, that its host overall task let it has progress, has progress.
  18530. // If no progress, pass index from upstream to downstream each time plan called.
  18531. if (this._progress) {
  18532. var start = this._dueIndex;
  18533. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  18534. if (!skip && (forceFirstProgress || start < end)) {
  18535. var progress = this._progress;
  18536. if (isArray(progress)) {
  18537. for (var i = 0; i < progress.length; i++) {
  18538. this._doProgress(progress[i], start, end, modBy, modDataCount);
  18539. }
  18540. } else {
  18541. this._doProgress(progress, start, end, modBy, modDataCount);
  18542. }
  18543. }
  18544. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  18545. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  18546. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  18547. if ("development" !== 'production') {
  18548. // ??? Can not rollback.
  18549. assert(outputDueEnd >= this._outputDueEnd);
  18550. }
  18551. this._outputDueEnd = outputDueEnd;
  18552. } else {
  18553. // (1) Some overall task has no progress.
  18554. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  18555. // This should always be performed so it can be passed to downstream.
  18556. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  18557. }
  18558. return this.unfinished();
  18559. };
  18560. Task.prototype.dirty = function () {
  18561. this._dirty = true;
  18562. this._onDirty && this._onDirty(this.context);
  18563. };
  18564. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  18565. iterator.reset(start, end, modBy, modDataCount);
  18566. this._callingProgress = progress;
  18567. this._callingProgress({
  18568. start: start,
  18569. end: end,
  18570. count: end - start,
  18571. next: iterator.next
  18572. }, this.context);
  18573. };
  18574. Task.prototype._doReset = function (skip) {
  18575. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  18576. this._settedOutputEnd = null;
  18577. var progress;
  18578. var forceFirstProgress;
  18579. if (!skip && this._reset) {
  18580. progress = this._reset(this.context);
  18581. if (progress && progress.progress) {
  18582. forceFirstProgress = progress.forceFirstProgress;
  18583. progress = progress.progress;
  18584. } // To simplify no progress checking, array must has item.
  18585. if (isArray(progress) && !progress.length) {
  18586. progress = null;
  18587. }
  18588. }
  18589. this._progress = progress;
  18590. this._modBy = this._modDataCount = null;
  18591. var downstream = this._downstream;
  18592. downstream && downstream.dirty();
  18593. return forceFirstProgress;
  18594. };
  18595. Task.prototype.unfinished = function () {
  18596. return this._progress && this._dueIndex < this._dueEnd;
  18597. };
  18598. /**
  18599. * @param downTask The downstream task.
  18600. * @return The downstream task.
  18601. */
  18602. Task.prototype.pipe = function (downTask) {
  18603. if ("development" !== 'production') {
  18604. assert(downTask && !downTask._disposed && downTask !== this);
  18605. } // If already downstream, do not dirty downTask.
  18606. if (this._downstream !== downTask || this._dirty) {
  18607. this._downstream = downTask;
  18608. downTask._upstream = this;
  18609. downTask.dirty();
  18610. }
  18611. };
  18612. Task.prototype.dispose = function () {
  18613. if (this._disposed) {
  18614. return;
  18615. }
  18616. this._upstream && (this._upstream._downstream = null);
  18617. this._downstream && (this._downstream._upstream = null);
  18618. this._dirty = false;
  18619. this._disposed = true;
  18620. };
  18621. Task.prototype.getUpstream = function () {
  18622. return this._upstream;
  18623. };
  18624. Task.prototype.getDownstream = function () {
  18625. return this._downstream;
  18626. };
  18627. Task.prototype.setOutputEnd = function (end) {
  18628. // This only happend in dataTask, dataZoom, map, currently.
  18629. // where dataZoom do not set end each time, but only set
  18630. // when reset. So we should record the setted end, in case
  18631. // that the stub of dataZoom perform again and earse the
  18632. // setted end by upstream.
  18633. this._outputDueEnd = this._settedOutputEnd = end;
  18634. };
  18635. return Task;
  18636. }();
  18637. var iterator = function () {
  18638. var end;
  18639. var current;
  18640. var modBy;
  18641. var modDataCount;
  18642. var winCount;
  18643. var it = {
  18644. reset: function (s, e, sStep, sCount) {
  18645. current = s;
  18646. end = e;
  18647. modBy = sStep;
  18648. modDataCount = sCount;
  18649. winCount = Math.ceil(modDataCount / modBy);
  18650. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  18651. }
  18652. };
  18653. return it;
  18654. function sequentialNext() {
  18655. return current < end ? current++ : null;
  18656. }
  18657. function modNext() {
  18658. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  18659. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  18660. // Use normal linear rendering mode.
  18661. : current;
  18662. current++;
  18663. return result;
  18664. }
  18665. }(); ///////////////////////////////////////////////////////////
  18666. // For stream debug (Should be commented out after used!)
  18667. // @usage: printTask(this, 'begin');
  18668. // @usage: printTask(this, null, {someExtraProp});
  18669. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  18670. //
  18671. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  18672. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  18673. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  18674. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  18675. // let props = [];
  18676. // if (task.__pipeline) {
  18677. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  18678. // props.push({text: '__idxInPipeline/total', value: val});
  18679. // } else {
  18680. // let stubCount = 0;
  18681. // task.agentStubMap.each(() => stubCount++);
  18682. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  18683. // }
  18684. // props.push({text: 'uid', value: task.uidDebug});
  18685. // if (task.__pipeline) {
  18686. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  18687. // task.agent && props.push(
  18688. // {text: 'stubFor', value: task.agent.uidDebug}
  18689. // );
  18690. // }
  18691. // props.push(
  18692. // {text: 'dirty', value: task._dirty},
  18693. // {text: 'dueIndex', value: task._dueIndex},
  18694. // {text: 'dueEnd', value: task._dueEnd},
  18695. // {text: 'outputDueEnd', value: task._outputDueEnd}
  18696. // );
  18697. // if (extra) {
  18698. // Object.keys(extra).forEach(key => {
  18699. // props.push({text: key, value: extra[key]});
  18700. // });
  18701. // }
  18702. // let args = ['color: blue'];
  18703. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  18704. // args.push('color: green', 'color: red'),
  18705. // `${item.text}: %c${item.value}`
  18706. // )).join('%c, ');
  18707. // console.log.apply(console, [msg].concat(args));
  18708. // // console.log(this);
  18709. // };
  18710. // window.printPipeline = function (task: any, prefix: string) {
  18711. // const pipeline = task.__pipeline;
  18712. // let currTask = pipeline.head;
  18713. // while (currTask) {
  18714. // window.printTask(currTask, prefix);
  18715. // currTask = currTask._downstream;
  18716. // }
  18717. // };
  18718. // window.showChain = function (chainHeadTask) {
  18719. // var chain = [];
  18720. // var task = chainHeadTask;
  18721. // while (task) {
  18722. // chain.push({
  18723. // task: task,
  18724. // up: task._upstream,
  18725. // down: task._downstream,
  18726. // idxInPipeline: task.__idxInPipeline
  18727. // });
  18728. // task = task._downstream;
  18729. // }
  18730. // return chain;
  18731. // };
  18732. // window.findTaskInChain = function (task, chainHeadTask) {
  18733. // let chain = window.showChain(chainHeadTask);
  18734. // let result = [];
  18735. // for (let i = 0; i < chain.length; i++) {
  18736. // let chainItem = chain[i];
  18737. // if (chainItem.task === task) {
  18738. // result.push(i);
  18739. // }
  18740. // }
  18741. // return result;
  18742. // };
  18743. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  18744. // let chainA = window.showChain(chainHeadTaskA);
  18745. // for (let i = 0; i < chainA.length; i++) {
  18746. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  18747. // }
  18748. // };
  18749. /**
  18750. * Convert raw the value in to inner value in List.
  18751. *
  18752. * [Performance sensitive]
  18753. *
  18754. * [Caution]: this is the key logic of user value parser.
  18755. * For backward compatibiliy, do not modify it until have to!
  18756. */
  18757. function parseDataValue(value, // For high performance, do not omit the second param.
  18758. opt) {
  18759. // Performance sensitive.
  18760. var dimType = opt && opt.type;
  18761. if (dimType === 'ordinal') {
  18762. // If given value is a category string
  18763. var ordinalMeta = opt && opt.ordinalMeta;
  18764. return ordinalMeta ? ordinalMeta.parseAndCollect(value) : value;
  18765. }
  18766. if (dimType === 'time' // spead up when using timestamp
  18767. && typeof value !== 'number' && value != null && value !== '-') {
  18768. value = +parseDate(value);
  18769. } // dimType defaults 'number'.
  18770. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  18771. // parse to NaN.
  18772. // number-like string (like ' 123 ') can be converted to a number.
  18773. // where null/undefined or other string will be converted to NaN.
  18774. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  18775. // If object, also parse to NaN
  18776. : +value;
  18777. }
  18778. var valueParserMap = createHashMap({
  18779. 'number': function (val) {
  18780. // Do not use `numericToNumber` here. We have by defualt `numericToNumber`.
  18781. // Here the number parser can have loose rule:
  18782. // enable to cut suffix: "120px" => 120, "14%" => 14.
  18783. return parseFloat(val);
  18784. },
  18785. 'time': function (val) {
  18786. // return timestamp.
  18787. return +parseDate(val);
  18788. },
  18789. 'trim': function (val) {
  18790. return typeof val === 'string' ? trim(val) : val;
  18791. }
  18792. });
  18793. /**
  18794. * TODO: disable writable.
  18795. * This structure will be exposed to users.
  18796. */
  18797. var ExternalSource =
  18798. /** @class */
  18799. function () {
  18800. function ExternalSource() {}
  18801. ExternalSource.prototype.getRawData = function () {
  18802. // Only built-in transform available.
  18803. throw new Error('not supported');
  18804. };
  18805. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  18806. // Only built-in transform available.
  18807. throw new Error('not supported');
  18808. };
  18809. ExternalSource.prototype.cloneRawData = function () {
  18810. return;
  18811. };
  18812. /**
  18813. * @return If dimension not found, return null/undefined.
  18814. */
  18815. ExternalSource.prototype.getDimensionInfo = function (dim) {
  18816. return;
  18817. };
  18818. /**
  18819. * dimensions defined if and only if either:
  18820. * (a) dataset.dimensions are declared.
  18821. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  18822. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  18823. * the defined dimensions.
  18824. * Otherwise, `dimensionInfoAll` is determined by data columns.
  18825. * @return Always return an array (even empty array).
  18826. */
  18827. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  18828. return;
  18829. };
  18830. ExternalSource.prototype.count = function () {
  18831. return;
  18832. };
  18833. /**
  18834. * Only support by dimension index.
  18835. * No need to support by dimension name in transform function,
  18836. * becuase transform function is not case-specific, no need to use name literally.
  18837. */
  18838. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  18839. return;
  18840. };
  18841. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  18842. return;
  18843. };
  18844. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  18845. return parseDataValue(rawVal, dimInfo);
  18846. };
  18847. return ExternalSource;
  18848. }();
  18849. function createExternalSource(internalSource, externalTransform) {
  18850. var extSource = new ExternalSource();
  18851. var data = internalSource.data;
  18852. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  18853. var sourceHeaderCount = internalSource.startIndex;
  18854. var errMsg = '';
  18855. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  18856. // For the logic simplicity in transformer, only 'culumn' is
  18857. // supported in data transform. Otherwise, the `dimensionsDefine`
  18858. // might be detected by 'row', which probably confuses users.
  18859. if ("development" !== 'production') {
  18860. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  18861. }
  18862. throwError(errMsg);
  18863. } // [MEMO]
  18864. // Create a new dimensions structure for exposing.
  18865. // Do not expose all dimension info to users directly.
  18866. // Becuase the dimension is probably auto detected from data and not might reliable.
  18867. // Should not lead the transformers to think that is relialbe and return it.
  18868. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  18869. var dimensions = [];
  18870. var dimsByName = {};
  18871. var dimsDef = internalSource.dimensionsDefine;
  18872. if (dimsDef) {
  18873. each(dimsDef, function (dimDef, idx) {
  18874. var name = dimDef.name;
  18875. var dimDefExt = {
  18876. index: idx,
  18877. name: name,
  18878. displayName: dimDef.displayName
  18879. };
  18880. dimensions.push(dimDefExt); // Users probably not sepcify dimension name. For simplicity, data transform
  18881. // do not generate dimension name.
  18882. if (name != null) {
  18883. // Dimension name should not be duplicated.
  18884. // For simplicity, data transform forbid name duplication, do not generate
  18885. // new name like module `completeDimensions.ts` did, but just tell users.
  18886. var errMsg_1 = '';
  18887. if (hasOwn(dimsByName, name)) {
  18888. if ("development" !== 'production') {
  18889. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  18890. }
  18891. throwError(errMsg_1);
  18892. }
  18893. dimsByName[name] = dimDefExt;
  18894. }
  18895. });
  18896. } // If dimension definitions are not defined and can not be detected.
  18897. // e.g., pure data `[[11, 22], ...]`.
  18898. else {
  18899. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  18900. // Do not generete name or anything others. The consequence process in
  18901. // `transform` or `series` probably have there own name generation strategry.
  18902. dimensions.push({
  18903. index: i
  18904. });
  18905. }
  18906. } // Implement public methods:
  18907. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  18908. if (externalTransform.__isBuiltIn) {
  18909. extSource.getRawDataItem = function (dataIndex) {
  18910. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  18911. };
  18912. extSource.getRawData = bind(getRawData, null, internalSource);
  18913. }
  18914. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  18915. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  18916. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  18917. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  18918. extSource.retrieveValue = function (dataIndex, dimIndex) {
  18919. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  18920. return retrieveValueFromItem(rawItem, dimIndex);
  18921. };
  18922. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  18923. if (dataItem == null) {
  18924. return;
  18925. }
  18926. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  18927. if (dimDef) {
  18928. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  18929. }
  18930. };
  18931. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  18932. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  18933. return extSource;
  18934. }
  18935. function getRawData(upstream) {
  18936. var sourceFormat = upstream.sourceFormat;
  18937. if (!isSupportedSourceFormat(sourceFormat)) {
  18938. var errMsg = '';
  18939. if ("development" !== 'production') {
  18940. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  18941. }
  18942. throwError(errMsg);
  18943. }
  18944. return upstream.data;
  18945. }
  18946. function cloneRawData(upstream) {
  18947. var sourceFormat = upstream.sourceFormat;
  18948. var data = upstream.data;
  18949. if (!isSupportedSourceFormat(sourceFormat)) {
  18950. var errMsg = '';
  18951. if ("development" !== 'production') {
  18952. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  18953. }
  18954. throwError(errMsg);
  18955. }
  18956. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18957. var result = [];
  18958. for (var i = 0, len = data.length; i < len; i++) {
  18959. // Not strictly clone for performance
  18960. result.push(data[i].slice());
  18961. }
  18962. return result;
  18963. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18964. var result = [];
  18965. for (var i = 0, len = data.length; i < len; i++) {
  18966. // Not strictly clone for performance
  18967. result.push(extend({}, data[i]));
  18968. }
  18969. return result;
  18970. }
  18971. }
  18972. function getDimensionInfo(dimensions, dimsByName, dim) {
  18973. if (dim == null) {
  18974. return;
  18975. } // Keep the same logic as `List::getDimension` did.
  18976. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  18977. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  18978. return dimensions[dim];
  18979. } else if (hasOwn(dimsByName, dim)) {
  18980. return dimsByName[dim];
  18981. }
  18982. }
  18983. function cloneAllDimensionInfo(dimensions) {
  18984. return clone(dimensions);
  18985. }
  18986. var externalTransformMap = createHashMap();
  18987. function registerExternalTransform(externalTransform) {
  18988. externalTransform = clone(externalTransform);
  18989. var type = externalTransform.type;
  18990. var errMsg = '';
  18991. if (!type) {
  18992. if ("development" !== 'production') {
  18993. errMsg = 'Must have a `type` when `registerTransform`.';
  18994. }
  18995. throwError(errMsg);
  18996. }
  18997. var typeParsed = type.split(':');
  18998. if (typeParsed.length !== 2) {
  18999. if ("development" !== 'production') {
  19000. errMsg = 'Name must include namespace like "ns:regression".';
  19001. }
  19002. throwError(errMsg);
  19003. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  19004. // be called directly via 'xxx' rather than 'echarts:xxx'.
  19005. var isBuiltIn = false;
  19006. if (typeParsed[0] === 'echarts') {
  19007. type = typeParsed[1];
  19008. isBuiltIn = true;
  19009. }
  19010. externalTransform.__isBuiltIn = isBuiltIn;
  19011. externalTransformMap.set(type, externalTransform);
  19012. }
  19013. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  19014. var pipedTransOption = normalizeToArray(rawTransOption);
  19015. var pipeLen = pipedTransOption.length;
  19016. var errMsg = '';
  19017. if (!pipeLen) {
  19018. if ("development" !== 'production') {
  19019. errMsg = 'If `transform` declared, it should at least contain one transform.';
  19020. }
  19021. throwError(errMsg);
  19022. }
  19023. for (var i = 0, len = pipeLen; i < len; i++) {
  19024. var transOption = pipedTransOption[i];
  19025. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  19026. // piped transform only support single output, except the last one.
  19027. if (i !== len - 1) {
  19028. sourceList.length = Math.max(sourceList.length, 1);
  19029. }
  19030. }
  19031. return sourceList;
  19032. }
  19033. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  19034. pipeIndex) {
  19035. var errMsg = '';
  19036. if (!upSourceList.length) {
  19037. if ("development" !== 'production') {
  19038. errMsg = 'Must have at least one upstream dataset.';
  19039. }
  19040. throwError(errMsg);
  19041. }
  19042. if (!isObject(transOption)) {
  19043. if ("development" !== 'production') {
  19044. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  19045. }
  19046. throwError(errMsg);
  19047. }
  19048. var transType = transOption.type;
  19049. var externalTransform = externalTransformMap.get(transType);
  19050. if (!externalTransform) {
  19051. if ("development" !== 'production') {
  19052. errMsg = 'Can not find transform on type "' + transType + '".';
  19053. }
  19054. throwError(errMsg);
  19055. } // Prepare source
  19056. var extUpSourceList = map(upSourceList, function (upSource) {
  19057. return createExternalSource(upSource, externalTransform);
  19058. });
  19059. var resultList = normalizeToArray(externalTransform.transform({
  19060. upstream: extUpSourceList[0],
  19061. upstreamList: extUpSourceList,
  19062. config: clone(transOption.config)
  19063. }));
  19064. if ("development" !== 'production') {
  19065. if (transOption.print) {
  19066. var printStrArr = map(resultList, function (extSource) {
  19067. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  19068. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  19069. }).join('\n');
  19070. consoleLog(printStrArr);
  19071. }
  19072. }
  19073. return map(resultList, function (result, resultIndex) {
  19074. var errMsg = '';
  19075. if (!isObject(result)) {
  19076. if ("development" !== 'production') {
  19077. errMsg = 'A transform should not return some empty results.';
  19078. }
  19079. throwError(errMsg);
  19080. }
  19081. if (!result.data) {
  19082. if ("development" !== 'production') {
  19083. errMsg = 'Transform result data should be not be null or undefined';
  19084. }
  19085. throwError(errMsg);
  19086. }
  19087. var sourceFormat = detectSourceFormat(result.data);
  19088. if (!isSupportedSourceFormat(sourceFormat)) {
  19089. if ("development" !== 'production') {
  19090. errMsg = 'Transform result data should be array rows or object rows.';
  19091. }
  19092. throwError(errMsg);
  19093. }
  19094. var resultMetaRawOption;
  19095. var firstUpSource = upSourceList[0];
  19096. /**
  19097. * Intuitively, the end users known the content of the original `dataset.source`,
  19098. * calucating the transform result in mind.
  19099. * Suppose the original `dataset.source` is:
  19100. * ```js
  19101. * [
  19102. * ['product', '2012', '2013', '2014', '2015'],
  19103. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  19104. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  19105. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  19106. * ]
  19107. * ```
  19108. * The dimension info have to be detected from the source data.
  19109. * Some of the transformers (like filter, sort) will follow the dimension info
  19110. * of upstream, while others use new dimensions (like aggregate).
  19111. * Transformer can output a field `dimensions` to define the its own output dimensions.
  19112. * We also allow transformers to ignore the output `dimensions` field, and
  19113. * inherit the upstream dimensions definition. It can reduce the burden of handling
  19114. * dimensions in transformers.
  19115. *
  19116. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19117. */
  19118. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  19119. // dimensions definitions. We do not inherit anything from upstream.
  19120. && !result.dimensions) {
  19121. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result becuase:
  19122. // (1) The returned data always does not contain header line and can not be used
  19123. // as dimension-detection. In this case we can not use "detected dimensions" of
  19124. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  19125. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  19126. // So the original detected header should be add to the result, otherwise they can not be read.
  19127. if (startIndex) {
  19128. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  19129. }
  19130. resultMetaRawOption = {
  19131. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19132. sourceHeader: startIndex,
  19133. dimensions: firstUpSource.metaRawOption.dimensions
  19134. };
  19135. } else {
  19136. resultMetaRawOption = {
  19137. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19138. sourceHeader: 0,
  19139. dimensions: result.dimensions
  19140. };
  19141. }
  19142. return createSource(result.data, resultMetaRawOption, null, null);
  19143. });
  19144. }
  19145. function isSupportedSourceFormat(sourceFormat) {
  19146. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  19147. }
  19148. /**
  19149. * [REQUIREMENT_MEMO]:
  19150. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  19151. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  19152. * `root-dataset`. Them on `series` has higher priority.
  19153. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  19154. * confuse users: whether those props indicate how to visit the upstream source or visit
  19155. * the transform result source, and some transforms has nothing to do with these props,
  19156. * and some transforms might have multiple upstream.
  19157. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  19158. * declared in `root-dataset`.
  19159. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  19160. * That is for reducing complexity in transfroms.
  19161. * PENDING: Whether to provide transposition transform?
  19162. *
  19163. * [IMPLEMENTAION_MEMO]:
  19164. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  19165. * They will not be calculated until `source` is about to be visited (to prevent from
  19166. * duplicate calcuation). `source` is visited only in series and input to transforms.
  19167. *
  19168. * [DIMENSION_INHERIT_RULE]:
  19169. * By default the dimensions are inherited from ancestors, unless a transform return
  19170. * a new dimensions definition.
  19171. * Consider the case:
  19172. * ```js
  19173. * dataset: [{
  19174. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  19175. * }, {
  19176. * transform: { type: 'filter', ... }
  19177. * }]
  19178. * dataset: [{
  19179. * dimension: ['Product', 'Sales', 'Prise'],
  19180. * source: [ ['Cookies', 321, 44.21], ...]
  19181. * }, {
  19182. * transform: { type: 'filter', ... }
  19183. * }]
  19184. * ```
  19185. * The two types of option should have the same behavior after transform.
  19186. *
  19187. *
  19188. * [SCENARIO]:
  19189. * (1) Provide source data directly:
  19190. * ```js
  19191. * series: {
  19192. * encode: {...},
  19193. * dimensions: [...]
  19194. * seriesLayoutBy: 'row',
  19195. * data: [[...]]
  19196. * }
  19197. * ```
  19198. * (2) Series refer to dataset.
  19199. * ```js
  19200. * series: [{
  19201. * encode: {...}
  19202. * // Ignore datasetIndex means `datasetIndex: 0`
  19203. * // and the dimensions defination in dataset is used
  19204. * }, {
  19205. * encode: {...},
  19206. * seriesLayoutBy: 'column',
  19207. * datasetIndex: 1
  19208. * }]
  19209. * ```
  19210. * (3) dataset transform
  19211. * ```js
  19212. * dataset: [{
  19213. * source: [...]
  19214. * }, {
  19215. * source: [...]
  19216. * }, {
  19217. * // By default from 0.
  19218. * transform: { type: 'filter', config: {...} }
  19219. * }, {
  19220. * // Piped.
  19221. * transform: [
  19222. * { type: 'filter', config: {...} },
  19223. * { type: 'sort', config: {...} }
  19224. * ]
  19225. * }, {
  19226. * id: 'regressionData',
  19227. * fromDatasetIndex: 1,
  19228. * // Third-party transform
  19229. * transform: { type: 'ecStat:regression', config: {...} }
  19230. * }, {
  19231. * // retrieve the extra result.
  19232. * id: 'regressionFormula',
  19233. * fromDatasetId: 'regressionData',
  19234. * fromTransformResult: 1
  19235. * }]
  19236. * ```
  19237. */
  19238. var SourceManager =
  19239. /** @class */
  19240. function () {
  19241. function SourceManager(sourceHost) {
  19242. // Cached source. Do not repeat calculating if not dirty.
  19243. this._sourceList = []; // version sign of each upstream source manager.
  19244. this._upstreamSignList = [];
  19245. this._versionSignBase = 0;
  19246. this._sourceHost = sourceHost;
  19247. }
  19248. /**
  19249. * Mark dirty.
  19250. */
  19251. SourceManager.prototype.dirty = function () {
  19252. this._setLocalSource([], []);
  19253. };
  19254. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  19255. this._sourceList = sourceList;
  19256. this._upstreamSignList = upstreamSignList;
  19257. this._versionSignBase++;
  19258. if (this._versionSignBase > 9e10) {
  19259. this._versionSignBase = 0;
  19260. }
  19261. };
  19262. /**
  19263. * For detecting whether the upstream source is dirty, so that
  19264. * the local cached source (in `_sourceList`) should be discarded.
  19265. */
  19266. SourceManager.prototype._getVersionSign = function () {
  19267. return this._sourceHost.uid + '_' + this._versionSignBase;
  19268. };
  19269. /**
  19270. * Always return a source instance. Otherwise throw error.
  19271. */
  19272. SourceManager.prototype.prepareSource = function () {
  19273. // For the case that call `setOption` multiple time but no data changed,
  19274. // cache the result source to prevent from repeating transform.
  19275. if (this._isDirty()) {
  19276. this._createSource();
  19277. }
  19278. };
  19279. SourceManager.prototype._createSource = function () {
  19280. this._setLocalSource([], []);
  19281. var sourceHost = this._sourceHost;
  19282. var upSourceMgrList = this._getUpstreamSourceManagers();
  19283. var hasUpstream = !!upSourceMgrList.length;
  19284. var resultSourceList;
  19285. var upstreamSignList;
  19286. if (isSeries(sourceHost)) {
  19287. var seriesModel = sourceHost;
  19288. var data = void 0;
  19289. var sourceFormat = void 0;
  19290. var upSource = void 0; // Has upstream dataset
  19291. if (hasUpstream) {
  19292. var upSourceMgr = upSourceMgrList[0];
  19293. upSourceMgr.prepareSource();
  19294. upSource = upSourceMgr.getSource();
  19295. data = upSource.data;
  19296. sourceFormat = upSource.sourceFormat;
  19297. upstreamSignList = [upSourceMgr._getVersionSign()];
  19298. } // Series data is from own.
  19299. else {
  19300. data = seriesModel.get('data', true);
  19301. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  19302. upstreamSignList = [];
  19303. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  19304. var newMetaRawOption = this._getSourceMetaRawOption();
  19305. var upMetaRawOption = upSource ? upSource.metaRawOption : null;
  19306. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption ? upMetaRawOption.seriesLayoutBy : null);
  19307. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption ? upMetaRawOption.sourceHeader : null); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  19308. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  19309. // but series need `seriesLayoutBy: 'row'`.
  19310. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption ? upMetaRawOption.dimensions : null);
  19311. resultSourceList = [createSource(data, {
  19312. seriesLayoutBy: seriesLayoutBy,
  19313. sourceHeader: sourceHeader,
  19314. dimensions: dimensions
  19315. }, sourceFormat, seriesModel.get('encode', true))];
  19316. } else {
  19317. var datasetModel = sourceHost; // Has upstream dataset.
  19318. if (hasUpstream) {
  19319. var result = this._applyTransform(upSourceMgrList);
  19320. resultSourceList = result.sourceList;
  19321. upstreamSignList = result.upstreamSignList;
  19322. } // Is root dataset.
  19323. else {
  19324. var sourceData = datasetModel.get('source', true);
  19325. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null, // Note: dataset option does not have `encode`.
  19326. null)];
  19327. upstreamSignList = [];
  19328. }
  19329. }
  19330. if ("development" !== 'production') {
  19331. assert(resultSourceList && upstreamSignList);
  19332. }
  19333. this._setLocalSource(resultSourceList, upstreamSignList);
  19334. };
  19335. SourceManager.prototype._applyTransform = function (upMgrList) {
  19336. var datasetModel = this._sourceHost;
  19337. var transformOption = datasetModel.get('transform', true);
  19338. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  19339. if ("development" !== 'production') {
  19340. assert(fromTransformResult != null || transformOption != null);
  19341. }
  19342. if (fromTransformResult != null) {
  19343. var errMsg = '';
  19344. if (upMgrList.length !== 1) {
  19345. if ("development" !== 'production') {
  19346. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  19347. }
  19348. doThrow(errMsg);
  19349. }
  19350. }
  19351. var sourceList;
  19352. var upSourceList = [];
  19353. var upstreamSignList = [];
  19354. each(upMgrList, function (upMgr) {
  19355. upMgr.prepareSource();
  19356. var upSource = upMgr.getSource(fromTransformResult || 0);
  19357. var errMsg = '';
  19358. if (fromTransformResult != null && !upSource) {
  19359. if ("development" !== 'production') {
  19360. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  19361. }
  19362. doThrow(errMsg);
  19363. }
  19364. upSourceList.push(upSource);
  19365. upstreamSignList.push(upMgr._getVersionSign());
  19366. });
  19367. if (transformOption) {
  19368. sourceList = applyDataTransform(transformOption, upSourceList, {
  19369. datasetIndex: datasetModel.componentIndex
  19370. });
  19371. } else if (fromTransformResult != null) {
  19372. sourceList = [cloneSourceShallow(upSourceList[0])];
  19373. }
  19374. return {
  19375. sourceList: sourceList,
  19376. upstreamSignList: upstreamSignList
  19377. };
  19378. };
  19379. SourceManager.prototype._isDirty = function () {
  19380. var sourceList = this._sourceList;
  19381. if (!sourceList.length) {
  19382. return true;
  19383. } // All sourceList is from the some upsteam.
  19384. var upSourceMgrList = this._getUpstreamSourceManagers();
  19385. for (var i = 0; i < upSourceMgrList.length; i++) {
  19386. var upSrcMgr = upSourceMgrList[i];
  19387. if ( // Consider the case that there is ancestor diry, call it recursively.
  19388. // The performance is probably not an issue because usually the chain is not long.
  19389. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  19390. return true;
  19391. }
  19392. }
  19393. };
  19394. /**
  19395. * @param sourceIndex By defualt 0, means "main source".
  19396. * Most cases there is only one source.
  19397. */
  19398. SourceManager.prototype.getSource = function (sourceIndex) {
  19399. return this._sourceList[sourceIndex || 0];
  19400. };
  19401. /**
  19402. * PEDING: Is it fast enough?
  19403. * If no upstream, return empty array.
  19404. */
  19405. SourceManager.prototype._getUpstreamSourceManagers = function () {
  19406. // Always get the relationship from the raw option.
  19407. // Do not cache the link of the dependency graph, so that
  19408. // no need to update them when change happen.
  19409. var sourceHost = this._sourceHost;
  19410. if (isSeries(sourceHost)) {
  19411. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  19412. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  19413. } else {
  19414. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  19415. return datasetModel.getSourceManager();
  19416. });
  19417. }
  19418. };
  19419. SourceManager.prototype._getSourceMetaRawOption = function () {
  19420. var sourceHost = this._sourceHost;
  19421. var seriesLayoutBy;
  19422. var sourceHeader;
  19423. var dimensions;
  19424. if (isSeries(sourceHost)) {
  19425. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  19426. sourceHeader = sourceHost.get('sourceHeader', true);
  19427. dimensions = sourceHost.get('dimensions', true);
  19428. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  19429. else if (!this._getUpstreamSourceManagers().length) {
  19430. var model = sourceHost;
  19431. seriesLayoutBy = model.get('seriesLayoutBy', true);
  19432. sourceHeader = model.get('sourceHeader', true);
  19433. dimensions = model.get('dimensions', true);
  19434. }
  19435. return {
  19436. seriesLayoutBy: seriesLayoutBy,
  19437. sourceHeader: sourceHeader,
  19438. dimensions: dimensions
  19439. };
  19440. };
  19441. return SourceManager;
  19442. }();
  19443. // disable the transform merge, but do not disable transfrom clone from rawOption.
  19444. function disableTransformOptionMerge(datasetModel) {
  19445. var transformOption = datasetModel.option.transform;
  19446. transformOption && setAsPrimitive(datasetModel.option.transform);
  19447. }
  19448. function isSeries(sourceHost) {
  19449. // Avoid circular dependency with Series.ts
  19450. return sourceHost.mainType === 'series';
  19451. }
  19452. function doThrow(errMsg) {
  19453. throw new Error(errMsg);
  19454. }
  19455. function createTooltipMarkup(type, option) {
  19456. option.type = type;
  19457. return option;
  19458. }
  19459. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  19460. var style = series.getData().getItemVisual(dataIndex, 'style');
  19461. var color = style[series.visualDrawType];
  19462. return convertToColorString(color);
  19463. }
  19464. function defaultSeriesFormatTooltip(opt) {
  19465. var series = opt.series;
  19466. var dataIndex = opt.dataIndex;
  19467. var multipleSeries = opt.multipleSeries;
  19468. var data = series.getData();
  19469. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  19470. var tooltipDimLen = tooltipDims.length;
  19471. var value = series.getRawValue(dataIndex);
  19472. var isValueArr = isArray(value);
  19473. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  19474. var inlineValue;
  19475. var inlineValueType;
  19476. var subBlocks;
  19477. var sortParam;
  19478. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  19479. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  19480. inlineValue = formatArrResult.inlineValues;
  19481. inlineValueType = formatArrResult.inlineValueTypes;
  19482. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  19483. sortParam = formatArrResult.inlineValues[0];
  19484. } else if (tooltipDimLen) {
  19485. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  19486. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  19487. inlineValueType = dimInfo.type;
  19488. } else {
  19489. sortParam = inlineValue = isValueArr ? value[0] : value;
  19490. } // Do not show generated series name. It might not be readable.
  19491. var seriesNameSpecified = isNameSpecified(series);
  19492. var seriesName = seriesNameSpecified && series.name || '';
  19493. var itemName = data.getName(dataIndex);
  19494. var inlineName = multipleSeries ? seriesName : itemName;
  19495. return createTooltipMarkup('section', {
  19496. header: seriesName,
  19497. // When series name not specified, do not show a header line with only '-'.
  19498. // This case alway happen in tooltip.trigger: 'item'.
  19499. noHeader: multipleSeries || !seriesNameSpecified,
  19500. sortParam: sortParam,
  19501. blocks: [createTooltipMarkup('nameValue', {
  19502. markerType: 'item',
  19503. markerColor: markerColor,
  19504. // Do not mix display seriesName and itemName in one tooltip,
  19505. // which might confuses users.
  19506. name: inlineName,
  19507. // name dimension might be auto assigned, where the name might
  19508. // be not readable. So we check trim here.
  19509. noName: !trim(inlineName),
  19510. value: inlineValue,
  19511. valueType: inlineValueType
  19512. })].concat(subBlocks || [])
  19513. });
  19514. }
  19515. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  19516. // check: category-no-encode-has-axis-data in dataset.html
  19517. var data = series.getData();
  19518. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  19519. var dimItem = data.getDimensionInfo(idx);
  19520. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19521. }, false);
  19522. var inlineValues = [];
  19523. var inlineValueTypes = [];
  19524. var blocks = [];
  19525. tooltipDims.length ? each(tooltipDims, function (dim) {
  19526. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19527. }) // By default, all dims is used on tooltip.
  19528. : each(value, setEachItem);
  19529. function setEachItem(val, dim) {
  19530. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  19531. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19532. return;
  19533. }
  19534. if (isValueMultipleLine) {
  19535. blocks.push(createTooltipMarkup('nameValue', {
  19536. markerType: 'subItem',
  19537. markerColor: colorStr,
  19538. name: dimInfo.displayName,
  19539. value: val,
  19540. valueType: dimInfo.type
  19541. }));
  19542. } else {
  19543. inlineValues.push(val);
  19544. inlineValueTypes.push(dimInfo.type);
  19545. }
  19546. }
  19547. return {
  19548. inlineValues: inlineValues,
  19549. inlineValueTypes: inlineValueTypes,
  19550. blocks: blocks
  19551. };
  19552. }
  19553. var inner$1 = makeInner();
  19554. function getSelectionKey(data, dataIndex) {
  19555. return data.getName(dataIndex) || data.getId(dataIndex);
  19556. }
  19557. var SeriesModel =
  19558. /** @class */
  19559. function (_super) {
  19560. __extends(SeriesModel, _super);
  19561. function SeriesModel() {
  19562. // [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`,
  19563. // the class members must not be initialized in constructor or declaration place.
  19564. // Otherwise there is bad case:
  19565. // class A {xxx = 1;}
  19566. // enableClassExtend(A);
  19567. // class B extends A {}
  19568. // var C = B.extend({xxx: 5});
  19569. // var c = new C();
  19570. // console.log(c.xxx); // expect 5 but always 1.
  19571. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  19572. // Props about data selection
  19573. // ---------------------------------------
  19574. _this._selectedDataIndicesMap = {};
  19575. return _this;
  19576. }
  19577. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  19578. this.seriesIndex = this.componentIndex;
  19579. this.dataTask = createTask({
  19580. count: dataTaskCount,
  19581. reset: dataTaskReset
  19582. });
  19583. this.dataTask.context = {
  19584. model: this
  19585. };
  19586. this.mergeDefaultAndTheme(option, ecModel);
  19587. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  19588. sourceManager.prepareSource();
  19589. var data = this.getInitialData(option, ecModel);
  19590. wrapData(data, this);
  19591. this.dataTask.context.data = data;
  19592. if ("development" !== 'production') {
  19593. assert(data, 'getInitialData returned invalid data.');
  19594. }
  19595. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  19596. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19597. // cause data.graph.data !== data when using
  19598. // module:echarts/data/Graph or module:echarts/data/Tree.
  19599. // See module:echarts/data/helper/linkList
  19600. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19601. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19602. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19603. // Call `seriesModel.getRawData()` instead.
  19604. // this.restoreData();
  19605. autoSeriesName(this);
  19606. this._initSelectedMapFromData(data);
  19607. };
  19608. /**
  19609. * Util for merge default and theme to option
  19610. */
  19611. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  19612. var layoutMode = fetchLayoutMode(this);
  19613. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  19614. // But if name duplicate between series subType
  19615. // (for example: parallel) add component mainType,
  19616. // add suffix 'Series'.
  19617. var themeSubType = this.subType;
  19618. if (ComponentModel.hasClass(themeSubType)) {
  19619. themeSubType += 'Series';
  19620. }
  19621. merge(option, ecModel.getTheme().get(this.subType));
  19622. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  19623. defaultEmphasis(option, 'label', ['show']);
  19624. this.fillDataTextStyle(option.data);
  19625. if (layoutMode) {
  19626. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19627. }
  19628. };
  19629. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  19630. // this.settingTask.dirty();
  19631. newSeriesOption = merge(this.option, newSeriesOption, true);
  19632. this.fillDataTextStyle(newSeriesOption.data);
  19633. var layoutMode = fetchLayoutMode(this);
  19634. if (layoutMode) {
  19635. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19636. }
  19637. var sourceManager = inner$1(this).sourceManager;
  19638. sourceManager.dirty();
  19639. sourceManager.prepareSource();
  19640. var data = this.getInitialData(newSeriesOption, ecModel);
  19641. wrapData(data, this);
  19642. this.dataTask.dirty();
  19643. this.dataTask.context.data = data;
  19644. inner$1(this).dataBeforeProcessed = data;
  19645. autoSeriesName(this);
  19646. this._initSelectedMapFromData(data);
  19647. };
  19648. SeriesModel.prototype.fillDataTextStyle = function (data) {
  19649. // Default data label emphasis `show`
  19650. // FIXME Tree structure data ?
  19651. // FIXME Performance ?
  19652. if (data && !isTypedArray(data)) {
  19653. var props = ['show'];
  19654. for (var i = 0; i < data.length; i++) {
  19655. if (data[i] && data[i].label) {
  19656. defaultEmphasis(data[i], 'label', props);
  19657. }
  19658. }
  19659. }
  19660. };
  19661. /**
  19662. * Init a data structure from data related option in series
  19663. * Must be overriden.
  19664. */
  19665. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  19666. return;
  19667. };
  19668. /**
  19669. * Append data to list
  19670. */
  19671. SeriesModel.prototype.appendData = function (params) {
  19672. // FIXME ???
  19673. // (1) If data from dataset, forbidden append.
  19674. // (2) support append data of dataset.
  19675. var data = this.getRawData();
  19676. data.appendData(params.data);
  19677. };
  19678. /**
  19679. * Consider some method like `filter`, `map` need make new data,
  19680. * We should make sure that `seriesModel.getData()` get correct
  19681. * data in the stream procedure. So we fetch data from upstream
  19682. * each time `task.perform` called.
  19683. */
  19684. SeriesModel.prototype.getData = function (dataType) {
  19685. var task = getCurrentTask(this);
  19686. if (task) {
  19687. var data = task.context.data;
  19688. return dataType == null ? data : data.getLinkedData(dataType);
  19689. } else {
  19690. // When series is not alive (that may happen when click toolbox
  19691. // restore or setOption with not merge mode), series data may
  19692. // be still need to judge animation or something when graphic
  19693. // elements want to know whether fade out.
  19694. return inner$1(this).data;
  19695. }
  19696. };
  19697. SeriesModel.prototype.getAllData = function () {
  19698. var mainData = this.getData();
  19699. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  19700. data: mainData
  19701. }];
  19702. };
  19703. SeriesModel.prototype.setData = function (data) {
  19704. var task = getCurrentTask(this);
  19705. if (task) {
  19706. var context = task.context; // Consider case: filter, data sample.
  19707. // FIXME:TS never used, so comment it
  19708. // if (context.data !== data && task.modifyOutputEnd) {
  19709. // task.setOutputEnd(data.count());
  19710. // }
  19711. context.outputData = data; // Caution: setData should update context.data,
  19712. // Because getData may be called multiply in a
  19713. // single stage and expect to get the data just
  19714. // set. (For example, AxisProxy, x y both call
  19715. // getData and setDate sequentially).
  19716. // So the context.data should be fetched from
  19717. // upstream each time when a stage starts to be
  19718. // performed.
  19719. if (task !== this.dataTask) {
  19720. context.data = data;
  19721. }
  19722. }
  19723. inner$1(this).data = data;
  19724. };
  19725. SeriesModel.prototype.getSource = function () {
  19726. return inner$1(this).sourceManager.getSource();
  19727. };
  19728. /**
  19729. * Get data before processed
  19730. */
  19731. SeriesModel.prototype.getRawData = function () {
  19732. return inner$1(this).dataBeforeProcessed;
  19733. };
  19734. /**
  19735. * Get base axis if has coordinate system and has axis.
  19736. * By default use coordSys.getBaseAxis();
  19737. * Can be overrided for some chart.
  19738. * @return {type} description
  19739. */
  19740. SeriesModel.prototype.getBaseAxis = function () {
  19741. var coordSys = this.coordinateSystem; // @ts-ignore
  19742. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19743. };
  19744. /**
  19745. * Default tooltip formatter
  19746. *
  19747. * @param dataIndex
  19748. * @param multipleSeries
  19749. * @param dataType
  19750. * @param renderMode valid values: 'html'(by default) and 'richText'.
  19751. * 'html' is used for rendering tooltip in extra DOM form, and the result
  19752. * string is used as DOM HTML content.
  19753. * 'richText' is used for rendering tooltip in rich text form, for those where
  19754. * DOM operation is not supported.
  19755. * @return formatted tooltip with `html` and `markers`
  19756. * Notice: The override method can also return string
  19757. */
  19758. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19759. return defaultSeriesFormatTooltip({
  19760. series: this,
  19761. dataIndex: dataIndex,
  19762. multipleSeries: multipleSeries
  19763. });
  19764. };
  19765. SeriesModel.prototype.isAnimationEnabled = function () {
  19766. if (env.node) {
  19767. return false;
  19768. }
  19769. var animationEnabled = this.getShallow('animation');
  19770. if (animationEnabled) {
  19771. if (this.getData().count() > this.getShallow('animationThreshold')) {
  19772. animationEnabled = false;
  19773. }
  19774. }
  19775. return !!animationEnabled;
  19776. };
  19777. SeriesModel.prototype.restoreData = function () {
  19778. this.dataTask.dirty();
  19779. };
  19780. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  19781. var ecModel = this.ecModel; // PENDING
  19782. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  19783. if (!color) {
  19784. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  19785. }
  19786. return color;
  19787. };
  19788. /**
  19789. * Use `data.mapDimensionsAll(coordDim)` instead.
  19790. * @deprecated
  19791. */
  19792. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  19793. return this.getRawData().mapDimensionsAll(coordDim);
  19794. };
  19795. /**
  19796. * Get progressive rendering count each step
  19797. */
  19798. SeriesModel.prototype.getProgressive = function () {
  19799. return this.get('progressive');
  19800. };
  19801. /**
  19802. * Get progressive rendering count each step
  19803. */
  19804. SeriesModel.prototype.getProgressiveThreshold = function () {
  19805. return this.get('progressiveThreshold');
  19806. }; // PENGING If selectedMode is null ?
  19807. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  19808. this._innerSelect(this.getData(dataType), innerDataIndices);
  19809. };
  19810. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  19811. var selectedMap = this.option.selectedMap;
  19812. if (!selectedMap) {
  19813. return;
  19814. }
  19815. var data = this.getData(dataType);
  19816. for (var i = 0; i < innerDataIndices.length; i++) {
  19817. var dataIndex = innerDataIndices[i];
  19818. var nameOrId = getSelectionKey(data, dataIndex);
  19819. selectedMap[nameOrId] = false;
  19820. this._selectedDataIndicesMap[nameOrId] = -1;
  19821. }
  19822. };
  19823. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  19824. var tmpArr = [];
  19825. for (var i = 0; i < innerDataIndices.length; i++) {
  19826. tmpArr[0] = innerDataIndices[i];
  19827. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  19828. }
  19829. };
  19830. SeriesModel.prototype.getSelectedDataIndices = function () {
  19831. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  19832. var nameOrIds = keys(selectedDataIndicesMap);
  19833. var dataIndices = [];
  19834. for (var i = 0; i < nameOrIds.length; i++) {
  19835. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  19836. if (dataIndex >= 0) {
  19837. dataIndices.push(dataIndex);
  19838. }
  19839. }
  19840. return dataIndices;
  19841. };
  19842. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  19843. var selectedMap = this.option.selectedMap;
  19844. if (!selectedMap) {
  19845. return false;
  19846. }
  19847. var data = this.getData(dataType);
  19848. var nameOrId = getSelectionKey(data, dataIndex);
  19849. return selectedMap[nameOrId] || false;
  19850. };
  19851. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  19852. var _a, _b;
  19853. var selectedMode = this.option.selectedMode;
  19854. var len = innerDataIndices.length;
  19855. if (!selectedMode || !len) {
  19856. return;
  19857. }
  19858. if (selectedMode === 'multiple') {
  19859. var selectedMap = this.option.selectedMap || (this.option.selectedMap = {});
  19860. for (var i = 0; i < len; i++) {
  19861. var dataIndex = innerDataIndices[i]; // TODO diffrent types of data share same object.
  19862. var nameOrId = getSelectionKey(data, dataIndex);
  19863. selectedMap[nameOrId] = true;
  19864. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  19865. }
  19866. } else if (selectedMode === 'single' || selectedMode === true) {
  19867. var lastDataIndex = innerDataIndices[len - 1];
  19868. var nameOrId = getSelectionKey(data, lastDataIndex);
  19869. this.option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  19870. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  19871. }
  19872. };
  19873. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  19874. // Ignore select info in data if selectedMap exists.
  19875. // NOTE It's only for legacy usage. edge data is not supported.
  19876. if (this.option.selectedMap) {
  19877. return;
  19878. }
  19879. var dataIndices = [];
  19880. if (data.hasItemOption) {
  19881. data.each(function (idx) {
  19882. var rawItem = data.getRawDataItem(idx);
  19883. if (typeof rawItem === 'object' && rawItem.selected) {
  19884. dataIndices.push(idx);
  19885. }
  19886. });
  19887. }
  19888. if (dataIndices.length > 0) {
  19889. this._innerSelect(data, dataIndices);
  19890. }
  19891. }; // /**
  19892. // * @see {module:echarts/stream/Scheduler}
  19893. // */
  19894. // abstract pipeTask: null
  19895. SeriesModel.registerClass = function (clz) {
  19896. return ComponentModel.registerClass(clz);
  19897. };
  19898. SeriesModel.protoInitialize = function () {
  19899. var proto = SeriesModel.prototype;
  19900. proto.type = 'series.__base__';
  19901. proto.seriesIndex = 0;
  19902. proto.useColorPaletteOnData = false;
  19903. proto.ignoreStyleOnData = false;
  19904. proto.hasSymbolVisual = false;
  19905. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  19906. proto.visualStyleAccessPath = 'itemStyle';
  19907. proto.visualDrawType = 'fill';
  19908. }();
  19909. return SeriesModel;
  19910. }(ComponentModel);
  19911. mixin(SeriesModel, DataFormatMixin);
  19912. mixin(SeriesModel, PaletteMixin);
  19913. mountExtend(SeriesModel, ComponentModel);
  19914. /**
  19915. * MUST be called after `prepareSource` called
  19916. * Here we need to make auto series, especially for auto legend. But we
  19917. * do not modify series.name in option to avoid side effects.
  19918. */
  19919. function autoSeriesName(seriesModel) {
  19920. // User specified name has higher priority, otherwise it may cause
  19921. // series can not be queried unexpectedly.
  19922. var name = seriesModel.name;
  19923. if (!isNameSpecified(seriesModel)) {
  19924. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  19925. }
  19926. }
  19927. function getSeriesAutoName(seriesModel) {
  19928. var data = seriesModel.getRawData();
  19929. var dataDims = data.mapDimensionsAll('seriesName');
  19930. var nameArr = [];
  19931. each(dataDims, function (dataDim) {
  19932. var dimInfo = data.getDimensionInfo(dataDim);
  19933. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  19934. });
  19935. return nameArr.join(' ');
  19936. }
  19937. function dataTaskCount(context) {
  19938. return context.model.getRawData().count();
  19939. }
  19940. function dataTaskReset(context) {
  19941. var seriesModel = context.model;
  19942. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  19943. return dataTaskProgress;
  19944. }
  19945. function dataTaskProgress(param, context) {
  19946. // Avoid repead cloneShallow when data just created in reset.
  19947. if (context.outputData && param.end > context.outputData.count()) {
  19948. context.model.getRawData().cloneShallow(context.outputData);
  19949. }
  19950. } // TODO refactor
  19951. function wrapData(data, seriesModel) {
  19952. each(__spreadArrays(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  19953. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  19954. });
  19955. }
  19956. function onDataChange(seriesModel, newList) {
  19957. var task = getCurrentTask(seriesModel);
  19958. if (task) {
  19959. // Consider case: filter, selectRange
  19960. task.setOutputEnd((newList || this).count());
  19961. }
  19962. return newList;
  19963. }
  19964. function getCurrentTask(seriesModel) {
  19965. var scheduler = (seriesModel.ecModel || {}).scheduler;
  19966. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  19967. if (pipeline) {
  19968. // When pipline finished, the currrentTask keep the last
  19969. // task (renderTask).
  19970. var task = pipeline.currentTask;
  19971. if (task) {
  19972. var agentStubMap = task.agentStubMap;
  19973. if (agentStubMap) {
  19974. task = agentStubMap.get(seriesModel.uid);
  19975. }
  19976. }
  19977. return task;
  19978. }
  19979. }
  19980. var ComponentView =
  19981. /** @class */
  19982. function () {
  19983. function ComponentView() {
  19984. this.group = new Group();
  19985. this.uid = getUID('viewComponent');
  19986. }
  19987. ComponentView.prototype.init = function (ecModel, api) {};
  19988. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  19989. ComponentView.prototype.dispose = function (ecModel, api) {};
  19990. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  19991. };
  19992. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  19993. };
  19994. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  19995. };
  19996. /**
  19997. * Hook for blur target series.
  19998. * Can be used in marker for blur the markers
  19999. */
  20000. ComponentView.prototype.blurSeries = function (seriesModels, ecModel) {// Do nothing;
  20001. };
  20002. return ComponentView;
  20003. }();
  20004. enableClassExtend(ComponentView);
  20005. enableClassManagement(ComponentView);
  20006. /**
  20007. * @return {string} If large mode changed, return string 'reset';
  20008. */
  20009. function createRenderPlanner() {
  20010. var inner = makeInner();
  20011. return function (seriesModel) {
  20012. var fields = inner(seriesModel);
  20013. var pipelineContext = seriesModel.pipelineContext;
  20014. var originalLarge = !!fields.large;
  20015. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  20016. // exists. See #11611 . Probably we need to modify this structure, see the comment
  20017. // on `performRawSeries` in `Schedular.js`.
  20018. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  20019. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  20020. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  20021. };
  20022. }
  20023. var inner$2 = makeInner();
  20024. var renderPlanner = createRenderPlanner();
  20025. var ChartView =
  20026. /** @class */
  20027. function () {
  20028. function ChartView() {
  20029. this.group = new Group();
  20030. this.uid = getUID('viewChart');
  20031. this.renderTask = createTask({
  20032. plan: renderTaskPlan,
  20033. reset: renderTaskReset
  20034. });
  20035. this.renderTask.context = {
  20036. view: this
  20037. };
  20038. }
  20039. ChartView.prototype.init = function (ecModel, api) {};
  20040. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {};
  20041. /**
  20042. * Highlight series or specified data item.
  20043. */
  20044. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  20045. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20046. };
  20047. /**
  20048. * Downplay series or specified data item.
  20049. */
  20050. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  20051. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20052. };
  20053. /**
  20054. * Remove self.
  20055. */
  20056. ChartView.prototype.remove = function (ecModel, api) {
  20057. this.group.removeAll();
  20058. };
  20059. /**
  20060. * Dispose self.
  20061. */
  20062. ChartView.prototype.dispose = function (ecModel, api) {};
  20063. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  20064. this.render(seriesModel, ecModel, api, payload);
  20065. }; // FIXME never used?
  20066. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  20067. this.render(seriesModel, ecModel, api, payload);
  20068. }; // FIXME never used?
  20069. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  20070. this.render(seriesModel, ecModel, api, payload);
  20071. };
  20072. ChartView.markUpdateMethod = function (payload, methodName) {
  20073. inner$2(payload).updateMethod = methodName;
  20074. };
  20075. ChartView.protoInitialize = function () {
  20076. var proto = ChartView.prototype;
  20077. proto.type = 'chart';
  20078. }();
  20079. return ChartView;
  20080. }();
  20081. /**
  20082. * Set state of single element
  20083. */
  20084. function elSetState(el, state, highlightDigit) {
  20085. if (el) {
  20086. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  20087. }
  20088. }
  20089. function toggleHighlight(data, payload, state) {
  20090. var dataIndex = queryDataIndex(data, payload);
  20091. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  20092. if (dataIndex != null) {
  20093. each(normalizeToArray(dataIndex), function (dataIdx) {
  20094. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  20095. });
  20096. } else {
  20097. data.eachItemGraphicEl(function (el) {
  20098. elSetState(el, state, highlightDigit);
  20099. });
  20100. }
  20101. }
  20102. enableClassExtend(ChartView, ['dispose']);
  20103. enableClassManagement(ChartView);
  20104. function renderTaskPlan(context) {
  20105. return renderPlanner(context.model);
  20106. }
  20107. function renderTaskReset(context) {
  20108. var seriesModel = context.model;
  20109. var ecModel = context.ecModel;
  20110. var api = context.api;
  20111. var payload = context.payload; // FIXME: remove updateView updateVisual
  20112. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20113. var view = context.view;
  20114. var updateMethod = payload && inner$2(payload).updateMethod;
  20115. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  20116. // is less than progressive threshold.
  20117. : 'render';
  20118. if (methodName !== 'render') {
  20119. view[methodName](seriesModel, ecModel, api, payload);
  20120. }
  20121. return progressMethodMap[methodName];
  20122. }
  20123. var progressMethodMap = {
  20124. incrementalPrepareRender: {
  20125. progress: function (params, context) {
  20126. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  20127. }
  20128. },
  20129. render: {
  20130. // Put view.render in `progress` to support appendData. But in this case
  20131. // view.render should not be called in reset, otherwise it will be called
  20132. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20133. // in any cases.
  20134. forceFirstProgress: true,
  20135. progress: function (params, context) {
  20136. context.view.render(context.model, context.ecModel, context.api, context.payload);
  20137. }
  20138. }
  20139. };
  20140. /**
  20141. * @public
  20142. * @param {(Function)} fn
  20143. * @param {number} [delay=0] Unit: ms.
  20144. * @param {boolean} [debounce=false]
  20145. * true: If call interval less than `delay`, only the last call works.
  20146. * false: If call interval less than `delay, call works on fixed rate.
  20147. * @return {(Function)} throttled fn.
  20148. */
  20149. function throttle(fn, delay, debounce) {
  20150. var currCall;
  20151. var lastCall = 0;
  20152. var lastExec = 0;
  20153. var timer = null;
  20154. var diff;
  20155. var scope;
  20156. var args;
  20157. var debounceNextCall;
  20158. delay = delay || 0;
  20159. function exec() {
  20160. lastExec = new Date().getTime();
  20161. timer = null;
  20162. fn.apply(scope, args || []);
  20163. }
  20164. var cb = function () {
  20165. var cbArgs = [];
  20166. for (var _i = 0; _i < arguments.length; _i++) {
  20167. cbArgs[_i] = arguments[_i];
  20168. }
  20169. currCall = new Date().getTime();
  20170. scope = this;
  20171. args = cbArgs;
  20172. var thisDelay = debounceNextCall || delay;
  20173. var thisDebounce = debounceNextCall || debounce;
  20174. debounceNextCall = null;
  20175. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20176. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  20177. // than a new call of `cb`, that is, preserving the command order. Consider
  20178. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20179. // happens, either the `exec` is called dierectly, or the call is delayed.
  20180. // But the delayed call should never be later than next call of `cb`. Under
  20181. // this assurance, we can simply update view state each time `dispatchAction`
  20182. // triggered by user roaming, but not need to add extra code to avoid the
  20183. // state being "rolled-back".
  20184. if (thisDebounce) {
  20185. timer = setTimeout(exec, thisDelay);
  20186. } else {
  20187. if (diff >= 0) {
  20188. exec();
  20189. } else {
  20190. timer = setTimeout(exec, -diff);
  20191. }
  20192. }
  20193. lastCall = currCall;
  20194. };
  20195. /**
  20196. * Clear throttle.
  20197. * @public
  20198. */
  20199. cb.clear = function () {
  20200. if (timer) {
  20201. clearTimeout(timer);
  20202. timer = null;
  20203. }
  20204. };
  20205. /**
  20206. * Enable debounce once.
  20207. */
  20208. cb.debounceNextCall = function (debounceDelay) {
  20209. debounceNextCall = debounceDelay;
  20210. };
  20211. return cb;
  20212. }
  20213. var inner$3 = makeInner();
  20214. var defaultStyleMappers = {
  20215. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  20216. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  20217. };
  20218. var defaultColorKey = {
  20219. lineStyle: 'stroke',
  20220. itemStyle: 'fill'
  20221. };
  20222. function getStyleMapper(seriesModel, stylePath) {
  20223. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  20224. if (!styleMapper) {
  20225. console.warn("Unkown style type '" + stylePath + "'.");
  20226. return defaultStyleMappers.itemStyle;
  20227. }
  20228. return styleMapper;
  20229. }
  20230. function getDefaultColorKey(seriesModel, stylePath) {
  20231. // return defaultColorKey[stylePath] ||
  20232. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  20233. if (!colorKey) {
  20234. console.warn("Unkown style type '" + stylePath + "'.");
  20235. return 'fill';
  20236. }
  20237. return colorKey;
  20238. }
  20239. var seriesStyleTask = {
  20240. createOnAllSeries: true,
  20241. performRawSeries: true,
  20242. reset: function (seriesModel, ecModel) {
  20243. var data = seriesModel.getData();
  20244. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  20245. var styleModel = seriesModel.getModel(stylePath);
  20246. var getStyle = getStyleMapper(seriesModel, stylePath);
  20247. var globalStyle = getStyle(styleModel);
  20248. var decalOption = styleModel.getShallow('decal');
  20249. if (decalOption) {
  20250. data.setVisual('decal', decalOption);
  20251. decalOption.dirty = true;
  20252. } // TODO
  20253. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  20254. var color = globalStyle[colorKey]; // TODO style callback
  20255. var colorCallback = isFunction(color) ? color : null; // Get from color palette by default.
  20256. if (!globalStyle[colorKey] || colorCallback) {
  20257. // Note: if some series has color specified (e.g., by itemStyle.color), we DO NOT
  20258. // make it effect palette. Bacause some scenarios users need to make some series
  20259. // transparent or as background, which should better not effect the palette.
  20260. globalStyle[colorKey] = seriesModel.getColorFromPalette( // TODO series count changed.
  20261. seriesModel.name, null, ecModel.getSeriesCount());
  20262. data.setVisual('colorFromPalette', true);
  20263. }
  20264. data.setVisual('style', globalStyle);
  20265. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  20266. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  20267. data.setVisual('colorFromPalette', false);
  20268. return {
  20269. dataEach: function (data, idx) {
  20270. var dataParams = seriesModel.getDataParams(idx);
  20271. var itemStyle = extend({}, globalStyle);
  20272. itemStyle[colorKey] = colorCallback(dataParams);
  20273. data.setItemVisual(idx, 'style', itemStyle);
  20274. }
  20275. };
  20276. }
  20277. }
  20278. };
  20279. var sharedModel = new Model();
  20280. var dataStyleTask = {
  20281. createOnAllSeries: true,
  20282. performRawSeries: true,
  20283. reset: function (seriesModel, ecModel) {
  20284. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  20285. return;
  20286. }
  20287. var data = seriesModel.getData();
  20288. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  20289. var getStyle = getStyleMapper(seriesModel, stylePath);
  20290. var colorKey = data.getVisual('drawType');
  20291. return {
  20292. dataEach: data.hasItemOption ? function (data, idx) {
  20293. // Not use getItemModel for performance considuration
  20294. var rawItem = data.getRawDataItem(idx);
  20295. if (rawItem && rawItem[stylePath]) {
  20296. sharedModel.option = rawItem[stylePath];
  20297. var style = getStyle(sharedModel);
  20298. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  20299. extend(existsStyle, style);
  20300. if (sharedModel.option.decal) {
  20301. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  20302. sharedModel.option.decal.dirty = true;
  20303. }
  20304. if (colorKey in style) {
  20305. data.setItemVisual(idx, 'colorFromPalette', false);
  20306. }
  20307. }
  20308. } : null
  20309. };
  20310. }
  20311. }; // Pick color from palette for the data which has not been set with color yet.
  20312. // Note: do not support stream rendering. No such cases yet.
  20313. var dataColorPaletteTask = {
  20314. performRawSeries: true,
  20315. overallReset: function (ecModel) {
  20316. // Each type of series use one scope.
  20317. // Pie and funnel are using diferrent scopes
  20318. var paletteScopeGroupByType = createHashMap();
  20319. ecModel.eachSeries(function (seriesModel) {
  20320. if (!seriesModel.useColorPaletteOnData) {
  20321. return;
  20322. }
  20323. var colorScope = paletteScopeGroupByType.get(seriesModel.type);
  20324. if (!colorScope) {
  20325. colorScope = {};
  20326. paletteScopeGroupByType.set(seriesModel.type, colorScope);
  20327. }
  20328. inner$3(seriesModel).scope = colorScope;
  20329. });
  20330. ecModel.eachSeries(function (seriesModel) {
  20331. if (!seriesModel.useColorPaletteOnData || ecModel.isSeriesFiltered(seriesModel)) {
  20332. return;
  20333. }
  20334. var dataAll = seriesModel.getRawData();
  20335. var idxMap = {};
  20336. var data = seriesModel.getData();
  20337. var colorScope = inner$3(seriesModel).scope;
  20338. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  20339. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  20340. data.each(function (idx) {
  20341. var rawIdx = data.getRawIndex(idx);
  20342. idxMap[rawIdx] = idx;
  20343. }); // Iterate on data before filtered. To make sure color from palette can be
  20344. // Consistent when toggling legend.
  20345. dataAll.each(function (rawIdx) {
  20346. var idx = idxMap[rawIdx];
  20347. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  20348. // also picked from color palette. So following situation is not in the case:
  20349. // 1. series.itemStyle.color is set
  20350. // 2. color is encoded by visualMap
  20351. if (fromPalette) {
  20352. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  20353. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  20354. var dataCount = dataAll.count();
  20355. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  20356. }
  20357. });
  20358. });
  20359. }
  20360. };
  20361. var PI$3 = Math.PI;
  20362. /**
  20363. * @param {module:echarts/ExtensionAPI} api
  20364. * @param {Object} [opts]
  20365. * @param {string} [opts.text]
  20366. * @param {string} [opts.color]
  20367. * @param {string} [opts.textColor]
  20368. * @return {module:zrender/Element}
  20369. */
  20370. function defaultLoading(api, opts) {
  20371. opts = opts || {};
  20372. defaults(opts, {
  20373. text: 'loading',
  20374. textColor: '#000',
  20375. fontSize: 12,
  20376. fontWeight: 'normal',
  20377. fontStyle: 'normal',
  20378. fontFamily: 'sans-serif',
  20379. maskColor: 'rgba(255, 255, 255, 0.8)',
  20380. showSpinner: true,
  20381. color: '#5470c6',
  20382. spinnerRadius: 10,
  20383. lineWidth: 5,
  20384. zlevel: 0
  20385. });
  20386. var group = new Group();
  20387. var mask = new Rect({
  20388. style: {
  20389. fill: opts.maskColor
  20390. },
  20391. zlevel: opts.zlevel,
  20392. z: 10000
  20393. });
  20394. group.add(mask);
  20395. var textContent = new ZRText({
  20396. style: {
  20397. text: opts.text,
  20398. fill: opts.textColor,
  20399. fontSize: opts.fontSize,
  20400. fontWeight: opts.fontWeight,
  20401. fontStyle: opts.fontStyle,
  20402. fontFamily: opts.fontFamily
  20403. }
  20404. });
  20405. var labelRect = new Rect({
  20406. style: {
  20407. fill: 'none'
  20408. },
  20409. textContent: textContent,
  20410. textConfig: {
  20411. position: 'right',
  20412. distance: 10
  20413. },
  20414. zlevel: opts.zlevel,
  20415. z: 10001
  20416. });
  20417. group.add(labelRect);
  20418. var arc;
  20419. if (opts.showSpinner) {
  20420. arc = new Arc({
  20421. shape: {
  20422. startAngle: -PI$3 / 2,
  20423. endAngle: -PI$3 / 2 + 0.1,
  20424. r: opts.spinnerRadius
  20425. },
  20426. style: {
  20427. stroke: opts.color,
  20428. lineCap: 'round',
  20429. lineWidth: opts.lineWidth
  20430. },
  20431. zlevel: opts.zlevel,
  20432. z: 10001
  20433. });
  20434. arc.animateShape(true).when(1000, {
  20435. endAngle: PI$3 * 3 / 2
  20436. }).start('circularInOut');
  20437. arc.animateShape(true).when(1000, {
  20438. startAngle: PI$3 * 3 / 2
  20439. }).delay(300).start('circularInOut');
  20440. group.add(arc);
  20441. } // Inject resize
  20442. group.resize = function () {
  20443. var textWidth = textContent.getBoundingRect().width;
  20444. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  20445. // textDistance needs to be calculated when both animation and text exist
  20446. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  20447. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  20448. + (textWidth ? 0 : r);
  20449. var cy = api.getHeight() / 2;
  20450. opts.showSpinner && arc.setShape({
  20451. cx: cx,
  20452. cy: cy
  20453. });
  20454. labelRect.setShape({
  20455. x: cx - r,
  20456. y: cy - r,
  20457. width: r * 2,
  20458. height: r * 2
  20459. });
  20460. mask.setShape({
  20461. x: 0,
  20462. y: 0,
  20463. width: api.getWidth(),
  20464. height: api.getHeight()
  20465. });
  20466. };
  20467. group.resize();
  20468. return group;
  20469. }
  20470. var Scheduler =
  20471. /** @class */
  20472. function () {
  20473. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  20474. // key: handlerUID
  20475. this._stageTaskMap = createHashMap();
  20476. this.ecInstance = ecInstance;
  20477. this.api = api; // Fix current processors in case that in some rear cases that
  20478. // processors might be registered after echarts instance created.
  20479. // Register processors incrementally for a echarts instance is
  20480. // not supported by this stream architecture.
  20481. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  20482. visualHandlers = this._visualHandlers = visualHandlers.slice();
  20483. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  20484. }
  20485. Scheduler.prototype.restoreData = function (ecModel, payload) {
  20486. // TODO: Only restore needed series and components, but not all components.
  20487. // Currently `restoreData` of all of the series and component will be called.
  20488. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  20489. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  20490. // and some components like coordinate system, axes, dataZoom, visualMap only
  20491. // need their target series refresh.
  20492. // (1) If we are implementing this feature some day, we should consider these cases:
  20493. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  20494. // on the settings of `dataZoom`), it should be re-performed if the component
  20495. // is modified by `setOption`.
  20496. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  20497. // it should be re-performed when the result array of `getTargetSeries` changed.
  20498. // We use `dependencies` to cover these issues.
  20499. // (3) How to update target series when coordinate system related components modified.
  20500. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  20501. // and this case all of the tasks will be set as dirty.
  20502. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  20503. // depends on all of the series.
  20504. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  20505. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  20506. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  20507. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  20508. // probably cause state chaos (consider `dataZoomProcessor`).
  20509. this._stageTaskMap.each(function (taskRecord) {
  20510. var overallTask = taskRecord.overallTask;
  20511. overallTask && overallTask.dirty();
  20512. });
  20513. }; // If seriesModel provided, incremental threshold is check by series data.
  20514. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  20515. // For overall task
  20516. if (!task.__pipeline) {
  20517. return;
  20518. }
  20519. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20520. var pCtx = pipeline.context;
  20521. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  20522. var step = incremental ? pipeline.step : null;
  20523. var modDataCount = pCtx && pCtx.modDataCount;
  20524. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  20525. return {
  20526. step: step,
  20527. modBy: modBy,
  20528. modDataCount: modDataCount
  20529. };
  20530. };
  20531. Scheduler.prototype.getPipeline = function (pipelineId) {
  20532. return this._pipelineMap.get(pipelineId);
  20533. };
  20534. /**
  20535. * Current, progressive rendering starts from visual and layout.
  20536. * Always detect render mode in the same stage, avoiding that incorrect
  20537. * detection caused by data filtering.
  20538. * Caution:
  20539. * `updateStreamModes` use `seriesModel.getData()`.
  20540. */
  20541. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  20542. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20543. var data = seriesModel.getData();
  20544. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  20545. // animation frame. Note that some types of series do not provide
  20546. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  20547. // use the term `incremental` but not `progressive` to describe the
  20548. // case that `chart.appendData`.
  20549. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  20550. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  20551. // see `test/candlestick-large3.html`
  20552. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  20553. seriesModel.pipelineContext = pipeline.context = {
  20554. progressiveRender: progressiveRender,
  20555. modDataCount: modDataCount,
  20556. large: large
  20557. };
  20558. };
  20559. Scheduler.prototype.restorePipelines = function (ecModel) {
  20560. var scheduler = this;
  20561. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20562. ecModel.eachSeries(function (seriesModel) {
  20563. var progressive = seriesModel.getProgressive();
  20564. var pipelineId = seriesModel.uid;
  20565. pipelineMap.set(pipelineId, {
  20566. id: pipelineId,
  20567. head: null,
  20568. tail: null,
  20569. threshold: seriesModel.getProgressiveThreshold(),
  20570. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20571. blockIndex: -1,
  20572. step: Math.round(progressive || 700),
  20573. count: 0
  20574. });
  20575. scheduler._pipe(seriesModel, seriesModel.dataTask);
  20576. });
  20577. };
  20578. Scheduler.prototype.prepareStageTasks = function () {
  20579. var stageTaskMap = this._stageTaskMap;
  20580. var ecModel = this.api.getModel();
  20581. var api = this.api;
  20582. each(this._allHandlers, function (handler) {
  20583. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  20584. var errMsg = '';
  20585. if ("development" !== 'production') {
  20586. // Currently do not need to support to sepecify them both.
  20587. errMsg = '"reset" and "overallReset" must not be both specified.';
  20588. }
  20589. assert(!(handler.reset && handler.overallReset), errMsg);
  20590. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  20591. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  20592. }, this);
  20593. };
  20594. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  20595. var renderTask = view.renderTask;
  20596. var context = renderTask.context;
  20597. context.model = model;
  20598. context.ecModel = ecModel;
  20599. context.api = api;
  20600. renderTask.__block = !view.incrementalPrepareRender;
  20601. this._pipe(model, renderTask);
  20602. };
  20603. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  20604. // If we do not use `block` here, it should be considered when to update modes.
  20605. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  20606. block: true
  20607. });
  20608. };
  20609. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  20610. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  20611. };
  20612. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  20613. opt = opt || {};
  20614. var unfinished = false;
  20615. var scheduler = this;
  20616. each(stageHandlers, function (stageHandler, idx) {
  20617. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20618. return;
  20619. }
  20620. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20621. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20622. var overallTask = stageHandlerRecord.overallTask;
  20623. if (overallTask) {
  20624. var overallNeedDirty_1;
  20625. var agentStubMap = overallTask.agentStubMap;
  20626. agentStubMap.each(function (stub) {
  20627. if (needSetDirty(opt, stub)) {
  20628. stub.dirty();
  20629. overallNeedDirty_1 = true;
  20630. }
  20631. });
  20632. overallNeedDirty_1 && overallTask.dirty();
  20633. scheduler.updatePayload(overallTask, payload);
  20634. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  20635. // then execute the overall task. And stub will call seriesModel.setData,
  20636. // which ensures that in the overallTask seriesModel.getData() will not
  20637. // return incorrect data.
  20638. agentStubMap.each(function (stub) {
  20639. stub.perform(performArgs_1);
  20640. });
  20641. if (overallTask.perform(performArgs_1)) {
  20642. unfinished = true;
  20643. }
  20644. } else if (seriesTaskMap) {
  20645. seriesTaskMap.each(function (task, pipelineId) {
  20646. if (needSetDirty(opt, task)) {
  20647. task.dirty();
  20648. }
  20649. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  20650. // if intending to decalare `performRawSeries` in handlers, only
  20651. // stream-independent (specifically, data item independent) operations can be
  20652. // performed. Because is a series is filtered, most of the tasks will not
  20653. // be performed. A stream-dependent operation probably cause wrong biz logic.
  20654. // Perhaps we should not provide a separate callback for this case instead
  20655. // of providing the config `performRawSeries`. The stream-dependent operaions
  20656. // and stream-independent operations should better not be mixed.
  20657. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  20658. scheduler.updatePayload(task, payload);
  20659. if (task.perform(performArgs)) {
  20660. unfinished = true;
  20661. }
  20662. });
  20663. }
  20664. });
  20665. function needSetDirty(opt, task) {
  20666. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20667. }
  20668. this.unfinished = unfinished || this.unfinished;
  20669. };
  20670. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  20671. var unfinished;
  20672. ecModel.eachSeries(function (seriesModel) {
  20673. // Progress to the end for dataInit and dataRestore.
  20674. unfinished = seriesModel.dataTask.perform() || unfinished;
  20675. });
  20676. this.unfinished = unfinished || this.unfinished;
  20677. };
  20678. Scheduler.prototype.plan = function () {
  20679. // Travel pipelines, check block.
  20680. this._pipelineMap.each(function (pipeline) {
  20681. var task = pipeline.tail;
  20682. do {
  20683. if (task.__block) {
  20684. pipeline.blockIndex = task.__idxInPipeline;
  20685. break;
  20686. }
  20687. task = task.getUpstream();
  20688. } while (task);
  20689. });
  20690. };
  20691. Scheduler.prototype.updatePayload = function (task, payload) {
  20692. payload !== 'remain' && (task.context.payload = payload);
  20693. };
  20694. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  20695. var scheduler = this;
  20696. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  20697. // do not need to reuse the map.
  20698. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  20699. var seriesType = stageHandler.seriesType;
  20700. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20701. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20702. // it works but it may cause other irrelevant charts blocked.
  20703. if (stageHandler.createOnAllSeries) {
  20704. ecModel.eachRawSeries(create);
  20705. } else if (seriesType) {
  20706. ecModel.eachRawSeriesByType(seriesType, create);
  20707. } else if (getTargetSeries) {
  20708. getTargetSeries(ecModel, api).each(create);
  20709. }
  20710. function create(seriesModel) {
  20711. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  20712. // Reuse original task instance.
  20713. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  20714. plan: seriesTaskPlan,
  20715. reset: seriesTaskReset,
  20716. count: seriesTaskCount
  20717. }));
  20718. task.context = {
  20719. model: seriesModel,
  20720. ecModel: ecModel,
  20721. api: api,
  20722. // PENDING: `useClearVisual` not used?
  20723. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20724. plan: stageHandler.plan,
  20725. reset: stageHandler.reset,
  20726. scheduler: scheduler
  20727. };
  20728. scheduler._pipe(seriesModel, task);
  20729. }
  20730. };
  20731. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  20732. var scheduler = this;
  20733. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  20734. || createTask({
  20735. reset: overallTaskReset
  20736. });
  20737. overallTask.context = {
  20738. ecModel: ecModel,
  20739. api: api,
  20740. overallReset: stageHandler.overallReset,
  20741. scheduler: scheduler
  20742. };
  20743. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  20744. // do not need to reuse the map.
  20745. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  20746. var seriesType = stageHandler.seriesType;
  20747. var getTargetSeries = stageHandler.getTargetSeries;
  20748. var overallProgress = true;
  20749. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  20750. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  20751. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20752. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20753. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20754. // we set the pipeline block.
  20755. var errMsg = '';
  20756. if ("development" !== 'production') {
  20757. errMsg = '"createOnAllSeries" do not supported for "overallReset", ' + 'becuase it will block all streams.';
  20758. }
  20759. assert(!stageHandler.createOnAllSeries, errMsg);
  20760. if (seriesType) {
  20761. ecModel.eachRawSeriesByType(seriesType, createStub);
  20762. } else if (getTargetSeries) {
  20763. getTargetSeries(ecModel, api).each(createStub);
  20764. } // Otherwise, (usually it is legancy case), the overall task will only be
  20765. // executed when upstream dirty. Otherwise the progressive rendering of all
  20766. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20767. // dirty info from upsteam.
  20768. else {
  20769. overallProgress = false;
  20770. each(ecModel.getSeries(), createStub);
  20771. }
  20772. function createStub(seriesModel) {
  20773. var pipelineId = seriesModel.uid;
  20774. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  20775. // should be set as dirty and re-performed.
  20776. shouldOverallTaskDirty = true, createTask({
  20777. reset: stubReset,
  20778. onDirty: stubOnDirty
  20779. })));
  20780. stub.context = {
  20781. model: seriesModel,
  20782. overallProgress: overallProgress // FIXME:TS never used, so comment it
  20783. // modifyOutputEnd: modifyOutputEnd
  20784. };
  20785. stub.agent = overallTask;
  20786. stub.__block = overallProgress;
  20787. scheduler._pipe(seriesModel, stub);
  20788. }
  20789. if (shouldOverallTaskDirty) {
  20790. overallTask.dirty();
  20791. }
  20792. };
  20793. Scheduler.prototype._pipe = function (seriesModel, task) {
  20794. var pipelineId = seriesModel.uid;
  20795. var pipeline = this._pipelineMap.get(pipelineId);
  20796. !pipeline.head && (pipeline.head = task);
  20797. pipeline.tail && pipeline.tail.pipe(task);
  20798. pipeline.tail = task;
  20799. task.__idxInPipeline = pipeline.count++;
  20800. task.__pipeline = pipeline;
  20801. };
  20802. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20803. if (isFunction(stageHandler)) {
  20804. stageHandler = {
  20805. overallReset: stageHandler,
  20806. seriesType: detectSeriseType(stageHandler)
  20807. };
  20808. }
  20809. stageHandler.uid = getUID('stageHandler');
  20810. visualType && (stageHandler.visualType = visualType);
  20811. return stageHandler;
  20812. };
  20813. return Scheduler;
  20814. }();
  20815. function overallTaskReset(context) {
  20816. context.overallReset(context.ecModel, context.api, context.payload);
  20817. }
  20818. function stubReset(context) {
  20819. return context.overallProgress && stubProgress;
  20820. }
  20821. function stubProgress() {
  20822. this.agent.dirty();
  20823. this.getDownstream().dirty();
  20824. }
  20825. function stubOnDirty() {
  20826. this.agent && this.agent.dirty();
  20827. }
  20828. function seriesTaskPlan(context) {
  20829. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  20830. }
  20831. function seriesTaskReset(context) {
  20832. if (context.useClearVisual) {
  20833. context.data.clearAllVisual();
  20834. }
  20835. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  20836. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  20837. return makeSeriesTaskProgress(idx);
  20838. }) : singleSeriesTaskProgress;
  20839. }
  20840. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  20841. function makeSeriesTaskProgress(resetDefineIdx) {
  20842. return function (params, context) {
  20843. var data = context.data;
  20844. var resetDefine = context.resetDefines[resetDefineIdx];
  20845. if (resetDefine && resetDefine.dataEach) {
  20846. for (var i = params.start; i < params.end; i++) {
  20847. resetDefine.dataEach(data, i);
  20848. }
  20849. } else if (resetDefine && resetDefine.progress) {
  20850. resetDefine.progress(params, data);
  20851. }
  20852. };
  20853. }
  20854. function seriesTaskCount(context) {
  20855. return context.data.count();
  20856. }
  20857. /**
  20858. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20859. * To ensure that they can work normally, they should work in block mode, that is,
  20860. * they should not be started util the previous tasks finished. So they cause the
  20861. * progressive rendering disabled. We try to detect the series type, to narrow down
  20862. * the block range to only the series type they concern, but not all series.
  20863. */
  20864. function detectSeriseType(legacyFunc) {
  20865. seriesType = null;
  20866. try {
  20867. // Assume there is no async when calling `eachSeriesByType`.
  20868. legacyFunc(ecModelMock, apiMock);
  20869. } catch (e) {}
  20870. return seriesType;
  20871. }
  20872. var ecModelMock = {};
  20873. var apiMock = {};
  20874. var seriesType;
  20875. mockMethods(ecModelMock, GlobalModel);
  20876. mockMethods(apiMock, ExtensionAPI);
  20877. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20878. seriesType = type;
  20879. };
  20880. ecModelMock.eachComponent = function (cond) {
  20881. if (cond.mainType === 'series' && cond.subType) {
  20882. seriesType = cond.subType;
  20883. }
  20884. };
  20885. function mockMethods(target, Clz) {
  20886. /* eslint-disable */
  20887. for (var name_1 in Clz.prototype) {
  20888. // Do not use hasOwnProperty
  20889. target[name_1] = noop;
  20890. }
  20891. /* eslint-enable */
  20892. }
  20893. /*
  20894. * Licensed to the Apache Software Foundation (ASF) under one
  20895. * or more contributor license agreements. See the NOTICE file
  20896. * distributed with this work for additional information
  20897. * regarding copyright ownership. The ASF licenses this file
  20898. * to you under the Apache License, Version 2.0 (the
  20899. * "License"); you may not use this file except in compliance
  20900. * with the License. You may obtain a copy of the License at
  20901. *
  20902. * http://www.apache.org/licenses/LICENSE-2.0
  20903. *
  20904. * Unless required by applicable law or agreed to in writing,
  20905. * software distributed under the License is distributed on an
  20906. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20907. * KIND, either express or implied. See the License for the
  20908. * specific language governing permissions and limitations
  20909. * under the License.
  20910. */
  20911. /**
  20912. * AUTO-GENERATED FILE. DO NOT MODIFY.
  20913. */
  20914. /*
  20915. * Licensed to the Apache Software Foundation (ASF) under one
  20916. * or more contributor license agreements. See the NOTICE file
  20917. * distributed with this work for additional information
  20918. * regarding copyright ownership. The ASF licenses this file
  20919. * to you under the Apache License, Version 2.0 (the
  20920. * "License"); you may not use this file except in compliance
  20921. * with the License. You may obtain a copy of the License at
  20922. *
  20923. * http://www.apache.org/licenses/LICENSE-2.0
  20924. *
  20925. * Unless required by applicable law or agreed to in writing,
  20926. * software distributed under the License is distributed on an
  20927. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20928. * KIND, either express or implied. See the License for the
  20929. * specific language governing permissions and limitations
  20930. * under the License.
  20931. */
  20932. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20933. var lightTheme = {
  20934. color: colorAll,
  20935. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  20936. };
  20937. /*
  20938. * Licensed to the Apache Software Foundation (ASF) under one
  20939. * or more contributor license agreements. See the NOTICE file
  20940. * distributed with this work for additional information
  20941. * regarding copyright ownership. The ASF licenses this file
  20942. * to you under the Apache License, Version 2.0 (the
  20943. * "License"); you may not use this file except in compliance
  20944. * with the License. You may obtain a copy of the License at
  20945. *
  20946. * http://www.apache.org/licenses/LICENSE-2.0
  20947. *
  20948. * Unless required by applicable law or agreed to in writing,
  20949. * software distributed under the License is distributed on an
  20950. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20951. * KIND, either express or implied. See the License for the
  20952. * specific language governing permissions and limitations
  20953. * under the License.
  20954. */
  20955. /**
  20956. * AUTO-GENERATED FILE. DO NOT MODIFY.
  20957. */
  20958. /*
  20959. * Licensed to the Apache Software Foundation (ASF) under one
  20960. * or more contributor license agreements. See the NOTICE file
  20961. * distributed with this work for additional information
  20962. * regarding copyright ownership. The ASF licenses this file
  20963. * to you under the Apache License, Version 2.0 (the
  20964. * "License"); you may not use this file except in compliance
  20965. * with the License. You may obtain a copy of the License at
  20966. *
  20967. * http://www.apache.org/licenses/LICENSE-2.0
  20968. *
  20969. * Unless required by applicable law or agreed to in writing,
  20970. * software distributed under the License is distributed on an
  20971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20972. * KIND, either express or implied. See the License for the
  20973. * specific language governing permissions and limitations
  20974. * under the License.
  20975. */
  20976. var contrastColor = '#B9B8CE';
  20977. var backgroundColor = '#100C2A';
  20978. var axisCommon = function () {
  20979. return {
  20980. axisLine: {
  20981. lineStyle: {
  20982. color: contrastColor
  20983. }
  20984. },
  20985. splitLine: {
  20986. lineStyle: {
  20987. color: '#484753'
  20988. }
  20989. },
  20990. splitArea: {
  20991. areaStyle: {
  20992. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  20993. }
  20994. },
  20995. minorSplitLine: {
  20996. lineStyle: {
  20997. color: '#20203B'
  20998. }
  20999. }
  21000. };
  21001. };
  21002. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  21003. var theme = {
  21004. darkMode: true,
  21005. color: colorPalette,
  21006. backgroundColor: backgroundColor,
  21007. axisPointer: {
  21008. lineStyle: {
  21009. color: '#817f91'
  21010. },
  21011. crossStyle: {
  21012. color: '#817f91'
  21013. },
  21014. label: {
  21015. // TODO Contrast of label backgorundColor
  21016. color: '#fff'
  21017. }
  21018. },
  21019. legend: {
  21020. textStyle: {
  21021. color: contrastColor
  21022. }
  21023. },
  21024. textStyle: {
  21025. color: contrastColor
  21026. },
  21027. title: {
  21028. textStyle: {
  21029. color: '#EEF1FA'
  21030. },
  21031. subtextStyle: {
  21032. color: '#B9B8CE'
  21033. }
  21034. },
  21035. toolbox: {
  21036. iconStyle: {
  21037. borderColor: contrastColor
  21038. }
  21039. },
  21040. dataZoom: {
  21041. borderColor: '#71708A',
  21042. textStyle: {
  21043. color: contrastColor
  21044. },
  21045. brushStyle: {
  21046. color: 'rgba(135,163,206,0.3)'
  21047. },
  21048. handleStyle: {
  21049. color: '#353450',
  21050. borderColor: '#C5CBE3'
  21051. },
  21052. moveHandleStyle: {
  21053. color: '#B0B6C3',
  21054. opacity: 0.3
  21055. },
  21056. fillerColor: 'rgba(135,163,206,0.2)',
  21057. emphasis: {
  21058. handleStyle: {
  21059. borderColor: '#91B7F2',
  21060. color: '#4D587D'
  21061. },
  21062. moveHandleStyle: {
  21063. color: '#636D9A',
  21064. opacity: 0.7
  21065. }
  21066. },
  21067. dataBackground: {
  21068. lineStyle: {
  21069. color: '#71708A',
  21070. width: 1
  21071. },
  21072. areaStyle: {
  21073. color: '#71708A'
  21074. }
  21075. },
  21076. selectedDataBackground: {
  21077. lineStyle: {
  21078. color: '#87A3CE'
  21079. },
  21080. areaStyle: {
  21081. color: '#87A3CE'
  21082. }
  21083. }
  21084. },
  21085. visualMap: {
  21086. textStyle: {
  21087. color: contrastColor
  21088. }
  21089. },
  21090. timeline: {
  21091. lineStyle: {
  21092. color: contrastColor
  21093. },
  21094. label: {
  21095. color: contrastColor
  21096. },
  21097. controlStyle: {
  21098. color: contrastColor,
  21099. borderColor: contrastColor
  21100. }
  21101. },
  21102. calendar: {
  21103. itemStyle: {
  21104. color: backgroundColor
  21105. },
  21106. dayLabel: {
  21107. color: contrastColor
  21108. },
  21109. monthLabel: {
  21110. color: contrastColor
  21111. },
  21112. yearLabel: {
  21113. color: contrastColor
  21114. }
  21115. },
  21116. timeAxis: axisCommon(),
  21117. logAxis: axisCommon(),
  21118. valueAxis: axisCommon(),
  21119. categoryAxis: axisCommon(),
  21120. line: {
  21121. symbol: 'circle'
  21122. },
  21123. graph: {
  21124. color: colorPalette
  21125. },
  21126. gauge: {
  21127. title: {
  21128. color: contrastColor
  21129. },
  21130. axisLine: {
  21131. lineStyle: {
  21132. color: [[1, 'rgba(207,212,219,0.2)']]
  21133. }
  21134. },
  21135. axisLabel: {
  21136. color: contrastColor
  21137. },
  21138. detail: {
  21139. color: '#EEF1FA'
  21140. }
  21141. },
  21142. candlestick: {
  21143. itemStyle: {
  21144. color: '#f64e56',
  21145. color0: '#54ea92',
  21146. borderColor: '#f64e56',
  21147. borderColor0: '#54ea92' // borderColor: '#ca2824',
  21148. // borderColor0: '#09a443'
  21149. }
  21150. }
  21151. };
  21152. theme.categoryAxis.splitLine.show = false;
  21153. function parseXML(svg) {
  21154. if (isString(svg)) {
  21155. var parser = new DOMParser();
  21156. svg = parser.parseFromString(svg, 'text/xml');
  21157. }
  21158. var svgNode = svg;
  21159. if (svgNode.nodeType === 9) {
  21160. svgNode = svgNode.firstChild;
  21161. }
  21162. while (svgNode.nodeName.toLowerCase() !== 'svg' || svgNode.nodeType !== 1) {
  21163. svgNode = svgNode.nextSibling;
  21164. }
  21165. return svgNode;
  21166. }
  21167. var storage = createHashMap();
  21168. var mapDataStorage = {
  21169. /**
  21170. * Compatible with previous `echarts.registerMap`.
  21171. * @usage
  21172. * ```js
  21173. * $.get('USA.json', function (geoJson) {
  21174. * echarts.registerMap('USA', geoJson);
  21175. * // Or
  21176. * echarts.registerMap('USA', {
  21177. * geoJson: geoJson,
  21178. * specialAreas: {}
  21179. * })
  21180. * });
  21181. *
  21182. * $.get('airport.svg', function (svg) {
  21183. * echarts.registerMap('airport', {
  21184. * svg: svg
  21185. * }
  21186. * });
  21187. *
  21188. * echarts.registerMap('eu', [
  21189. * {svg: eu-topographic.svg},
  21190. * {geoJSON: eu.json}
  21191. * ])
  21192. * ```
  21193. */
  21194. registerMap: function (mapName, rawDef, rawSpecialAreas) {
  21195. var records;
  21196. if (isArray(rawDef)) {
  21197. records = rawDef;
  21198. } else if (rawDef.svg) {
  21199. records = [{
  21200. type: 'svg',
  21201. source: rawDef.svg,
  21202. specialAreas: rawDef.specialAreas
  21203. }];
  21204. } else {
  21205. // Backward compatibility.
  21206. var geoSource = rawDef.geoJson || rawDef.geoJSON;
  21207. if (geoSource && !rawDef.features) {
  21208. rawSpecialAreas = rawDef.specialAreas;
  21209. rawDef = geoSource;
  21210. }
  21211. records = [{
  21212. type: 'geoJSON',
  21213. source: rawDef,
  21214. specialAreas: rawSpecialAreas
  21215. }];
  21216. }
  21217. each(records, function (record) {
  21218. var type = record.type;
  21219. type === 'geoJson' && (type = record.type = 'geoJSON');
  21220. var parse = parsers[type];
  21221. if ("development" !== 'production') {
  21222. assert(parse, 'Illegal map type: ' + type);
  21223. }
  21224. parse(record);
  21225. });
  21226. return storage.set(mapName, records);
  21227. },
  21228. retrieveMap: function (mapName) {
  21229. return storage.get(mapName);
  21230. }
  21231. };
  21232. var parsers = {
  21233. geoJSON: function (record) {
  21234. var source = record.source;
  21235. record.geoJSON = !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  21236. },
  21237. // Only perform parse to XML object here, which might be time
  21238. // consiming for large SVG.
  21239. // Although convert XML to zrender element is also time consiming,
  21240. // if we do it here, the clone of zrender elements has to be
  21241. // required. So we do it once for each geo instance, util real
  21242. // performance issues call for optimizing it.
  21243. svg: function (record) {
  21244. record.svgXML = parseXML(record.source);
  21245. }
  21246. };
  21247. /**
  21248. * Usage of query:
  21249. * `chart.on('click', query, handler);`
  21250. * The `query` can be:
  21251. * + The component type query string, only `mainType` or `mainType.subType`,
  21252. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  21253. * + The component query object, like:
  21254. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  21255. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  21256. * + The data query object, like:
  21257. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  21258. * + The other query object (cmponent customized query), like:
  21259. * `{element: 'some'}` (only available in custom series).
  21260. *
  21261. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  21262. * same as there is no such prop in the `query` object.
  21263. */
  21264. var ECEventProcessor =
  21265. /** @class */
  21266. function () {
  21267. function ECEventProcessor() {}
  21268. ECEventProcessor.prototype.normalizeQuery = function (query) {
  21269. var cptQuery = {};
  21270. var dataQuery = {};
  21271. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  21272. if (isString(query)) {
  21273. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  21274. cptQuery.mainType = condCptType.main || null;
  21275. cptQuery.subType = condCptType.sub || null;
  21276. } // `query` is an object, convert to {mainType, index, name, id}.
  21277. else {
  21278. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  21279. // can not be used in `compomentModel.filterForExposedEvent`.
  21280. var suffixes_1 = ['Index', 'Name', 'Id'];
  21281. var dataKeys_1 = {
  21282. name: 1,
  21283. dataIndex: 1,
  21284. dataType: 1
  21285. };
  21286. each(query, function (val, key) {
  21287. var reserved = false;
  21288. for (var i = 0; i < suffixes_1.length; i++) {
  21289. var propSuffix = suffixes_1[i];
  21290. var suffixPos = key.lastIndexOf(propSuffix);
  21291. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  21292. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  21293. if (mainType !== 'data') {
  21294. cptQuery.mainType = mainType;
  21295. cptQuery[propSuffix.toLowerCase()] = val;
  21296. reserved = true;
  21297. }
  21298. }
  21299. }
  21300. if (dataKeys_1.hasOwnProperty(key)) {
  21301. dataQuery[key] = val;
  21302. reserved = true;
  21303. }
  21304. if (!reserved) {
  21305. otherQuery[key] = val;
  21306. }
  21307. });
  21308. }
  21309. return {
  21310. cptQuery: cptQuery,
  21311. dataQuery: dataQuery,
  21312. otherQuery: otherQuery
  21313. };
  21314. };
  21315. ECEventProcessor.prototype.filter = function (eventType, query) {
  21316. // They should be assigned before each trigger call.
  21317. var eventInfo = this.eventInfo;
  21318. if (!eventInfo) {
  21319. return true;
  21320. }
  21321. var targetEl = eventInfo.targetEl;
  21322. var packedEvent = eventInfo.packedEvent;
  21323. var model = eventInfo.model;
  21324. var view = eventInfo.view; // For event like 'globalout'.
  21325. if (!model || !view) {
  21326. return true;
  21327. }
  21328. var cptQuery = query.cptQuery;
  21329. var dataQuery = query.dataQuery;
  21330. 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));
  21331. function check(query, host, prop, propOnHost) {
  21332. return query[prop] == null || host[propOnHost || prop] === query[prop];
  21333. }
  21334. };
  21335. ECEventProcessor.prototype.afterTrigger = function () {
  21336. // Make sure the eventInfo wont be used in next trigger.
  21337. this.eventInfo = null;
  21338. };
  21339. return ECEventProcessor;
  21340. }();
  21341. var seriesSymbolTask = {
  21342. createOnAllSeries: true,
  21343. // For legend.
  21344. performRawSeries: true,
  21345. reset: function (seriesModel, ecModel) {
  21346. var data = seriesModel.getData();
  21347. if (seriesModel.legendSymbol) {
  21348. data.setVisual('legendSymbol', seriesModel.legendSymbol);
  21349. }
  21350. if (!seriesModel.hasSymbolVisual) {
  21351. return;
  21352. }
  21353. var symbolType = seriesModel.get('symbol');
  21354. var symbolSize = seriesModel.get('symbolSize');
  21355. var keepAspect = seriesModel.get('symbolKeepAspect');
  21356. var symbolRotate = seriesModel.get('symbolRotate');
  21357. var hasSymbolTypeCallback = isFunction(symbolType);
  21358. var hasSymbolSizeCallback = isFunction(symbolSize);
  21359. var hasSymbolRotateCallback = isFunction(symbolRotate);
  21360. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  21361. var seriesSymbol = !hasSymbolTypeCallback && symbolType ? symbolType : seriesModel.defaultSymbol;
  21362. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  21363. var seriesSymbolRotate = !hasSymbolRotateCallback ? symbolRotate : null;
  21364. data.setVisual({
  21365. legendSymbol: seriesModel.legendSymbol || seriesSymbol,
  21366. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  21367. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  21368. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  21369. // some cases but generally it is not recommanded.
  21370. symbol: seriesSymbol,
  21371. symbolSize: seriesSymbolSize,
  21372. symbolKeepAspect: keepAspect,
  21373. symbolRotate: seriesSymbolRotate
  21374. }); // Only visible series has each data be visual encoded
  21375. if (ecModel.isSeriesFiltered(seriesModel)) {
  21376. return;
  21377. }
  21378. function dataEach(data, idx) {
  21379. var rawValue = seriesModel.getRawValue(idx);
  21380. var params = seriesModel.getDataParams(idx);
  21381. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  21382. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  21383. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  21384. }
  21385. return {
  21386. dataEach: hasCallback ? dataEach : null
  21387. };
  21388. }
  21389. };
  21390. var dataSymbolTask = {
  21391. createOnAllSeries: true,
  21392. // For legend.
  21393. performRawSeries: true,
  21394. reset: function (seriesModel, ecModel) {
  21395. if (!seriesModel.hasSymbolVisual) {
  21396. return;
  21397. } // Only visible series has each data be visual encoded
  21398. if (ecModel.isSeriesFiltered(seriesModel)) {
  21399. return;
  21400. }
  21401. var data = seriesModel.getData();
  21402. function dataEach(data, idx) {
  21403. var itemModel = data.getItemModel(idx);
  21404. var itemSymbolType = itemModel.getShallow('symbol', true);
  21405. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  21406. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  21407. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true); // If has item symbol
  21408. if (itemSymbolType != null) {
  21409. data.setItemVisual(idx, 'symbol', itemSymbolType);
  21410. }
  21411. if (itemSymbolSize != null) {
  21412. // PENDING Transform symbolSize ?
  21413. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  21414. }
  21415. if (itemSymbolRotate != null) {
  21416. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  21417. }
  21418. if (itemSymbolKeepAspect != null) {
  21419. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  21420. }
  21421. }
  21422. return {
  21423. dataEach: data.hasItemOption ? dataEach : null
  21424. };
  21425. }
  21426. };
  21427. /*
  21428. * Licensed to the Apache Software Foundation (ASF) under one
  21429. * or more contributor license agreements. See the NOTICE file
  21430. * distributed with this work for additional information
  21431. * regarding copyright ownership. The ASF licenses this file
  21432. * to you under the Apache License, Version 2.0 (the
  21433. * "License"); you may not use this file except in compliance
  21434. * with the License. You may obtain a copy of the License at
  21435. *
  21436. * http://www.apache.org/licenses/LICENSE-2.0
  21437. *
  21438. * Unless required by applicable law or agreed to in writing,
  21439. * software distributed under the License is distributed on an
  21440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21441. * KIND, either express or implied. See the License for the
  21442. * specific language governing permissions and limitations
  21443. * under the License.
  21444. */
  21445. /**
  21446. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21447. */
  21448. /*
  21449. * Licensed to the Apache Software Foundation (ASF) under one
  21450. * or more contributor license agreements. See the NOTICE file
  21451. * distributed with this work for additional information
  21452. * regarding copyright ownership. The ASF licenses this file
  21453. * to you under the Apache License, Version 2.0 (the
  21454. * "License"); you may not use this file except in compliance
  21455. * with the License. You may obtain a copy of the License at
  21456. *
  21457. * http://www.apache.org/licenses/LICENSE-2.0
  21458. *
  21459. * Unless required by applicable law or agreed to in writing,
  21460. * software distributed under the License is distributed on an
  21461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21462. * KIND, either express or implied. See the License for the
  21463. * specific language governing permissions and limitations
  21464. * under the License.
  21465. */
  21466. function getItemVisualFromData(data, dataIndex, key) {
  21467. switch (key) {
  21468. case 'color':
  21469. var style = data.getItemVisual(dataIndex, 'style');
  21470. return style[data.getVisual('drawType')];
  21471. case 'opacity':
  21472. return data.getItemVisual(dataIndex, 'style').opacity;
  21473. case 'symbol':
  21474. case 'symbolSize':
  21475. case 'liftZ':
  21476. return data.getItemVisual(dataIndex, key);
  21477. default:
  21478. if ("development" !== 'production') {
  21479. console.warn("Unknown visual type " + key);
  21480. }
  21481. }
  21482. }
  21483. function getVisualFromData(data, key) {
  21484. switch (key) {
  21485. case 'color':
  21486. var style = data.getVisual('style');
  21487. return style[data.getVisual('drawType')];
  21488. case 'opacity':
  21489. return data.getVisual('style').opacity;
  21490. case 'symbol':
  21491. case 'symbolSize':
  21492. case 'liftZ':
  21493. return data.getVisual(key);
  21494. default:
  21495. if ("development" !== 'production') {
  21496. console.warn("Unknown visual type " + key);
  21497. }
  21498. }
  21499. }
  21500. var PI2$6 = Math.PI * 2;
  21501. var CMD$3 = PathProxy.CMD;
  21502. var DEFAULT_SEARCH_SPACE = ['top', 'right', 'bottom', 'left'];
  21503. function getCandidateAnchor(pos, distance, rect, outPt, outDir) {
  21504. var width = rect.width;
  21505. var height = rect.height;
  21506. switch (pos) {
  21507. case 'top':
  21508. outPt.set(rect.x + width / 2, rect.y - distance);
  21509. outDir.set(0, -1);
  21510. break;
  21511. case 'bottom':
  21512. outPt.set(rect.x + width / 2, rect.y + height + distance);
  21513. outDir.set(0, 1);
  21514. break;
  21515. case 'left':
  21516. outPt.set(rect.x - distance, rect.y + height / 2);
  21517. outDir.set(-1, 0);
  21518. break;
  21519. case 'right':
  21520. outPt.set(rect.x + width + distance, rect.y + height / 2);
  21521. outDir.set(1, 0);
  21522. break;
  21523. }
  21524. }
  21525. function projectPointToArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) {
  21526. x -= cx;
  21527. y -= cy;
  21528. var d = Math.sqrt(x * x + y * y);
  21529. x /= d;
  21530. y /= d; // Intersect point.
  21531. var ox = x * r + cx;
  21532. var oy = y * r + cy;
  21533. if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) {
  21534. // Is a circle
  21535. out[0] = ox;
  21536. out[1] = oy;
  21537. return d - r;
  21538. }
  21539. if (anticlockwise) {
  21540. var tmp = startAngle;
  21541. startAngle = normalizeRadian(endAngle);
  21542. endAngle = normalizeRadian(tmp);
  21543. } else {
  21544. startAngle = normalizeRadian(startAngle);
  21545. endAngle = normalizeRadian(endAngle);
  21546. }
  21547. if (startAngle > endAngle) {
  21548. endAngle += PI2$6;
  21549. }
  21550. var angle = Math.atan2(y, x);
  21551. if (angle < 0) {
  21552. angle += PI2$6;
  21553. }
  21554. if (angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) {
  21555. // Project point is on the arc.
  21556. out[0] = ox;
  21557. out[1] = oy;
  21558. return d - r;
  21559. }
  21560. var x1 = r * Math.cos(startAngle) + cx;
  21561. var y1 = r * Math.sin(startAngle) + cy;
  21562. var x2 = r * Math.cos(endAngle) + cx;
  21563. var y2 = r * Math.sin(endAngle) + cy;
  21564. var d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
  21565. var d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
  21566. if (d1 < d2) {
  21567. out[0] = x1;
  21568. out[1] = y1;
  21569. return Math.sqrt(d1);
  21570. } else {
  21571. out[0] = x2;
  21572. out[1] = y2;
  21573. return Math.sqrt(d2);
  21574. }
  21575. }
  21576. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  21577. var dx = x - x1;
  21578. var dy = y - y1;
  21579. var dx1 = x2 - x1;
  21580. var dy1 = y2 - y1;
  21581. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  21582. dx1 /= lineLen;
  21583. dy1 /= lineLen; // dot product
  21584. var projectedLen = dx * dx1 + dy * dy1;
  21585. var t = projectedLen / lineLen;
  21586. if (limitToEnds) {
  21587. t = Math.min(Math.max(t, 0), 1);
  21588. }
  21589. t *= lineLen;
  21590. var ox = out[0] = x1 + t * dx1;
  21591. var oy = out[1] = y1 + t * dy1;
  21592. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  21593. }
  21594. function projectPointToRect(x1, y1, width, height, x, y, out) {
  21595. if (width < 0) {
  21596. x1 = x1 + width;
  21597. width = -width;
  21598. }
  21599. if (height < 0) {
  21600. y1 = y1 + height;
  21601. height = -height;
  21602. }
  21603. var x2 = x1 + width;
  21604. var y2 = y1 + height;
  21605. var ox = out[0] = Math.min(Math.max(x, x1), x2);
  21606. var oy = out[1] = Math.min(Math.max(y, y1), y2);
  21607. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  21608. }
  21609. var tmpPt = [];
  21610. function nearestPointOnRect(pt, rect, out) {
  21611. var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt);
  21612. out.set(tmpPt[0], tmpPt[1]);
  21613. return dist;
  21614. }
  21615. /**
  21616. * Calculate min distance corresponding point.
  21617. * This method won't evaluate if point is in the path.
  21618. */
  21619. function nearestPointOnPath(pt, path, out) {
  21620. var xi = 0;
  21621. var yi = 0;
  21622. var x0 = 0;
  21623. var y0 = 0;
  21624. var x1;
  21625. var y1;
  21626. var minDist = Infinity;
  21627. var data = path.data;
  21628. var x = pt.x;
  21629. var y = pt.y;
  21630. for (var i = 0; i < data.length;) {
  21631. var cmd = data[i++];
  21632. if (i === 1) {
  21633. xi = data[i];
  21634. yi = data[i + 1];
  21635. x0 = xi;
  21636. y0 = yi;
  21637. }
  21638. var d = minDist;
  21639. switch (cmd) {
  21640. case CMD$3.M:
  21641. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  21642. // 在 closePath 的时候使用
  21643. x0 = data[i++];
  21644. y0 = data[i++];
  21645. xi = x0;
  21646. yi = y0;
  21647. break;
  21648. case CMD$3.L:
  21649. d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, true);
  21650. xi = data[i++];
  21651. yi = data[i++];
  21652. break;
  21653. case CMD$3.C:
  21654. d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  21655. xi = data[i++];
  21656. yi = data[i++];
  21657. break;
  21658. case CMD$3.Q:
  21659. d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  21660. xi = data[i++];
  21661. yi = data[i++];
  21662. break;
  21663. case CMD$3.A:
  21664. // TODO Arc 判断的开销比较大
  21665. var cx = data[i++];
  21666. var cy = data[i++];
  21667. var rx = data[i++];
  21668. var ry = data[i++];
  21669. var theta = data[i++];
  21670. var dTheta = data[i++]; // TODO Arc 旋转
  21671. i += 1;
  21672. var anticlockwise = !!(1 - data[i++]);
  21673. x1 = Math.cos(theta) * rx + cx;
  21674. y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  21675. if (i <= 1) {
  21676. // 第一个命令起点还未定义
  21677. x0 = x1;
  21678. y0 = y1;
  21679. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  21680. var _x = (x - cx) * ry / rx + cx;
  21681. d = projectPointToArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt);
  21682. xi = Math.cos(theta + dTheta) * rx + cx;
  21683. yi = Math.sin(theta + dTheta) * ry + cy;
  21684. break;
  21685. case CMD$3.R:
  21686. x0 = xi = data[i++];
  21687. y0 = yi = data[i++];
  21688. var width = data[i++];
  21689. var height = data[i++];
  21690. d = projectPointToRect(x0, y0, width, height, x, y, tmpPt);
  21691. break;
  21692. case CMD$3.Z:
  21693. d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, true);
  21694. xi = x0;
  21695. yi = y0;
  21696. break;
  21697. }
  21698. if (d < minDist) {
  21699. minDist = d;
  21700. out.set(tmpPt[0], tmpPt[1]);
  21701. }
  21702. }
  21703. return minDist;
  21704. } // Temporal varible for intermediate usage.
  21705. var pt0 = new Point();
  21706. var pt1 = new Point();
  21707. var pt2 = new Point();
  21708. var dir = new Point();
  21709. var dir2 = new Point();
  21710. /**
  21711. * Calculate a proper guide line based on the label position and graphic element definition
  21712. * @param label
  21713. * @param labelRect
  21714. * @param target
  21715. * @param targetRect
  21716. */
  21717. function updateLabelLinePoints(target, labelLineModel) {
  21718. if (!target) {
  21719. return;
  21720. }
  21721. var labelLine = target.getTextGuideLine();
  21722. var label = target.getTextContent(); // Needs to create text guide in each charts.
  21723. if (!(label && labelLine)) {
  21724. return;
  21725. }
  21726. var labelGuideConfig = target.textGuideLineConfig || {};
  21727. var points = [[0, 0], [0, 0], [0, 0]];
  21728. var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;
  21729. var labelRect = label.getBoundingRect().clone();
  21730. labelRect.applyTransform(label.getComputedTransform());
  21731. var minDist = Infinity;
  21732. var anchorPoint = labelGuideConfig.anchor;
  21733. var targetTransform = target.getComputedTransform();
  21734. var targetInversedTransform = targetTransform && invert([], targetTransform);
  21735. var len = labelLineModel.get('length2') || 0;
  21736. if (anchorPoint) {
  21737. pt2.copy(anchorPoint);
  21738. }
  21739. for (var i = 0; i < searchSpace.length; i++) {
  21740. var candidate = searchSpace[i];
  21741. getCandidateAnchor(candidate, 0, labelRect, pt0, dir);
  21742. Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.
  21743. pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.
  21744. var boundingRect = target.getBoundingRect();
  21745. var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path
  21746. if (dist < minDist) {
  21747. minDist = dist; // Transform back to global space.
  21748. pt1.transform(targetTransform);
  21749. pt2.transform(targetTransform);
  21750. pt2.toArray(points[0]);
  21751. pt1.toArray(points[1]);
  21752. pt0.toArray(points[2]);
  21753. }
  21754. }
  21755. limitTurnAngle(points, labelLineModel.get('minTurnAngle'));
  21756. labelLine.setShape({
  21757. points: points
  21758. });
  21759. } // Temporal variable for the limitTurnAngle function
  21760. var tmpArr = [];
  21761. var tmpProjPoint = new Point();
  21762. /**
  21763. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  21764. * @param linePoints
  21765. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  21766. */
  21767. function limitTurnAngle(linePoints, minTurnAngle) {
  21768. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  21769. return;
  21770. }
  21771. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  21772. // /pt1----pt2 (label)
  21773. // /
  21774. // pt0/
  21775. pt0.fromArray(linePoints[0]);
  21776. pt1.fromArray(linePoints[1]);
  21777. pt2.fromArray(linePoints[2]);
  21778. Point.sub(dir, pt0, pt1);
  21779. Point.sub(dir2, pt2, pt1);
  21780. var len1 = dir.len();
  21781. var len2 = dir2.len();
  21782. if (len1 < 1e-3 || len2 < 1e-3) {
  21783. return;
  21784. }
  21785. dir.scale(1 / len1);
  21786. dir2.scale(1 / len2);
  21787. var angleCos = dir.dot(dir2);
  21788. var minTurnAngleCos = Math.cos(minTurnAngle);
  21789. if (minTurnAngleCos < angleCos) {
  21790. // Smaller than minTurnAngle
  21791. // Calculate project point of pt0 on pt1-pt2
  21792. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  21793. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  21794. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  21795. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  21796. if (isNaN(t)) {
  21797. return;
  21798. }
  21799. if (t < 0) {
  21800. Point.copy(tmpProjPoint, pt1);
  21801. } else if (t > 1) {
  21802. Point.copy(tmpProjPoint, pt2);
  21803. }
  21804. tmpProjPoint.toArray(linePoints[1]);
  21805. }
  21806. }
  21807. /**
  21808. * Limit the angle of line and the surface
  21809. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  21810. */
  21811. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  21812. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  21813. return;
  21814. }
  21815. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  21816. pt0.fromArray(linePoints[0]);
  21817. pt1.fromArray(linePoints[1]);
  21818. pt2.fromArray(linePoints[2]);
  21819. Point.sub(dir, pt1, pt0);
  21820. Point.sub(dir2, pt2, pt1);
  21821. var len1 = dir.len();
  21822. var len2 = dir2.len();
  21823. if (len1 < 1e-3 || len2 < 1e-3) {
  21824. return;
  21825. }
  21826. dir.scale(1 / len1);
  21827. dir2.scale(1 / len2);
  21828. var angleCos = dir.dot(surfaceNormal);
  21829. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  21830. if (angleCos < maxSurfaceAngleCos) {
  21831. // Calculate project point of pt0 on pt1-pt2
  21832. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  21833. tmpProjPoint.fromArray(tmpArr);
  21834. var HALF_PI = Math.PI / 2;
  21835. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  21836. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  21837. if (newAngle >= HALF_PI) {
  21838. // parallel
  21839. Point.copy(tmpProjPoint, pt2);
  21840. } else {
  21841. // Calculate new projected length with limited minTurnAngle and get the new connect point
  21842. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  21843. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  21844. if (isNaN(t)) {
  21845. return;
  21846. }
  21847. if (t < 0) {
  21848. Point.copy(tmpProjPoint, pt1);
  21849. } else if (t > 1) {
  21850. Point.copy(tmpProjPoint, pt2);
  21851. }
  21852. }
  21853. tmpProjPoint.toArray(linePoints[1]);
  21854. }
  21855. }
  21856. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  21857. var isNormal = stateName === 'normal';
  21858. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  21859. stateObj.ignore = ignore; // Set smooth
  21860. var smooth = stateModel.get('smooth');
  21861. if (smooth && smooth === true) {
  21862. smooth = 0.3;
  21863. }
  21864. stateObj.shape = stateObj.shape || {};
  21865. if (smooth > 0) {
  21866. stateObj.shape.smooth = smooth;
  21867. }
  21868. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  21869. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  21870. }
  21871. function buildLabelLinePath(path, shape) {
  21872. var smooth = shape.smooth;
  21873. var points = shape.points;
  21874. if (!points) {
  21875. return;
  21876. }
  21877. path.moveTo(points[0][0], points[0][1]);
  21878. if (smooth > 0 && points.length >= 3) {
  21879. var len1 = dist(points[0], points[1]);
  21880. var len2 = dist(points[1], points[2]);
  21881. if (!len1 || !len2) {
  21882. path.lineTo(points[1][0], points[1][1]);
  21883. path.lineTo(points[2][0], points[2][1]);
  21884. return;
  21885. }
  21886. var moveLen = Math.min(len1, len2) * smooth;
  21887. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  21888. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  21889. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  21890. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  21891. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  21892. } else {
  21893. for (var i = 1; i < points.length; i++) {
  21894. path.lineTo(points[i][0], points[i][1]);
  21895. }
  21896. }
  21897. }
  21898. /**
  21899. * Create a label line if necessary and set it's style.
  21900. */
  21901. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  21902. var labelLine = targetEl.getTextGuideLine();
  21903. var label = targetEl.getTextContent();
  21904. if (!label) {
  21905. // Not show label line if there is no label.
  21906. if (labelLine) {
  21907. targetEl.removeTextGuideLine();
  21908. }
  21909. return;
  21910. }
  21911. var normalModel = statesModels.normal;
  21912. var showNormal = normalModel.get('show');
  21913. var labelIgnoreNormal = label.ignore;
  21914. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  21915. var stateName = DISPLAY_STATES[i];
  21916. var stateModel = statesModels[stateName];
  21917. var isNormal = stateName === 'normal';
  21918. if (stateModel) {
  21919. var stateShow = stateModel.get('show');
  21920. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  21921. if (isLabelIgnored // Not show when label is not shown in this state.
  21922. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  21923. ) {
  21924. var stateObj = isNormal ? labelLine : labelLine && labelLine.states.normal;
  21925. if (stateObj) {
  21926. stateObj.ignore = true;
  21927. }
  21928. continue;
  21929. } // Create labelLine if not exists
  21930. if (!labelLine) {
  21931. labelLine = new Polyline();
  21932. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  21933. // NOTE: NORMAL should always been the first!
  21934. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  21935. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  21936. } // Use same state proxy.
  21937. if (targetEl.stateProxy) {
  21938. labelLine.stateProxy = targetEl.stateProxy;
  21939. }
  21940. }
  21941. setLabelLineState(labelLine, false, stateName, stateModel);
  21942. }
  21943. }
  21944. if (labelLine) {
  21945. defaults(labelLine.style, defaultStyle); // Not fill.
  21946. labelLine.style.fill = null;
  21947. var showAbove = normalModel.get('showAbove');
  21948. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  21949. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  21950. labelLine.buildPath = buildLabelLinePath;
  21951. }
  21952. }
  21953. function getLabelLineStatesModels(itemModel, labelLineName) {
  21954. labelLineName = labelLineName || 'labelLine';
  21955. var statesModels = {
  21956. normal: itemModel.getModel(labelLineName)
  21957. };
  21958. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  21959. var stateName = SPECIAL_STATES[i];
  21960. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  21961. }
  21962. return statesModels;
  21963. }
  21964. function prepareLayoutList(input) {
  21965. var list = [];
  21966. for (var i = 0; i < input.length; i++) {
  21967. var rawItem = input[i];
  21968. if (rawItem.defaultAttr.ignore) {
  21969. continue;
  21970. }
  21971. var label = rawItem.label;
  21972. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  21973. var localRect = label.getBoundingRect();
  21974. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  21975. var minMargin = label.style.margin || 0;
  21976. var globalRect = localRect.clone();
  21977. globalRect.applyTransform(transform);
  21978. globalRect.x -= minMargin / 2;
  21979. globalRect.y -= minMargin / 2;
  21980. globalRect.width += minMargin;
  21981. globalRect.height += minMargin;
  21982. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  21983. list.push({
  21984. label: label,
  21985. labelLine: rawItem.labelLine,
  21986. rect: globalRect,
  21987. localRect: localRect,
  21988. obb: obb,
  21989. priority: rawItem.priority,
  21990. defaultAttr: rawItem.defaultAttr,
  21991. layoutOption: rawItem.computedLayoutOption,
  21992. axisAligned: isAxisAligned,
  21993. transform: transform
  21994. });
  21995. }
  21996. return list;
  21997. }
  21998. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  21999. var len = list.length;
  22000. if (len < 2) {
  22001. return;
  22002. }
  22003. list.sort(function (a, b) {
  22004. return a.rect[xyDim] - b.rect[xyDim];
  22005. });
  22006. var lastPos = 0;
  22007. var delta;
  22008. var adjusted = false;
  22009. var totalShifts = 0;
  22010. for (var i = 0; i < len; i++) {
  22011. var item = list[i];
  22012. var rect = item.rect;
  22013. delta = rect[xyDim] - lastPos;
  22014. if (delta < 0) {
  22015. // shiftForward(i, len, -delta);
  22016. rect[xyDim] -= delta;
  22017. item.label[xyDim] -= delta;
  22018. adjusted = true;
  22019. }
  22020. var shift = Math.max(-delta, 0);
  22021. totalShifts += shift;
  22022. lastPos = rect[xyDim] + rect[sizeDim];
  22023. }
  22024. if (totalShifts > 0 && balanceShift) {
  22025. // Shift back to make the distribution more equally.
  22026. shiftList(-totalShifts / len, 0, len);
  22027. } // TODO bleedMargin?
  22028. var first = list[0];
  22029. var last = list[len - 1];
  22030. var minGap;
  22031. var maxGap;
  22032. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  22033. minGap < 0 && squeezeGaps(-minGap, 0.8);
  22034. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  22035. updateMinMaxGap();
  22036. takeBoundsGap(minGap, maxGap, 1);
  22037. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  22038. updateMinMaxGap();
  22039. if (minGap < 0) {
  22040. squeezeWhenBailout(-minGap);
  22041. }
  22042. if (maxGap < 0) {
  22043. squeezeWhenBailout(maxGap);
  22044. }
  22045. function updateMinMaxGap() {
  22046. minGap = first.rect[xyDim] - minBound;
  22047. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  22048. }
  22049. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  22050. if (gapThisBound < 0) {
  22051. // Move from other gap if can.
  22052. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  22053. if (moveFromMaxGap > 0) {
  22054. shiftList(moveFromMaxGap * moveDir, 0, len);
  22055. var remained = moveFromMaxGap + gapThisBound;
  22056. if (remained < 0) {
  22057. squeezeGaps(-remained * moveDir, 1);
  22058. }
  22059. } else {
  22060. squeezeGaps(-gapThisBound * moveDir, 1);
  22061. }
  22062. }
  22063. }
  22064. function shiftList(delta, start, end) {
  22065. if (delta !== 0) {
  22066. adjusted = true;
  22067. }
  22068. for (var i = start; i < end; i++) {
  22069. var item = list[i];
  22070. var rect = item.rect;
  22071. rect[xyDim] += delta;
  22072. item.label[xyDim] += delta;
  22073. }
  22074. } // Squeeze gaps if the labels exceed margin.
  22075. function squeezeGaps(delta, maxSqeezePercent) {
  22076. var gaps = [];
  22077. var totalGaps = 0;
  22078. for (var i = 1; i < len; i++) {
  22079. var prevItemRect = list[i - 1].rect;
  22080. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  22081. gaps.push(gap);
  22082. totalGaps += gap;
  22083. }
  22084. if (!totalGaps) {
  22085. return;
  22086. }
  22087. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  22088. if (delta > 0) {
  22089. for (var i = 0; i < len - 1; i++) {
  22090. // Distribute the shift delta to all gaps.
  22091. var movement = gaps[i] * squeezePercent; // Forward
  22092. shiftList(movement, 0, i + 1);
  22093. }
  22094. } else {
  22095. // Backward
  22096. for (var i = len - 1; i > 0; i--) {
  22097. // Distribute the shift delta to all gaps.
  22098. var movement = gaps[i - 1] * squeezePercent;
  22099. shiftList(-movement, i, len);
  22100. }
  22101. }
  22102. }
  22103. /**
  22104. * Squeeze to allow overlap if there is no more space available.
  22105. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  22106. */
  22107. function squeezeWhenBailout(delta) {
  22108. var dir = delta < 0 ? -1 : 1;
  22109. delta = Math.abs(delta);
  22110. var moveForEachLabel = Math.ceil(delta / (len - 1));
  22111. for (var i = 0; i < len - 1; i++) {
  22112. if (dir > 0) {
  22113. // Forward
  22114. shiftList(moveForEachLabel, 0, i + 1);
  22115. } else {
  22116. // Backward
  22117. shiftList(-moveForEachLabel, len - i - 1, len);
  22118. }
  22119. delta -= moveForEachLabel;
  22120. if (delta <= 0) {
  22121. return;
  22122. }
  22123. }
  22124. }
  22125. return adjusted;
  22126. }
  22127. /**
  22128. * Adjust labels on x direction to avoid overlap.
  22129. */
  22130. function shiftLayoutOnX(list, leftBound, rightBound, // If average the shifts on all labels and add them to 0
  22131. // TODO: Not sure if should enable it.
  22132. // Pros: The angle of lines will distribute more equally
  22133. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  22134. balanceShift) {
  22135. return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift);
  22136. }
  22137. /**
  22138. * Adjust labels on y direction to avoid overlap.
  22139. */
  22140. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  22141. balanceShift) {
  22142. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  22143. }
  22144. function hideOverlap(labelList) {
  22145. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  22146. labelList.sort(function (a, b) {
  22147. return b.priority - a.priority;
  22148. });
  22149. var globalRect = new BoundingRect(0, 0, 0, 0);
  22150. function hideEl(el) {
  22151. if (!el.ignore) {
  22152. // Show on emphasis.
  22153. var emphasisState = el.ensureState('emphasis');
  22154. if (emphasisState.ignore == null) {
  22155. emphasisState.ignore = false;
  22156. }
  22157. }
  22158. el.ignore = true;
  22159. }
  22160. for (var i = 0; i < labelList.length; i++) {
  22161. var labelItem = labelList[i];
  22162. var isAxisAligned = labelItem.axisAligned;
  22163. var localRect = labelItem.localRect;
  22164. var transform = labelItem.transform;
  22165. var label = labelItem.label;
  22166. var labelLine = labelItem.labelLine;
  22167. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  22168. globalRect.width -= 0.1;
  22169. globalRect.height -= 0.1;
  22170. globalRect.x += 0.05;
  22171. globalRect.y += 0.05;
  22172. var obb = labelItem.obb;
  22173. var overlapped = false;
  22174. for (var j = 0; j < displayedLabels.length; j++) {
  22175. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  22176. if (!globalRect.intersect(existsTextCfg.rect)) {
  22177. continue;
  22178. }
  22179. if (isAxisAligned && existsTextCfg.axisAligned) {
  22180. // Is overlapped
  22181. overlapped = true;
  22182. break;
  22183. }
  22184. if (!existsTextCfg.obb) {
  22185. // If self is not axis aligned. But other is.
  22186. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  22187. }
  22188. if (!obb) {
  22189. // If self is axis aligned. But other is not.
  22190. obb = new OrientedBoundingRect(localRect, transform);
  22191. }
  22192. if (obb.intersect(existsTextCfg.obb)) {
  22193. overlapped = true;
  22194. break;
  22195. }
  22196. } // TODO Callback to determine if this overlap should be handled?
  22197. if (overlapped) {
  22198. hideEl(label);
  22199. labelLine && hideEl(labelLine);
  22200. } else {
  22201. label.attr('ignore', labelItem.defaultAttr.ignore);
  22202. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  22203. displayedLabels.push(labelItem);
  22204. }
  22205. }
  22206. }
  22207. function cloneArr(points) {
  22208. if (points) {
  22209. var newPoints = [];
  22210. for (var i = 0; i < points.length; i++) {
  22211. newPoints.push(points[i].slice());
  22212. }
  22213. return newPoints;
  22214. }
  22215. }
  22216. function prepareLayoutCallbackParams(labelItem, hostEl) {
  22217. var label = labelItem.label;
  22218. var labelLine = hostEl && hostEl.getTextGuideLine();
  22219. return {
  22220. dataIndex: labelItem.dataIndex,
  22221. dataType: labelItem.dataType,
  22222. seriesIndex: labelItem.seriesModel.seriesIndex,
  22223. text: labelItem.label.style.text,
  22224. rect: labelItem.hostRect,
  22225. labelRect: labelItem.rect,
  22226. // x: labelAttr.x,
  22227. // y: labelAttr.y,
  22228. align: label.style.align,
  22229. verticalAlign: label.style.verticalAlign,
  22230. labelLinePoints: cloneArr(labelLine && labelLine.shape.points)
  22231. };
  22232. }
  22233. var LABEL_OPTION_TO_STYLE_KEYS = ['align', 'verticalAlign', 'width', 'height', 'fontSize'];
  22234. var dummyTransformable = new Transformable();
  22235. var labelLayoutInnerStore = makeInner();
  22236. var labelLineAnimationStore = makeInner();
  22237. function extendWithKeys(target, source, keys) {
  22238. for (var i = 0; i < keys.length; i++) {
  22239. var key = keys[i];
  22240. if (source[key] != null) {
  22241. target[key] = source[key];
  22242. }
  22243. }
  22244. }
  22245. var LABEL_LAYOUT_PROPS = ['x', 'y', 'rotation'];
  22246. var LabelManager =
  22247. /** @class */
  22248. function () {
  22249. function LabelManager() {
  22250. this._labelList = [];
  22251. this._chartViewList = [];
  22252. }
  22253. LabelManager.prototype.clearLabels = function () {
  22254. this._labelList = [];
  22255. this._chartViewList = [];
  22256. };
  22257. /**
  22258. * Add label to manager
  22259. */
  22260. LabelManager.prototype._addLabel = function (dataIndex, dataType, seriesModel, label, layoutOption) {
  22261. var labelStyle = label.style;
  22262. var hostEl = label.__hostTarget;
  22263. var textConfig = hostEl.textConfig || {}; // TODO: If label is in other state.
  22264. var labelTransform = label.getComputedTransform();
  22265. var labelRect = label.getBoundingRect().plain();
  22266. BoundingRect.applyTransform(labelRect, labelRect, labelTransform);
  22267. if (labelTransform) {
  22268. dummyTransformable.setLocalTransform(labelTransform);
  22269. } else {
  22270. // Identity transform.
  22271. dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0;
  22272. dummyTransformable.scaleX = dummyTransformable.scaleY = 1;
  22273. }
  22274. var host = label.__hostTarget;
  22275. var hostRect;
  22276. if (host) {
  22277. hostRect = host.getBoundingRect().plain();
  22278. var transform = host.getComputedTransform();
  22279. BoundingRect.applyTransform(hostRect, hostRect, transform);
  22280. }
  22281. var labelGuide = hostRect && host.getTextGuideLine();
  22282. this._labelList.push({
  22283. label: label,
  22284. labelLine: labelGuide,
  22285. seriesModel: seriesModel,
  22286. dataIndex: dataIndex,
  22287. dataType: dataType,
  22288. layoutOption: layoutOption,
  22289. computedLayoutOption: null,
  22290. rect: labelRect,
  22291. hostRect: hostRect,
  22292. // Label with lower priority will be hidden when overlapped
  22293. // Use rect size as default priority
  22294. priority: hostRect ? hostRect.width * hostRect.height : 0,
  22295. // Save default label attributes.
  22296. // For restore if developers want get back to default value in callback.
  22297. defaultAttr: {
  22298. ignore: label.ignore,
  22299. labelGuideIgnore: labelGuide && labelGuide.ignore,
  22300. x: dummyTransformable.x,
  22301. y: dummyTransformable.y,
  22302. rotation: dummyTransformable.rotation,
  22303. style: {
  22304. x: labelStyle.x,
  22305. y: labelStyle.y,
  22306. align: labelStyle.align,
  22307. verticalAlign: labelStyle.verticalAlign,
  22308. width: labelStyle.width,
  22309. height: labelStyle.height,
  22310. fontSize: labelStyle.fontSize
  22311. },
  22312. cursor: label.cursor,
  22313. attachedPos: textConfig.position,
  22314. attachedRot: textConfig.rotation
  22315. }
  22316. });
  22317. };
  22318. LabelManager.prototype.addLabelsOfSeries = function (chartView) {
  22319. var _this = this;
  22320. this._chartViewList.push(chartView);
  22321. var seriesModel = chartView.__model;
  22322. var layoutOption = seriesModel.get('labelLayout');
  22323. /**
  22324. * Ignore layouting if it's not specified anything.
  22325. */
  22326. if (!(isFunction(layoutOption) || keys(layoutOption).length)) {
  22327. return;
  22328. }
  22329. chartView.group.traverse(function (child) {
  22330. if (child.ignore) {
  22331. return true; // Stop traverse descendants.
  22332. } // Only support label being hosted on graphic elements.
  22333. var textEl = child.getTextContent();
  22334. var ecData = getECData(child); // Can only attach the text on the element with dataIndex
  22335. if (textEl && !textEl.disableLabelLayout) {
  22336. _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption);
  22337. }
  22338. });
  22339. };
  22340. LabelManager.prototype.updateLayoutConfig = function (api) {
  22341. var width = api.getWidth();
  22342. var height = api.getHeight();
  22343. function createDragHandler(el, labelLineModel) {
  22344. return function () {
  22345. updateLabelLinePoints(el, labelLineModel);
  22346. };
  22347. }
  22348. for (var i = 0; i < this._labelList.length; i++) {
  22349. var labelItem = this._labelList[i];
  22350. var label = labelItem.label;
  22351. var hostEl = label.__hostTarget;
  22352. var defaultLabelAttr = labelItem.defaultAttr;
  22353. var layoutOption = void 0; // TODO A global layout option?
  22354. if (typeof labelItem.layoutOption === 'function') {
  22355. layoutOption = labelItem.layoutOption(prepareLayoutCallbackParams(labelItem, hostEl));
  22356. } else {
  22357. layoutOption = labelItem.layoutOption;
  22358. }
  22359. layoutOption = layoutOption || {};
  22360. labelItem.computedLayoutOption = layoutOption;
  22361. var degreeToRadian = Math.PI / 180;
  22362. if (hostEl) {
  22363. hostEl.setTextConfig({
  22364. // Force to set local false.
  22365. local: false,
  22366. // Ignore position and rotation config on the host el if x or y is changed.
  22367. position: layoutOption.x != null || layoutOption.y != null ? null : defaultLabelAttr.attachedPos,
  22368. // Ignore rotation config on the host el if rotation is changed.
  22369. rotation: layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot,
  22370. offset: [layoutOption.dx || 0, layoutOption.dy || 0]
  22371. });
  22372. }
  22373. var needsUpdateLabelLine = false;
  22374. if (layoutOption.x != null) {
  22375. // TODO width of chart view.
  22376. label.x = parsePercent$1(layoutOption.x, width);
  22377. label.setStyle('x', 0); // Ignore movement in style. TODO: origin.
  22378. needsUpdateLabelLine = true;
  22379. } else {
  22380. label.x = defaultLabelAttr.x;
  22381. label.setStyle('x', defaultLabelAttr.style.x);
  22382. }
  22383. if (layoutOption.y != null) {
  22384. // TODO height of chart view.
  22385. label.y = parsePercent$1(layoutOption.y, height);
  22386. label.setStyle('y', 0); // Ignore movement in style.
  22387. needsUpdateLabelLine = true;
  22388. } else {
  22389. label.y = defaultLabelAttr.y;
  22390. label.setStyle('y', defaultLabelAttr.style.y);
  22391. }
  22392. if (layoutOption.labelLinePoints) {
  22393. var guideLine = hostEl.getTextGuideLine();
  22394. if (guideLine) {
  22395. guideLine.setShape({
  22396. points: layoutOption.labelLinePoints
  22397. }); // Not update
  22398. needsUpdateLabelLine = false;
  22399. }
  22400. }
  22401. var labelLayoutStore = labelLayoutInnerStore(label);
  22402. labelLayoutStore.needsUpdateLabelLine = needsUpdateLabelLine;
  22403. label.rotation = layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation;
  22404. for (var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++) {
  22405. var key = LABEL_OPTION_TO_STYLE_KEYS[k];
  22406. label.setStyle(key, layoutOption[key] != null ? layoutOption[key] : defaultLabelAttr.style[key]);
  22407. }
  22408. if (layoutOption.draggable) {
  22409. label.draggable = true;
  22410. label.cursor = 'move';
  22411. if (hostEl) {
  22412. var hostModel = labelItem.seriesModel;
  22413. if (labelItem.dataIndex != null) {
  22414. var data = labelItem.seriesModel.getData(labelItem.dataType);
  22415. hostModel = data.getItemModel(labelItem.dataIndex);
  22416. }
  22417. label.on('drag', createDragHandler(hostEl, hostModel.getModel('labelLine')));
  22418. }
  22419. } else {
  22420. // TODO Other drag functions?
  22421. label.off('drag');
  22422. label.cursor = defaultLabelAttr.cursor;
  22423. }
  22424. }
  22425. };
  22426. LabelManager.prototype.layout = function (api) {
  22427. var width = api.getWidth();
  22428. var height = api.getHeight();
  22429. var labelList = prepareLayoutList(this._labelList);
  22430. var labelsNeedsAdjustOnX = filter(labelList, function (item) {
  22431. return item.layoutOption.moveOverlap === 'shiftX';
  22432. });
  22433. var labelsNeedsAdjustOnY = filter(labelList, function (item) {
  22434. return item.layoutOption.moveOverlap === 'shiftY';
  22435. });
  22436. shiftLayoutOnX(labelsNeedsAdjustOnX, 0, width);
  22437. shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height);
  22438. var labelsNeedsHideOverlap = filter(labelList, function (item) {
  22439. return item.layoutOption.hideOverlap;
  22440. });
  22441. hideOverlap(labelsNeedsHideOverlap);
  22442. };
  22443. /**
  22444. * Process all labels. Not only labels with layoutOption.
  22445. */
  22446. LabelManager.prototype.processLabelsOverall = function () {
  22447. var _this = this;
  22448. each(this._chartViewList, function (chartView) {
  22449. var seriesModel = chartView.__model;
  22450. var ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate;
  22451. var animationEnabled = seriesModel.isAnimationEnabled();
  22452. chartView.group.traverse(function (child) {
  22453. if (child.ignore) {
  22454. return true; // Stop traverse descendants.
  22455. }
  22456. var needsUpdateLabelLine = !ignoreLabelLineUpdate;
  22457. var label = child.getTextContent();
  22458. if (!needsUpdateLabelLine && label) {
  22459. needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine;
  22460. }
  22461. if (needsUpdateLabelLine) {
  22462. _this._updateLabelLine(child, seriesModel);
  22463. }
  22464. if (animationEnabled) {
  22465. _this._animateLabels(child, seriesModel);
  22466. }
  22467. });
  22468. });
  22469. };
  22470. LabelManager.prototype._updateLabelLine = function (el, seriesModel) {
  22471. // Only support label being hosted on graphic elements.
  22472. var textEl = el.getTextContent(); // Update label line style.
  22473. var ecData = getECData(el);
  22474. var dataIndex = ecData.dataIndex; // Only support labelLine on the labels represent data.
  22475. if (textEl && dataIndex != null) {
  22476. var data = seriesModel.getData(ecData.dataType);
  22477. var itemModel = data.getItemModel(dataIndex);
  22478. var defaultStyle = {};
  22479. var visualStyle = data.getItemVisual(dataIndex, 'style');
  22480. var visualType = data.getVisual('drawType'); // Default to be same with main color
  22481. defaultStyle.stroke = visualStyle[visualType];
  22482. var labelLineModel = itemModel.getModel('labelLine');
  22483. setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle);
  22484. updateLabelLinePoints(el, labelLineModel);
  22485. }
  22486. };
  22487. LabelManager.prototype._animateLabels = function (el, seriesModel) {
  22488. var textEl = el.getTextContent();
  22489. var guideLine = el.getTextGuideLine(); // Animate
  22490. if (textEl && !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el)) {
  22491. var layoutStore = labelLayoutInnerStore(textEl);
  22492. var oldLayout = layoutStore.oldLayout;
  22493. var ecData = getECData(el);
  22494. var dataIndex = ecData.dataIndex;
  22495. var newProps = {
  22496. x: textEl.x,
  22497. y: textEl.y,
  22498. rotation: textEl.rotation
  22499. };
  22500. var data = seriesModel.getData(ecData.dataType);
  22501. if (!oldLayout) {
  22502. textEl.attr(newProps); // Disable fade in animation if value animation is enabled.
  22503. if (!labelInner(textEl).valueAnimation) {
  22504. var oldOpacity = retrieve2(textEl.style.opacity, 1); // Fade in animation
  22505. textEl.style.opacity = 0;
  22506. initProps(textEl, {
  22507. style: {
  22508. opacity: oldOpacity
  22509. }
  22510. }, seriesModel, dataIndex);
  22511. }
  22512. } else {
  22513. textEl.attr(oldLayout); // Make sure the animation from is in the right status.
  22514. var prevStates = el.prevStates;
  22515. if (prevStates) {
  22516. if (indexOf(prevStates, 'select') >= 0) {
  22517. textEl.attr(layoutStore.oldLayoutSelect);
  22518. }
  22519. if (indexOf(prevStates, 'emphasis') >= 0) {
  22520. textEl.attr(layoutStore.oldLayoutEmphasis);
  22521. }
  22522. }
  22523. updateProps(textEl, newProps, seriesModel, dataIndex);
  22524. }
  22525. layoutStore.oldLayout = newProps;
  22526. if (textEl.states.select) {
  22527. var layoutSelect = layoutStore.oldLayoutSelect = {};
  22528. extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS);
  22529. extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS);
  22530. }
  22531. if (textEl.states.emphasis) {
  22532. var layoutEmphasis = layoutStore.oldLayoutEmphasis = {};
  22533. extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS);
  22534. extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS);
  22535. }
  22536. animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel);
  22537. }
  22538. if (guideLine && !guideLine.ignore && !guideLine.invisible) {
  22539. var layoutStore = labelLineAnimationStore(guideLine);
  22540. var oldLayout = layoutStore.oldLayout;
  22541. var newLayout = {
  22542. points: guideLine.shape.points
  22543. };
  22544. if (!oldLayout) {
  22545. guideLine.setShape(newLayout);
  22546. guideLine.style.strokePercent = 0;
  22547. initProps(guideLine, {
  22548. style: {
  22549. strokePercent: 1
  22550. }
  22551. }, seriesModel);
  22552. } else {
  22553. guideLine.attr({
  22554. shape: oldLayout
  22555. });
  22556. updateProps(guideLine, {
  22557. shape: newLayout
  22558. }, seriesModel);
  22559. }
  22560. layoutStore.oldLayout = newLayout;
  22561. }
  22562. };
  22563. return LabelManager;
  22564. }();
  22565. // Inlucdes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  22566. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  22567. function getSeriesIndices(ecModel, payload) {
  22568. var seriesIndices = [];
  22569. ecModel.eachComponent({
  22570. mainType: 'series',
  22571. subType: seriesType,
  22572. query: payload
  22573. }, function (seriesModel) {
  22574. seriesIndices.push(seriesModel.seriesIndex);
  22575. });
  22576. return seriesIndices;
  22577. }
  22578. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  22579. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  22580. payload = extend({}, payload);
  22581. if ("development" !== 'production') {
  22582. deprecateReplaceLog(payload.type, eventsMap[1]);
  22583. }
  22584. api.dispatchAction(extend(payload, {
  22585. type: eventsMap[1],
  22586. seriesIndex: getSeriesIndices(ecModel, payload)
  22587. }));
  22588. });
  22589. });
  22590. }
  22591. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  22592. var legacyEventName = type + eventPostfix;
  22593. if (!ecIns.isSilent(legacyEventName)) {
  22594. if ("development" !== 'production') {
  22595. deprecateLog("event " + legacyEventName + " is deprecated.");
  22596. }
  22597. ecModel.eachComponent({
  22598. mainType: 'series',
  22599. subType: 'pie'
  22600. }, function (seriesModel) {
  22601. var seriesIndex = seriesModel.seriesIndex;
  22602. var selected = payload.selected;
  22603. for (var i = 0; i < selected.length; i++) {
  22604. if (selected[i].seriesIndex === seriesIndex) {
  22605. var data = seriesModel.getData();
  22606. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  22607. ecIns.trigger(legacyEventName, {
  22608. type: legacyEventName,
  22609. seriesId: seriesModel.id,
  22610. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  22611. selected: extend({}, seriesModel.option.selectedMap)
  22612. });
  22613. }
  22614. }
  22615. });
  22616. }
  22617. }
  22618. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  22619. messageCenter.on('selectchanged', function (params) {
  22620. var ecModel = api.getModel();
  22621. if (params.isFromClick) {
  22622. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  22623. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  22624. } else if (params.fromAction === 'select') {
  22625. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  22626. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  22627. } else if (params.fromAction === 'unselect') {
  22628. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  22629. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  22630. }
  22631. });
  22632. }
  22633. /*
  22634. * Licensed to the Apache Software Foundation (ASF) under one
  22635. * or more contributor license agreements. See the NOTICE file
  22636. * distributed with this work for additional information
  22637. * regarding copyright ownership. The ASF licenses this file
  22638. * to you under the Apache License, Version 2.0 (the
  22639. * "License"); you may not use this file except in compliance
  22640. * with the License. You may obtain a copy of the License at
  22641. *
  22642. * http://www.apache.org/licenses/LICENSE-2.0
  22643. *
  22644. * Unless required by applicable law or agreed to in writing,
  22645. * software distributed under the License is distributed on an
  22646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22647. * KIND, either express or implied. See the License for the
  22648. * specific language governing permissions and limitations
  22649. * under the License.
  22650. */
  22651. /**
  22652. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22653. */
  22654. /*
  22655. * Licensed to the Apache Software Foundation (ASF) under one
  22656. * or more contributor license agreements. See the NOTICE file
  22657. * distributed with this work for additional information
  22658. * regarding copyright ownership. The ASF licenses this file
  22659. * to you under the Apache License, Version 2.0 (the
  22660. * "License"); you may not use this file except in compliance
  22661. * with the License. You may obtain a copy of the License at
  22662. *
  22663. * http://www.apache.org/licenses/LICENSE-2.0
  22664. *
  22665. * Unless required by applicable law or agreed to in writing,
  22666. * software distributed under the License is distributed on an
  22667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22668. * KIND, either express or implied. See the License for the
  22669. * specific language governing permissions and limitations
  22670. * under the License.
  22671. */
  22672. function findEventDispatcher(target, det, returnFirstMatch) {
  22673. var found;
  22674. while (target) {
  22675. if (det(target)) {
  22676. found = target;
  22677. if (returnFirstMatch) {
  22678. break;
  22679. }
  22680. }
  22681. target = target.__hostTarget || target.parent;
  22682. }
  22683. return found;
  22684. }
  22685. var wmUniqueIndex = Math.round(Math.random() * 9);
  22686. var WeakMap = (function () {
  22687. function WeakMap() {
  22688. this._id = '__ec_inner_' + wmUniqueIndex++;
  22689. }
  22690. WeakMap.prototype.get = function (key) {
  22691. return this._guard(key)[this._id];
  22692. };
  22693. WeakMap.prototype.set = function (key, value) {
  22694. var target = this._guard(key);
  22695. if (typeof Object.defineProperty === 'function') {
  22696. Object.defineProperty(target, this._id, {
  22697. value: value,
  22698. enumerable: false,
  22699. configurable: true
  22700. });
  22701. }
  22702. else {
  22703. target[this._id] = value;
  22704. }
  22705. return this;
  22706. };
  22707. WeakMap.prototype["delete"] = function (key) {
  22708. if (this.has(key)) {
  22709. delete this._guard(key)[this._id];
  22710. return true;
  22711. }
  22712. return false;
  22713. };
  22714. WeakMap.prototype.has = function (key) {
  22715. return !!this._guard(key)[this._id];
  22716. };
  22717. WeakMap.prototype._guard = function (key) {
  22718. if (key !== Object(key)) {
  22719. throw TypeError('Value of WeakMap is not a non-null object.');
  22720. }
  22721. return key;
  22722. };
  22723. return WeakMap;
  22724. }());
  22725. /**
  22726. * Triangle shape
  22727. * @inner
  22728. */
  22729. var Triangle = Path.extend({
  22730. type: 'triangle',
  22731. shape: {
  22732. cx: 0,
  22733. cy: 0,
  22734. width: 0,
  22735. height: 0
  22736. },
  22737. buildPath: function (path, shape) {
  22738. var cx = shape.cx;
  22739. var cy = shape.cy;
  22740. var width = shape.width / 2;
  22741. var height = shape.height / 2;
  22742. path.moveTo(cx, cy - height);
  22743. path.lineTo(cx + width, cy + height);
  22744. path.lineTo(cx - width, cy + height);
  22745. path.closePath();
  22746. }
  22747. });
  22748. /**
  22749. * Diamond shape
  22750. * @inner
  22751. */
  22752. var Diamond = Path.extend({
  22753. type: 'diamond',
  22754. shape: {
  22755. cx: 0,
  22756. cy: 0,
  22757. width: 0,
  22758. height: 0
  22759. },
  22760. buildPath: function (path, shape) {
  22761. var cx = shape.cx;
  22762. var cy = shape.cy;
  22763. var width = shape.width / 2;
  22764. var height = shape.height / 2;
  22765. path.moveTo(cx, cy - height);
  22766. path.lineTo(cx + width, cy);
  22767. path.lineTo(cx, cy + height);
  22768. path.lineTo(cx - width, cy);
  22769. path.closePath();
  22770. }
  22771. });
  22772. /**
  22773. * Pin shape
  22774. * @inner
  22775. */
  22776. var Pin = Path.extend({
  22777. type: 'pin',
  22778. shape: {
  22779. // x, y on the cusp
  22780. x: 0,
  22781. y: 0,
  22782. width: 0,
  22783. height: 0
  22784. },
  22785. buildPath: function (path, shape) {
  22786. var x = shape.x;
  22787. var y = shape.y;
  22788. var w = shape.width / 5 * 3; // Height must be larger than width
  22789. var h = Math.max(w, shape.height);
  22790. var r = w / 2; // Dist on y with tangent point and circle center
  22791. var dy = r * r / (h - r);
  22792. var cy = y - h + r + dy;
  22793. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  22794. var dx = Math.cos(angle) * r;
  22795. var tanX = Math.sin(angle);
  22796. var tanY = Math.cos(angle);
  22797. var cpLen = r * 0.6;
  22798. var cpLen2 = r * 0.7;
  22799. path.moveTo(x - dx, cy + dy);
  22800. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  22801. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  22802. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  22803. path.closePath();
  22804. }
  22805. });
  22806. /**
  22807. * Arrow shape
  22808. * @inner
  22809. */
  22810. var Arrow = Path.extend({
  22811. type: 'arrow',
  22812. shape: {
  22813. x: 0,
  22814. y: 0,
  22815. width: 0,
  22816. height: 0
  22817. },
  22818. buildPath: function (ctx, shape) {
  22819. var height = shape.height;
  22820. var width = shape.width;
  22821. var x = shape.x;
  22822. var y = shape.y;
  22823. var dx = width / 3 * 2;
  22824. ctx.moveTo(x, y);
  22825. ctx.lineTo(x + dx, y + height);
  22826. ctx.lineTo(x, y + height / 4 * 3);
  22827. ctx.lineTo(x - dx, y + height);
  22828. ctx.lineTo(x, y);
  22829. ctx.closePath();
  22830. }
  22831. });
  22832. /**
  22833. * Map of path contructors
  22834. */
  22835. // TODO Use function to build symbol path.
  22836. var symbolCtors = {
  22837. // Use small height rect to simulate line.
  22838. // Avoid using stroke.
  22839. line: Rect,
  22840. rect: Rect,
  22841. roundRect: Rect,
  22842. square: Rect,
  22843. circle: Circle,
  22844. diamond: Diamond,
  22845. pin: Pin,
  22846. arrow: Arrow,
  22847. triangle: Triangle
  22848. }; // NOTICE Only use fill. No line!
  22849. var symbolShapeMakers = {
  22850. line: function (x, y, w, h, shape) {
  22851. var thickness = 2; // A thin line
  22852. shape.x = x;
  22853. shape.y = y + h / 2 - thickness / 2;
  22854. shape.width = w;
  22855. shape.height = thickness;
  22856. },
  22857. rect: function (x, y, w, h, shape) {
  22858. shape.x = x;
  22859. shape.y = y;
  22860. shape.width = w;
  22861. shape.height = h;
  22862. },
  22863. roundRect: function (x, y, w, h, shape) {
  22864. shape.x = x;
  22865. shape.y = y;
  22866. shape.width = w;
  22867. shape.height = h;
  22868. shape.r = Math.min(w, h) / 4;
  22869. },
  22870. square: function (x, y, w, h, shape) {
  22871. var size = Math.min(w, h);
  22872. shape.x = x;
  22873. shape.y = y;
  22874. shape.width = size;
  22875. shape.height = size;
  22876. },
  22877. circle: function (x, y, w, h, shape) {
  22878. // Put circle in the center of square
  22879. shape.cx = x + w / 2;
  22880. shape.cy = y + h / 2;
  22881. shape.r = Math.min(w, h) / 2;
  22882. },
  22883. diamond: function (x, y, w, h, shape) {
  22884. shape.cx = x + w / 2;
  22885. shape.cy = y + h / 2;
  22886. shape.width = w;
  22887. shape.height = h;
  22888. },
  22889. pin: function (x, y, w, h, shape) {
  22890. shape.x = x + w / 2;
  22891. shape.y = y + h / 2;
  22892. shape.width = w;
  22893. shape.height = h;
  22894. },
  22895. arrow: function (x, y, w, h, shape) {
  22896. shape.x = x + w / 2;
  22897. shape.y = y + h / 2;
  22898. shape.width = w;
  22899. shape.height = h;
  22900. },
  22901. triangle: function (x, y, w, h, shape) {
  22902. shape.cx = x + w / 2;
  22903. shape.cy = y + h / 2;
  22904. shape.width = w;
  22905. shape.height = h;
  22906. }
  22907. };
  22908. var symbolBuildProxies = {};
  22909. each(symbolCtors, function (Ctor, name) {
  22910. symbolBuildProxies[name] = new Ctor();
  22911. });
  22912. var SymbolClz = Path.extend({
  22913. type: 'symbol',
  22914. shape: {
  22915. symbolType: '',
  22916. x: 0,
  22917. y: 0,
  22918. width: 0,
  22919. height: 0
  22920. },
  22921. calculateTextPosition: function (out, config, rect) {
  22922. var res = calculateTextPosition(out, config, rect);
  22923. var shape = this.shape;
  22924. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  22925. res.y = rect.y + rect.height * 0.4;
  22926. }
  22927. return res;
  22928. },
  22929. buildPath: function (ctx, shape, inBundle) {
  22930. var symbolType = shape.symbolType;
  22931. if (symbolType !== 'none') {
  22932. var proxySymbol = symbolBuildProxies[symbolType];
  22933. if (!proxySymbol) {
  22934. // Default rect
  22935. symbolType = 'rect';
  22936. proxySymbol = symbolBuildProxies[symbolType];
  22937. }
  22938. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  22939. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  22940. }
  22941. }
  22942. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  22943. function symbolPathSetColor(color, innerColor) {
  22944. if (this.type !== 'image') {
  22945. var symbolStyle = this.style;
  22946. if (this.__isEmptyBrush) {
  22947. symbolStyle.stroke = color;
  22948. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView.
  22949. symbolStyle.lineWidth = 2;
  22950. } else {
  22951. symbolStyle.fill = color;
  22952. }
  22953. this.markRedraw();
  22954. }
  22955. }
  22956. /**
  22957. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  22958. */
  22959. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  22960. keepAspect) {
  22961. // TODO Support image object, DynamicImage.
  22962. var isEmpty = symbolType.indexOf('empty') === 0;
  22963. if (isEmpty) {
  22964. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  22965. }
  22966. var symbolPath;
  22967. if (symbolType.indexOf('image://') === 0) {
  22968. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  22969. } else if (symbolType.indexOf('path://') === 0) {
  22970. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  22971. } else {
  22972. symbolPath = new SymbolClz({
  22973. shape: {
  22974. symbolType: symbolType,
  22975. x: x,
  22976. y: y,
  22977. width: w,
  22978. height: h
  22979. }
  22980. });
  22981. }
  22982. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  22983. symbolPath.setColor = symbolPathSetColor;
  22984. if (color) {
  22985. symbolPath.setColor(color);
  22986. }
  22987. return symbolPath;
  22988. }
  22989. function createLinearGradient(ctx, obj, rect) {
  22990. var x = obj.x == null ? 0 : obj.x;
  22991. var x2 = obj.x2 == null ? 1 : obj.x2;
  22992. var y = obj.y == null ? 0 : obj.y;
  22993. var y2 = obj.y2 == null ? 0 : obj.y2;
  22994. if (!obj.global) {
  22995. x = x * rect.width + rect.x;
  22996. x2 = x2 * rect.width + rect.x;
  22997. y = y * rect.height + rect.y;
  22998. y2 = y2 * rect.height + rect.y;
  22999. }
  23000. x = isNaN(x) ? 0 : x;
  23001. x2 = isNaN(x2) ? 1 : x2;
  23002. y = isNaN(y) ? 0 : y;
  23003. y2 = isNaN(y2) ? 0 : y2;
  23004. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  23005. return canvasGradient;
  23006. }
  23007. function createRadialGradient(ctx, obj, rect) {
  23008. var width = rect.width;
  23009. var height = rect.height;
  23010. var min = Math.min(width, height);
  23011. var x = obj.x == null ? 0.5 : obj.x;
  23012. var y = obj.y == null ? 0.5 : obj.y;
  23013. var r = obj.r == null ? 0.5 : obj.r;
  23014. if (!obj.global) {
  23015. x = x * width + rect.x;
  23016. y = y * height + rect.y;
  23017. r = r * min;
  23018. }
  23019. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  23020. return canvasGradient;
  23021. }
  23022. function getCanvasGradient(ctx, obj, rect) {
  23023. var canvasGradient = obj.type === 'radial'
  23024. ? createRadialGradient(ctx, obj, rect)
  23025. : createLinearGradient(ctx, obj, rect);
  23026. var colorStops = obj.colorStops;
  23027. for (var i = 0; i < colorStops.length; i++) {
  23028. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  23029. }
  23030. return canvasGradient;
  23031. }
  23032. function isClipPathChanged(clipPaths, prevClipPaths) {
  23033. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  23034. return false;
  23035. }
  23036. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  23037. return true;
  23038. }
  23039. for (var i = 0; i < clipPaths.length; i++) {
  23040. if (clipPaths[i] !== prevClipPaths[i]) {
  23041. return true;
  23042. }
  23043. }
  23044. return false;
  23045. }
  23046. function normalizeLineDash(lineType, lineWidth) {
  23047. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  23048. return null;
  23049. }
  23050. lineWidth = lineWidth || 1;
  23051. return lineType === 'dashed'
  23052. ? [4 * lineWidth, 2 * lineWidth]
  23053. : lineType === 'dotted'
  23054. ? [lineWidth]
  23055. : isNumber(lineType)
  23056. ? [lineType] : isArray(lineType) ? lineType : null;
  23057. }
  23058. var pathProxyForDraw = new PathProxy(true);
  23059. function styleHasStroke(style) {
  23060. var stroke = style.stroke;
  23061. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  23062. }
  23063. function styleHasFill(style) {
  23064. var fill = style.fill;
  23065. return fill != null && fill !== 'none';
  23066. }
  23067. function doFillPath(ctx, style) {
  23068. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  23069. var originalGlobalAlpha = ctx.globalAlpha;
  23070. ctx.globalAlpha = style.fillOpacity * style.opacity;
  23071. ctx.fill();
  23072. ctx.globalAlpha = originalGlobalAlpha;
  23073. }
  23074. else {
  23075. ctx.fill();
  23076. }
  23077. }
  23078. function doStrokePath(ctx, style) {
  23079. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  23080. var originalGlobalAlpha = ctx.globalAlpha;
  23081. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  23082. ctx.stroke();
  23083. ctx.globalAlpha = originalGlobalAlpha;
  23084. }
  23085. else {
  23086. ctx.stroke();
  23087. }
  23088. }
  23089. function createCanvasPattern(ctx, pattern, el) {
  23090. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  23091. if (isImageReady(image)) {
  23092. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  23093. if (typeof DOMMatrix === 'function') {
  23094. var matrix = new DOMMatrix();
  23095. matrix.rotateSelf(0, 0, (pattern.rotation || 0) / Math.PI * 180);
  23096. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  23097. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  23098. canvasPattern.setTransform(matrix);
  23099. }
  23100. return canvasPattern;
  23101. }
  23102. }
  23103. function brushPath(ctx, el, style, inBatch) {
  23104. var hasStroke = styleHasStroke(style);
  23105. var hasFill = styleHasFill(style);
  23106. var strokePercent = style.strokePercent;
  23107. var strokePart = strokePercent < 1;
  23108. var firstDraw = !el.path;
  23109. if ((!el.silent || strokePart) && firstDraw) {
  23110. el.createPathProxy();
  23111. }
  23112. var path = el.path || pathProxyForDraw;
  23113. if (!inBatch) {
  23114. var fill = style.fill;
  23115. var stroke = style.stroke;
  23116. var hasFillGradient = hasFill && !!fill.colorStops;
  23117. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  23118. var hasFillPattern = hasFill && !!fill.image;
  23119. var hasStrokePattern = hasStroke && !!stroke.image;
  23120. var fillGradient = void 0;
  23121. var strokeGradient = void 0;
  23122. var fillPattern = void 0;
  23123. var strokePattern = void 0;
  23124. var rect = void 0;
  23125. if (hasFillGradient || hasStrokeGradient) {
  23126. rect = el.getBoundingRect();
  23127. }
  23128. if (hasFillGradient) {
  23129. fillGradient = el.__dirty
  23130. ? getCanvasGradient(ctx, fill, rect)
  23131. : el.__canvasFillGradient;
  23132. el.__canvasFillGradient = fillGradient;
  23133. }
  23134. if (hasStrokeGradient) {
  23135. strokeGradient = el.__dirty
  23136. ? getCanvasGradient(ctx, stroke, rect)
  23137. : el.__canvasStrokeGradient;
  23138. el.__canvasStrokeGradient = strokeGradient;
  23139. }
  23140. if (hasFillPattern) {
  23141. fillPattern = (el.__dirty || !el.__canvasFillPattern)
  23142. ? createCanvasPattern(ctx, fill, el)
  23143. : el.__canvasFillPattern;
  23144. el.__canvasFillPattern = fillPattern;
  23145. }
  23146. if (hasStrokePattern) {
  23147. strokePattern = (el.__dirty || !el.__canvasStrokePattern)
  23148. ? createCanvasPattern(ctx, stroke, el)
  23149. : el.__canvasStrokePattern;
  23150. el.__canvasStrokePattern = fillPattern;
  23151. }
  23152. if (hasFillGradient) {
  23153. ctx.fillStyle = fillGradient;
  23154. }
  23155. else if (hasFillPattern) {
  23156. if (fillPattern) {
  23157. ctx.fillStyle = fillPattern;
  23158. }
  23159. else {
  23160. hasFill = false;
  23161. }
  23162. }
  23163. if (hasStrokeGradient) {
  23164. ctx.strokeStyle = strokeGradient;
  23165. }
  23166. else if (hasStrokePattern) {
  23167. if (strokePattern) {
  23168. ctx.strokeStyle = strokePattern;
  23169. }
  23170. else {
  23171. hasStroke = false;
  23172. }
  23173. }
  23174. }
  23175. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  23176. var lineDashOffset = style.lineDashOffset;
  23177. var ctxLineDash = !!ctx.setLineDash;
  23178. var scale = el.getGlobalScale();
  23179. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  23180. if (lineDash) {
  23181. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  23182. if (lineScale_1 && lineScale_1 !== 1) {
  23183. lineDash = map(lineDash, function (rawVal) {
  23184. return rawVal / lineScale_1;
  23185. });
  23186. lineDashOffset /= lineScale_1;
  23187. }
  23188. }
  23189. var needsRebuild = true;
  23190. if (firstDraw || (el.__dirty & Path.SHAPE_CHANGED_BIT)
  23191. || (lineDash && !ctxLineDash && hasStroke)) {
  23192. path.setDPR(ctx.dpr);
  23193. if (strokePart) {
  23194. path.setContext(null);
  23195. }
  23196. else {
  23197. path.setContext(ctx);
  23198. needsRebuild = false;
  23199. }
  23200. path.reset();
  23201. if (lineDash && !ctxLineDash) {
  23202. path.setLineDash(lineDash);
  23203. path.setLineDashOffset(lineDashOffset);
  23204. }
  23205. el.buildPath(path, el.shape, inBatch);
  23206. path.toStatic();
  23207. el.pathUpdated();
  23208. }
  23209. if (needsRebuild) {
  23210. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  23211. }
  23212. if (lineDash && ctxLineDash) {
  23213. ctx.setLineDash(lineDash);
  23214. ctx.lineDashOffset = lineDashOffset;
  23215. }
  23216. if (!inBatch) {
  23217. if (style.strokeFirst) {
  23218. if (hasStroke) {
  23219. doStrokePath(ctx, style);
  23220. }
  23221. if (hasFill) {
  23222. doFillPath(ctx, style);
  23223. }
  23224. }
  23225. else {
  23226. if (hasFill) {
  23227. doFillPath(ctx, style);
  23228. }
  23229. if (hasStroke) {
  23230. doStrokePath(ctx, style);
  23231. }
  23232. }
  23233. }
  23234. if (lineDash && ctxLineDash) {
  23235. ctx.setLineDash([]);
  23236. }
  23237. }
  23238. function brushImage(ctx, el, style) {
  23239. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  23240. if (!image || !isImageReady(image)) {
  23241. return;
  23242. }
  23243. var x = style.x || 0;
  23244. var y = style.y || 0;
  23245. var width = el.getWidth();
  23246. var height = el.getHeight();
  23247. var aspect = image.width / image.height;
  23248. if (width == null && height != null) {
  23249. width = height * aspect;
  23250. }
  23251. else if (height == null && width != null) {
  23252. height = width / aspect;
  23253. }
  23254. else if (width == null && height == null) {
  23255. width = image.width;
  23256. height = image.height;
  23257. }
  23258. if (style.sWidth && style.sHeight) {
  23259. var sx = style.sx || 0;
  23260. var sy = style.sy || 0;
  23261. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  23262. }
  23263. else if (style.sx && style.sy) {
  23264. var sx = style.sx;
  23265. var sy = style.sy;
  23266. var sWidth = width - sx;
  23267. var sHeight = height - sy;
  23268. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  23269. }
  23270. else {
  23271. ctx.drawImage(image, x, y, width, height);
  23272. }
  23273. }
  23274. function brushText(ctx, el, style) {
  23275. var text = style.text;
  23276. text != null && (text += '');
  23277. if (text) {
  23278. ctx.font = style.font || DEFAULT_FONT;
  23279. ctx.textAlign = style.textAlign;
  23280. ctx.textBaseline = style.textBaseline;
  23281. var hasLineDash = void 0;
  23282. if (ctx.setLineDash) {
  23283. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  23284. var lineDashOffset = style.lineDashOffset;
  23285. if (lineDash) {
  23286. var lineScale_2 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  23287. if (lineScale_2 && lineScale_2 !== 1) {
  23288. lineDash = map(lineDash, function (rawVal) {
  23289. return rawVal / lineScale_2;
  23290. });
  23291. lineDashOffset /= lineScale_2;
  23292. }
  23293. ctx.setLineDash(lineDash);
  23294. ctx.lineDashOffset = lineDashOffset;
  23295. hasLineDash = true;
  23296. }
  23297. }
  23298. if (style.strokeFirst) {
  23299. if (styleHasStroke(style)) {
  23300. ctx.strokeText(text, style.x, style.y);
  23301. }
  23302. if (styleHasFill(style)) {
  23303. ctx.fillText(text, style.x, style.y);
  23304. }
  23305. }
  23306. else {
  23307. if (styleHasFill(style)) {
  23308. ctx.fillText(text, style.x, style.y);
  23309. }
  23310. if (styleHasStroke(style)) {
  23311. ctx.strokeText(text, style.x, style.y);
  23312. }
  23313. }
  23314. if (hasLineDash) {
  23315. ctx.setLineDash([]);
  23316. }
  23317. }
  23318. }
  23319. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  23320. var STROKE_PROPS = [
  23321. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  23322. ];
  23323. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  23324. var styleChanged = false;
  23325. if (!forceSetAll) {
  23326. prevStyle = prevStyle || {};
  23327. if (style === prevStyle) {
  23328. return false;
  23329. }
  23330. }
  23331. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  23332. if (!styleChanged) {
  23333. flushPathDrawn(ctx, scope);
  23334. styleChanged = true;
  23335. }
  23336. ctx.globalAlpha = style.opacity == null ? DEFAULT_COMMON_STYLE.opacity : style.opacity;
  23337. }
  23338. if (forceSetAll || style.blend !== prevStyle.blend) {
  23339. if (!styleChanged) {
  23340. flushPathDrawn(ctx, scope);
  23341. styleChanged = true;
  23342. }
  23343. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  23344. }
  23345. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  23346. var propName = SHADOW_NUMBER_PROPS[i];
  23347. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  23348. if (!styleChanged) {
  23349. flushPathDrawn(ctx, scope);
  23350. styleChanged = true;
  23351. }
  23352. ctx[propName] = ctx.dpr * (style[propName] || 0);
  23353. }
  23354. }
  23355. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  23356. if (!styleChanged) {
  23357. flushPathDrawn(ctx, scope);
  23358. styleChanged = true;
  23359. }
  23360. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  23361. }
  23362. return styleChanged;
  23363. }
  23364. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  23365. var style = getStyle(el, scope.inHover);
  23366. var prevStyle = forceSetAll
  23367. ? null
  23368. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  23369. if (style === prevStyle) {
  23370. return false;
  23371. }
  23372. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  23373. if (forceSetAll || style.fill !== prevStyle.fill) {
  23374. if (!styleChanged) {
  23375. flushPathDrawn(ctx, scope);
  23376. styleChanged = true;
  23377. }
  23378. ctx.fillStyle = style.fill;
  23379. }
  23380. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  23381. if (!styleChanged) {
  23382. flushPathDrawn(ctx, scope);
  23383. styleChanged = true;
  23384. }
  23385. ctx.strokeStyle = style.stroke;
  23386. }
  23387. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  23388. if (!styleChanged) {
  23389. flushPathDrawn(ctx, scope);
  23390. styleChanged = true;
  23391. }
  23392. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  23393. }
  23394. if (el.hasStroke()) {
  23395. var lineWidth = style.lineWidth;
  23396. var newLineWidth = lineWidth / ((style.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1);
  23397. if (ctx.lineWidth !== newLineWidth) {
  23398. if (!styleChanged) {
  23399. flushPathDrawn(ctx, scope);
  23400. styleChanged = true;
  23401. }
  23402. ctx.lineWidth = newLineWidth;
  23403. }
  23404. }
  23405. for (var i = 0; i < STROKE_PROPS.length; i++) {
  23406. var prop = STROKE_PROPS[i];
  23407. var propName = prop[0];
  23408. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  23409. if (!styleChanged) {
  23410. flushPathDrawn(ctx, scope);
  23411. styleChanged = true;
  23412. }
  23413. ctx[propName] = style[propName] || prop[1];
  23414. }
  23415. }
  23416. return styleChanged;
  23417. }
  23418. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  23419. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  23420. }
  23421. function setContextTransform(ctx, el) {
  23422. var m = el.transform;
  23423. var dpr = ctx.dpr || 1;
  23424. if (m) {
  23425. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  23426. }
  23427. else {
  23428. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  23429. }
  23430. }
  23431. function updateClipStatus(clipPaths, ctx, scope) {
  23432. var allClipped = false;
  23433. for (var i = 0; i < clipPaths.length; i++) {
  23434. var clipPath = clipPaths[i];
  23435. allClipped = allClipped || clipPath.isZeroArea();
  23436. setContextTransform(ctx, clipPath);
  23437. ctx.beginPath();
  23438. clipPath.buildPath(ctx, clipPath.shape);
  23439. ctx.clip();
  23440. }
  23441. scope.allClipped = allClipped;
  23442. }
  23443. function isTransformChanged(m0, m1) {
  23444. if (m0 && m1) {
  23445. return m0[0] !== m1[0]
  23446. || m0[1] !== m1[1]
  23447. || m0[2] !== m1[2]
  23448. || m0[3] !== m1[3]
  23449. || m0[4] !== m1[4]
  23450. || m0[5] !== m1[5];
  23451. }
  23452. else if (!m0 && !m1) {
  23453. return false;
  23454. }
  23455. return true;
  23456. }
  23457. var DRAW_TYPE_PATH = 1;
  23458. var DRAW_TYPE_IMAGE = 2;
  23459. var DRAW_TYPE_TEXT = 3;
  23460. var DRAW_TYPE_INCREMENTAL = 4;
  23461. function canPathBatch(style) {
  23462. var hasFill = styleHasFill(style);
  23463. var hasStroke = styleHasStroke(style);
  23464. return !(style.lineDash
  23465. || !(+hasFill ^ +hasStroke)
  23466. || (hasFill && typeof style.fill !== 'string')
  23467. || (hasStroke && typeof style.stroke !== 'string')
  23468. || style.strokePercent < 1
  23469. || style.strokeOpacity < 1
  23470. || style.fillOpacity < 1);
  23471. }
  23472. function flushPathDrawn(ctx, scope) {
  23473. scope.batchFill && ctx.fill();
  23474. scope.batchStroke && ctx.stroke();
  23475. scope.batchFill = '';
  23476. scope.batchStroke = '';
  23477. }
  23478. function getStyle(el, inHover) {
  23479. return inHover ? (el.__hoverStyle || el.style) : el.style;
  23480. }
  23481. function brushSingle(ctx, el) {
  23482. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  23483. }
  23484. function brush(ctx, el, scope, isLast) {
  23485. var m = el.transform;
  23486. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  23487. el.__dirty &= ~Element.REDARAW_BIT;
  23488. el.__isRendered = false;
  23489. return;
  23490. }
  23491. var clipPaths = el.__clipPaths;
  23492. var prevElClipPaths = scope.prevElClipPaths;
  23493. var forceSetTransform = false;
  23494. var forceSetStyle = false;
  23495. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  23496. if (prevElClipPaths && prevElClipPaths.length) {
  23497. flushPathDrawn(ctx, scope);
  23498. ctx.restore();
  23499. forceSetStyle = forceSetTransform = true;
  23500. scope.prevElClipPaths = null;
  23501. scope.allClipped = false;
  23502. scope.prevEl = null;
  23503. }
  23504. if (clipPaths && clipPaths.length) {
  23505. flushPathDrawn(ctx, scope);
  23506. ctx.save();
  23507. updateClipStatus(clipPaths, ctx, scope);
  23508. forceSetTransform = true;
  23509. }
  23510. scope.prevElClipPaths = clipPaths;
  23511. }
  23512. if (scope.allClipped) {
  23513. el.__isRendered = false;
  23514. return;
  23515. }
  23516. el.beforeBrush && el.beforeBrush();
  23517. el.innerBeforeBrush();
  23518. var prevEl = scope.prevEl;
  23519. if (!prevEl) {
  23520. forceSetStyle = forceSetTransform = true;
  23521. }
  23522. var canBatchPath = el instanceof Path
  23523. && el.autoBatch
  23524. && canPathBatch(el.style);
  23525. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  23526. flushPathDrawn(ctx, scope);
  23527. setContextTransform(ctx, el);
  23528. }
  23529. else if (!canBatchPath) {
  23530. flushPathDrawn(ctx, scope);
  23531. }
  23532. var style = getStyle(el, scope.inHover);
  23533. if (el instanceof Path) {
  23534. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  23535. forceSetStyle = true;
  23536. scope.lastDrawType = DRAW_TYPE_PATH;
  23537. }
  23538. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  23539. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  23540. ctx.beginPath();
  23541. }
  23542. brushPath(ctx, el, style, canBatchPath);
  23543. if (canBatchPath) {
  23544. scope.batchFill = style.fill || '';
  23545. scope.batchStroke = style.stroke || '';
  23546. }
  23547. }
  23548. else {
  23549. if (el instanceof TSpan) {
  23550. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  23551. forceSetStyle = true;
  23552. scope.lastDrawType = DRAW_TYPE_TEXT;
  23553. }
  23554. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  23555. brushText(ctx, el, style);
  23556. }
  23557. else if (el instanceof ZRImage) {
  23558. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  23559. forceSetStyle = true;
  23560. scope.lastDrawType = DRAW_TYPE_IMAGE;
  23561. }
  23562. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  23563. brushImage(ctx, el, style);
  23564. }
  23565. else if (el instanceof IncrementalDisplayable) {
  23566. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  23567. forceSetStyle = true;
  23568. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  23569. }
  23570. brushIncremental(ctx, el, scope);
  23571. }
  23572. }
  23573. if (canBatchPath && isLast) {
  23574. flushPathDrawn(ctx, scope);
  23575. }
  23576. el.innerAfterBrush();
  23577. el.afterBrush && el.afterBrush();
  23578. scope.prevEl = el;
  23579. el.__dirty = 0;
  23580. el.__isRendered = true;
  23581. }
  23582. function brushIncremental(ctx, el, scope) {
  23583. var displayables = el.getDisplayables();
  23584. var temporalDisplayables = el.getTemporalDisplayables();
  23585. ctx.save();
  23586. var innerScope = {
  23587. prevElClipPaths: null,
  23588. prevEl: null,
  23589. allClipped: false,
  23590. viewWidth: scope.viewWidth,
  23591. viewHeight: scope.viewHeight,
  23592. inHover: scope.inHover
  23593. };
  23594. var i;
  23595. var len;
  23596. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  23597. var displayable = displayables[i];
  23598. displayable.beforeBrush && displayable.beforeBrush();
  23599. displayable.innerBeforeBrush();
  23600. brush(ctx, displayable, innerScope, i === len - 1);
  23601. displayable.innerAfterBrush();
  23602. displayable.afterBrush && displayable.afterBrush();
  23603. innerScope.prevEl = displayable;
  23604. }
  23605. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  23606. var displayable = temporalDisplayables[i_1];
  23607. displayable.beforeBrush && displayable.beforeBrush();
  23608. displayable.innerBeforeBrush();
  23609. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  23610. displayable.innerAfterBrush();
  23611. displayable.afterBrush && displayable.afterBrush();
  23612. innerScope.prevEl = displayable;
  23613. }
  23614. el.clearTemporalDisplayables();
  23615. el.notClear = true;
  23616. ctx.restore();
  23617. }
  23618. var decalMap = new WeakMap();
  23619. var decalCache = new LRU(100);
  23620. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  23621. /**
  23622. * Create or update pattern image from decal options
  23623. *
  23624. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  23625. * @return {Pattern} pattern with generated image, null if no decal
  23626. */
  23627. function createOrUpdatePatternFromDecal(decalObject, api) {
  23628. if (decalObject === 'none') {
  23629. return null;
  23630. }
  23631. var dpr = api.getDevicePixelRatio();
  23632. var zr = api.getZr();
  23633. var isSVG = zr.painter.type === 'svg';
  23634. if (decalObject.dirty) {
  23635. decalMap["delete"](decalObject);
  23636. }
  23637. var oldPattern = decalMap.get(decalObject);
  23638. if (oldPattern) {
  23639. return oldPattern;
  23640. }
  23641. var decalOpt = defaults(decalObject, {
  23642. symbol: 'rect',
  23643. symbolSize: 1,
  23644. symbolKeepAspect: true,
  23645. color: 'rgba(0, 0, 0, 0.2)',
  23646. backgroundColor: null,
  23647. dashArrayX: 5,
  23648. dashArrayY: 5,
  23649. rotation: 0,
  23650. maxTileWidth: 512,
  23651. maxTileHeight: 512
  23652. });
  23653. if (decalOpt.backgroundColor === 'none') {
  23654. decalOpt.backgroundColor = null;
  23655. }
  23656. var pattern = {
  23657. repeat: 'repeat'
  23658. };
  23659. setPatternnSource(pattern);
  23660. pattern.rotation = decalOpt.rotation;
  23661. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  23662. decalMap.set(decalObject, pattern);
  23663. decalObject.dirty = false;
  23664. return pattern;
  23665. function setPatternnSource(pattern) {
  23666. var keys = [dpr];
  23667. var isValidKey = true;
  23668. for (var i = 0; i < decalKeys.length; ++i) {
  23669. var value = decalOpt[decalKeys[i]];
  23670. var valueType = typeof value;
  23671. if (value != null && !isArray(value) && valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') {
  23672. isValidKey = false;
  23673. break;
  23674. }
  23675. keys.push(value);
  23676. }
  23677. var cacheKey;
  23678. if (isValidKey) {
  23679. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  23680. var cache = decalCache.get(cacheKey);
  23681. if (cache) {
  23682. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  23683. }
  23684. }
  23685. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  23686. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  23687. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  23688. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  23689. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  23690. var canvas = !isSVG && createCanvas();
  23691. var svgRoot = isSVG && zr.painter.createSVGElement('g');
  23692. var pSize = getPatternSize();
  23693. var ctx;
  23694. if (canvas) {
  23695. canvas.width = pSize.width * dpr;
  23696. canvas.height = pSize.height * dpr;
  23697. ctx = canvas.getContext('2d');
  23698. }
  23699. brushDecal();
  23700. if (isValidKey) {
  23701. decalCache.put(cacheKey, canvas || svgRoot);
  23702. }
  23703. pattern.image = canvas;
  23704. pattern.svgElement = svgRoot;
  23705. pattern.svgWidth = pSize.width;
  23706. pattern.svgHeight = pSize.height;
  23707. /**
  23708. * Get minumum length that can make a repeatable pattern.
  23709. *
  23710. * @return {Object} pattern width and height
  23711. */
  23712. function getPatternSize() {
  23713. /**
  23714. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  23715. * |--- --- --- --- --- ...
  23716. * |-- -- -- -- -- -- -- -- ...
  23717. * |--- --- --- --- --- ...
  23718. * |-- -- -- -- -- -- -- -- ...
  23719. * So the minumum length of X is 15,
  23720. * which is the least common multiple of `3 + 2` and `2 + 1`
  23721. * |--- --- --- |--- --- ...
  23722. * |-- -- -- -- -- |-- -- -- ...
  23723. */
  23724. var width = 1;
  23725. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  23726. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  23727. }
  23728. var symbolRepeats = 1;
  23729. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  23730. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  23731. }
  23732. width *= symbolRepeats;
  23733. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  23734. if ("development" !== 'production') {
  23735. var warn = function (attrName) {
  23736. /* eslint-disable-next-line */
  23737. 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.");
  23738. };
  23739. if (width > decalOpt.maxTileWidth) {
  23740. warn('maxTileWidth');
  23741. }
  23742. if (height > decalOpt.maxTileHeight) {
  23743. warn('maxTileHeight');
  23744. }
  23745. }
  23746. return {
  23747. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  23748. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  23749. };
  23750. }
  23751. function brushDecal() {
  23752. if (ctx) {
  23753. ctx.clearRect(0, 0, canvas.width, canvas.height);
  23754. if (decalOpt.backgroundColor) {
  23755. ctx.fillStyle = decalOpt.backgroundColor;
  23756. ctx.fillRect(0, 0, canvas.width, canvas.height);
  23757. }
  23758. }
  23759. var ySum = 0;
  23760. for (var i = 0; i < dashArrayY.length; ++i) {
  23761. ySum += dashArrayY[i];
  23762. }
  23763. if (ySum <= 0) {
  23764. // dashArrayY is 0, draw nothing
  23765. return;
  23766. }
  23767. var y = -lineBlockLengthY;
  23768. var yId = 0;
  23769. var yIdTotal = 0;
  23770. var xId0 = 0;
  23771. while (y < pSize.height) {
  23772. if (yId % 2 === 0) {
  23773. var symbolYId = yIdTotal / 2 % symbolArray.length;
  23774. var x = 0;
  23775. var xId1 = 0;
  23776. var xId1Total = 0;
  23777. while (x < pSize.width * 2) {
  23778. var xSum = 0;
  23779. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  23780. xSum += dashArrayX[xId0][i];
  23781. }
  23782. if (xSum <= 0) {
  23783. // Skip empty line
  23784. break;
  23785. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  23786. if (xId1 % 2 === 0) {
  23787. var size = (1 - decalOpt.symbolSize) * 0.5;
  23788. var left = x + dashArrayX[xId0][xId1] * size;
  23789. var top_1 = y + dashArrayY[yId] * size;
  23790. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  23791. var height = dashArrayY[yId] * decalOpt.symbolSize;
  23792. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  23793. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  23794. }
  23795. x += dashArrayX[xId0][xId1];
  23796. ++xId1Total;
  23797. ++xId1;
  23798. if (xId1 === dashArrayX[xId0].length) {
  23799. xId1 = 0;
  23800. }
  23801. }
  23802. ++xId0;
  23803. if (xId0 === dashArrayX.length) {
  23804. xId0 = 0;
  23805. }
  23806. }
  23807. y += dashArrayY[yId];
  23808. ++yIdTotal;
  23809. ++yId;
  23810. if (yId === dashArrayY.length) {
  23811. yId = 0;
  23812. }
  23813. }
  23814. function brushSymbol(x, y, width, height, symbolType) {
  23815. var scale = isSVG ? 1 : dpr;
  23816. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  23817. if (isSVG) {
  23818. svgRoot.appendChild(zr.painter.paintOne(symbol));
  23819. } else {
  23820. // Paint to canvas for all other renderers.
  23821. brushSingle(ctx, symbol);
  23822. }
  23823. }
  23824. }
  23825. }
  23826. }
  23827. /**
  23828. * Convert symbol array into normalized array
  23829. *
  23830. * @param {string | (string | string[])[]} symbol symbol input
  23831. * @return {string[][]} normolized symbol array
  23832. */
  23833. function normalizeSymbolArray(symbol) {
  23834. if (!symbol || symbol.length === 0) {
  23835. return [['rect']];
  23836. }
  23837. if (typeof symbol === 'string') {
  23838. return [[symbol]];
  23839. }
  23840. var isAllString = true;
  23841. for (var i = 0; i < symbol.length; ++i) {
  23842. if (typeof symbol[i] !== 'string') {
  23843. isAllString = false;
  23844. break;
  23845. }
  23846. }
  23847. if (isAllString) {
  23848. return normalizeSymbolArray([symbol]);
  23849. }
  23850. var result = [];
  23851. for (var i = 0; i < symbol.length; ++i) {
  23852. if (typeof symbol[i] === 'string') {
  23853. result.push([symbol[i]]);
  23854. } else {
  23855. result.push(symbol[i]);
  23856. }
  23857. }
  23858. return result;
  23859. }
  23860. /**
  23861. * Convert dash input into dashArray
  23862. *
  23863. * @param {DecalDashArrayX} dash dash input
  23864. * @return {number[][]} normolized dash array
  23865. */
  23866. function normalizeDashArrayX(dash) {
  23867. if (!dash || dash.length === 0) {
  23868. return [[0, 0]];
  23869. }
  23870. if (typeof dash === 'number') {
  23871. var dashValue = Math.ceil(dash);
  23872. return [[dashValue, dashValue]];
  23873. }
  23874. /**
  23875. * [20, 5] should be normalized into [[20, 5]],
  23876. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  23877. */
  23878. var isAllNumber = true;
  23879. for (var i = 0; i < dash.length; ++i) {
  23880. if (typeof dash[i] !== 'number') {
  23881. isAllNumber = false;
  23882. break;
  23883. }
  23884. }
  23885. if (isAllNumber) {
  23886. return normalizeDashArrayX([dash]);
  23887. }
  23888. var result = [];
  23889. for (var i = 0; i < dash.length; ++i) {
  23890. if (typeof dash[i] === 'number') {
  23891. var dashValue = Math.ceil(dash[i]);
  23892. result.push([dashValue, dashValue]);
  23893. } else {
  23894. var dashValue = map(dash[i], function (n) {
  23895. return Math.ceil(n);
  23896. });
  23897. if (dashValue.length % 2 === 1) {
  23898. // [4, 2, 1] means |---- - -- |---- - -- |
  23899. // so normalize it to be [4, 2, 1, 4, 2, 1]
  23900. result.push(dashValue.concat(dashValue));
  23901. } else {
  23902. result.push(dashValue);
  23903. }
  23904. }
  23905. }
  23906. return result;
  23907. }
  23908. /**
  23909. * Convert dash input into dashArray
  23910. *
  23911. * @param {DecalDashArrayY} dash dash input
  23912. * @return {number[]} normolized dash array
  23913. */
  23914. function normalizeDashArrayY(dash) {
  23915. if (!dash || typeof dash === 'object' && dash.length === 0) {
  23916. return [0, 0];
  23917. }
  23918. if (typeof dash === 'number') {
  23919. var dashValue_1 = Math.ceil(dash);
  23920. return [dashValue_1, dashValue_1];
  23921. }
  23922. var dashValue = map(dash, function (n) {
  23923. return Math.ceil(n);
  23924. });
  23925. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  23926. }
  23927. /**
  23928. * Get block length of each line. A block is the length of dash line and space.
  23929. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  23930. * that, so the block length of this line is 5.
  23931. *
  23932. * @param {number[][]} dash dash arrary of X or Y
  23933. * @return {number[]} block length of each line
  23934. */
  23935. function getLineBlockLengthX(dash) {
  23936. return map(dash, function (line) {
  23937. return getLineBlockLengthY(line);
  23938. });
  23939. }
  23940. function getLineBlockLengthY(dash) {
  23941. var blockLength = 0;
  23942. for (var i = 0; i < dash.length; ++i) {
  23943. blockLength += dash[i];
  23944. }
  23945. if (dash.length % 2 === 1) {
  23946. // [4, 2, 1] means |---- - -- |---- - -- |
  23947. // So total length is (4 + 2 + 1) * 2
  23948. return blockLength * 2;
  23949. }
  23950. return blockLength;
  23951. }
  23952. function decalVisual(ecModel, api) {
  23953. ecModel.eachRawSeries(function (seriesModel) {
  23954. if (ecModel.isSeriesFiltered(seriesModel)) {
  23955. return;
  23956. }
  23957. var data = seriesModel.getData();
  23958. if (data.hasItemVisual()) {
  23959. data.each(function (idx) {
  23960. var decal = data.getItemVisual(idx, 'decal');
  23961. if (decal) {
  23962. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  23963. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  23964. }
  23965. });
  23966. }
  23967. var decal = data.getVisual('decal');
  23968. if (decal) {
  23969. var style = data.getVisual('style');
  23970. style.decal = createOrUpdatePatternFromDecal(decal, api);
  23971. }
  23972. });
  23973. }
  23974. var assert$1 = assert;
  23975. var each$3 = each;
  23976. var isFunction$1 = isFunction;
  23977. var isObject$2 = isObject;
  23978. var indexOf$1 = indexOf;
  23979. var hasWindow = typeof window !== 'undefined';
  23980. var version$1 = '5.0.2';
  23981. var dependencies = {
  23982. zrender: '5.0.4'
  23983. };
  23984. var TEST_FRAME_REMAIN_TIME = 1;
  23985. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  23986. // So data stack stage should be in front of data processing stage.
  23987. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  23988. // put at the begining of data processing.
  23989. var PRIORITY_PROCESSOR_FILTER = 1000;
  23990. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  23991. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23992. var PRIORITY_VISUAL_LAYOUT = 1000;
  23993. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  23994. var PRIORITY_VISUAL_GLOBAL = 2000;
  23995. var PRIORITY_VISUAL_CHART = 3000;
  23996. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  23997. // overwrite the viusal result of component (like `visualMap`)
  23998. // using data item specific setting (like itemStyle.xxx on data item)
  23999. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  24000. // visual result like `symbolSize`.
  24001. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  24002. var PRIORITY_VISUAL_BRUSH = 5000;
  24003. var PRIORITY_VISUAL_ARIA = 6000;
  24004. var PRIORITY_VISUAL_DECAL = 7000;
  24005. var PRIORITY = {
  24006. PROCESSOR: {
  24007. FILTER: PRIORITY_PROCESSOR_FILTER,
  24008. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24009. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24010. },
  24011. VISUAL: {
  24012. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24013. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24014. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24015. CHART: PRIORITY_VISUAL_CHART,
  24016. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24017. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24018. BRUSH: PRIORITY_VISUAL_BRUSH,
  24019. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  24020. ARIA: PRIORITY_VISUAL_ARIA,
  24021. DECAL: PRIORITY_VISUAL_DECAL
  24022. }
  24023. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24024. // where they must not be invoked nestedly, except the only case: invoke
  24025. // dispatchAction with updateMethod "none" in main process.
  24026. // This flag is used to carry out this rule.
  24027. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24028. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  24029. var OPTION_UPDATED_KEY = '__optionUpdated';
  24030. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  24031. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24032. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  24033. var CONNECT_STATUS_PENDING = 0;
  24034. var CONNECT_STATUS_UPDATING = 1;
  24035. var CONNECT_STATUS_UPDATED = 2;
  24036. function createRegisterEventWithLowercaseECharts(method) {
  24037. return function () {
  24038. var args = [];
  24039. for (var _i = 0; _i < arguments.length; _i++) {
  24040. args[_i] = arguments[_i];
  24041. }
  24042. if (this.isDisposed()) {
  24043. disposedWarning(this.id);
  24044. return;
  24045. }
  24046. return toLowercaseNameAndCallEventful(this, method, args);
  24047. };
  24048. }
  24049. function createRegisterEventWithLowercaseMessageCenter(method) {
  24050. return function () {
  24051. var args = [];
  24052. for (var _i = 0; _i < arguments.length; _i++) {
  24053. args[_i] = arguments[_i];
  24054. }
  24055. return toLowercaseNameAndCallEventful(this, method, args);
  24056. };
  24057. }
  24058. function toLowercaseNameAndCallEventful(host, method, args) {
  24059. // `args[0]` is event name. Event name is all lowercase.
  24060. args[0] = args[0] && args[0].toLowerCase();
  24061. return Eventful.prototype[method].apply(host, args);
  24062. }
  24063. var MessageCenter =
  24064. /** @class */
  24065. function (_super) {
  24066. __extends(MessageCenter, _super);
  24067. function MessageCenter() {
  24068. return _super !== null && _super.apply(this, arguments) || this;
  24069. }
  24070. return MessageCenter;
  24071. }(Eventful);
  24072. var messageCenterProto = MessageCenter.prototype;
  24073. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  24074. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  24075. // Internal method names for class ECharts
  24076. // ---------------------------------------
  24077. var prepare;
  24078. var prepareView;
  24079. var updateDirectly;
  24080. var updateMethods;
  24081. var doConvertPixel;
  24082. var updateStreamModes;
  24083. var doDispatchAction;
  24084. var flushPendingActions;
  24085. var triggerUpdatedEvent;
  24086. var bindRenderedEvent;
  24087. var bindMouseEvent;
  24088. var clearColorPalette;
  24089. var render;
  24090. var renderComponents;
  24091. var renderSeries;
  24092. var performPostUpdateFuncs;
  24093. var createExtensionAPI;
  24094. var enableConnect;
  24095. var setTransitionOpt;
  24096. var markStatusToUpdate;
  24097. var applyChangedStates;
  24098. var ECharts =
  24099. /** @class */
  24100. function (_super) {
  24101. __extends(ECharts, _super);
  24102. function ECharts(dom, // Theme name or themeOption.
  24103. theme, opts) {
  24104. var _this = _super.call(this, new ECEventProcessor()) || this;
  24105. _this._chartsViews = [];
  24106. _this._chartsMap = {};
  24107. _this._componentsViews = [];
  24108. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  24109. _this._pendingActions = [];
  24110. opts = opts || {}; // Get theme by name
  24111. if (typeof theme === 'string') {
  24112. theme = themeStorage[theme];
  24113. }
  24114. _this._dom = dom;
  24115. var defaultRenderer = 'canvas';
  24116. var defaultUseDirtyRect = false;
  24117. if ("development" !== 'production') {
  24118. var root =
  24119. /* eslint-disable-next-line */
  24120. hasWindow ? window : global;
  24121. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24122. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  24123. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  24124. }
  24125. var zr = _this._zr = init(dom, {
  24126. renderer: opts.renderer || defaultRenderer,
  24127. devicePixelRatio: opts.devicePixelRatio,
  24128. width: opts.width,
  24129. height: opts.height,
  24130. useDirtyRect: opts.useDirtyRect == null ? defaultUseDirtyRect : opts.useDirtyRect
  24131. }); // Expect 60 fps.
  24132. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24133. theme = clone(theme);
  24134. theme && globalBackwardCompat(theme, true);
  24135. _this._theme = theme;
  24136. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  24137. _this._coordSysMgr = new CoordinateSystemManager();
  24138. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  24139. function prioritySortFunc(a, b) {
  24140. return a.__prio - b.__prio;
  24141. }
  24142. sort(visualFuncs, prioritySortFunc);
  24143. sort(dataProcessorFuncs, prioritySortFunc);
  24144. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  24145. _this._messageCenter = new MessageCenter();
  24146. _this._labelManager = new LabelManager(); // Init mouse events
  24147. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  24148. _this.resize = bind(_this.resize, _this);
  24149. zr.animation.on('frame', _this._onframe, _this);
  24150. bindRenderedEvent(zr, _this);
  24151. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  24152. setAsPrimitive(_this);
  24153. return _this;
  24154. }
  24155. ECharts.prototype._onframe = function () {
  24156. if (this._disposed) {
  24157. return;
  24158. }
  24159. applyChangedStates(this);
  24160. var scheduler = this._scheduler; // Lazy update
  24161. if (this[OPTION_UPDATED_KEY]) {
  24162. var silent = this[OPTION_UPDATED_KEY].silent;
  24163. this[IN_MAIN_PROCESS_KEY] = true;
  24164. prepare(this);
  24165. updateMethods.update.call(this); // At present, in each frame, zrender performs:
  24166. // (1) animation step forward.
  24167. // (2) trigger('frame') (where this `_onframe` is called)
  24168. // (3) zrender flush (render).
  24169. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  24170. // will render the final state of the elements before the real animation started.
  24171. this._zr.flush();
  24172. this[IN_MAIN_PROCESS_KEY] = false;
  24173. this[OPTION_UPDATED_KEY] = false;
  24174. flushPendingActions.call(this, silent);
  24175. triggerUpdatedEvent.call(this, silent);
  24176. } // Avoid do both lazy update and progress in one frame.
  24177. else if (scheduler.unfinished) {
  24178. // Stream progress.
  24179. var remainTime = TEST_FRAME_REMAIN_TIME;
  24180. var ecModel = this._model;
  24181. var api = this._api;
  24182. scheduler.unfinished = false;
  24183. do {
  24184. var startTime = +new Date();
  24185. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  24186. scheduler.performDataProcessorTasks(ecModel);
  24187. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  24188. // each frame is not a good user experience. So we follow the rule that
  24189. // the extent of the coordinate system is determin in the first frame (the
  24190. // frame is executed immedietely after task reset.
  24191. // this._coordSysMgr.update(ecModel, api);
  24192. // console.log('--- ec frame visual ---', remainTime);
  24193. scheduler.performVisualTasks(ecModel);
  24194. renderSeries(this, this._model, api, 'remain');
  24195. remainTime -= +new Date() - startTime;
  24196. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  24197. if (!scheduler.unfinished) {
  24198. this._zr.flush();
  24199. } // Else, zr flushing be ensue within the same frame,
  24200. // because zr flushing is after onframe event.
  24201. }
  24202. };
  24203. ECharts.prototype.getDom = function () {
  24204. return this._dom;
  24205. };
  24206. ECharts.prototype.getId = function () {
  24207. return this.id;
  24208. };
  24209. ECharts.prototype.getZr = function () {
  24210. return this._zr;
  24211. };
  24212. /* eslint-disable-next-line */
  24213. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  24214. if ("development" !== 'production') {
  24215. assert$1(!this[IN_MAIN_PROCESS_KEY], '`setOption` should not be called during main process.');
  24216. }
  24217. if (this._disposed) {
  24218. disposedWarning(this.id);
  24219. return;
  24220. }
  24221. var silent;
  24222. var replaceMerge;
  24223. var transitionOpt;
  24224. if (isObject$2(notMerge)) {
  24225. lazyUpdate = notMerge.lazyUpdate;
  24226. silent = notMerge.silent;
  24227. replaceMerge = notMerge.replaceMerge;
  24228. transitionOpt = notMerge.transition;
  24229. notMerge = notMerge.notMerge;
  24230. }
  24231. this[IN_MAIN_PROCESS_KEY] = true;
  24232. if (!this._model || notMerge) {
  24233. var optionManager = new OptionManager(this._api);
  24234. var theme = this._theme;
  24235. var ecModel = this._model = new GlobalModel();
  24236. ecModel.scheduler = this._scheduler;
  24237. ecModel.init(null, null, null, theme, this._locale, optionManager);
  24238. }
  24239. this._model.setOption(option, {
  24240. replaceMerge: replaceMerge
  24241. }, optionPreprocessorFuncs);
  24242. setTransitionOpt(this, transitionOpt);
  24243. if (lazyUpdate) {
  24244. this[OPTION_UPDATED_KEY] = {
  24245. silent: silent
  24246. };
  24247. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  24248. // It should wake it up to make sure zrender start to render at the next frame.
  24249. this.getZr().wakeUp();
  24250. } else {
  24251. prepare(this);
  24252. updateMethods.update.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be
  24253. // fetched after `setOption`.
  24254. this._zr.flush();
  24255. this[OPTION_UPDATED_KEY] = false;
  24256. this[IN_MAIN_PROCESS_KEY] = false;
  24257. flushPendingActions.call(this, silent);
  24258. triggerUpdatedEvent.call(this, silent);
  24259. }
  24260. };
  24261. /**
  24262. * @DEPRECATED
  24263. */
  24264. ECharts.prototype.setTheme = function () {
  24265. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24266. }; // We don't want developers to use getModel directly.
  24267. ECharts.prototype.getModel = function () {
  24268. return this._model;
  24269. };
  24270. ECharts.prototype.getOption = function () {
  24271. return this._model && this._model.getOption();
  24272. };
  24273. ECharts.prototype.getWidth = function () {
  24274. return this._zr.getWidth();
  24275. };
  24276. ECharts.prototype.getHeight = function () {
  24277. return this._zr.getHeight();
  24278. };
  24279. ECharts.prototype.getDevicePixelRatio = function () {
  24280. return this._zr.painter.dpr
  24281. /* eslint-disable-next-line */
  24282. || hasWindow && window.devicePixelRatio || 1;
  24283. };
  24284. /**
  24285. * Get canvas which has all thing rendered
  24286. */
  24287. ECharts.prototype.getRenderedCanvas = function (opts) {
  24288. if (!env.canvasSupported) {
  24289. return;
  24290. }
  24291. opts = extend({}, opts || {});
  24292. opts.pixelRatio = opts.pixelRatio || this.getDevicePixelRatio();
  24293. opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor');
  24294. var zr = this._zr; // let list = zr.storage.getDisplayList();
  24295. // Stop animations
  24296. // Never works before in init animation, so remove it.
  24297. // zrUtil.each(list, function (el) {
  24298. // el.stopAnimation(true);
  24299. // });
  24300. return zr.painter.getRenderedCanvas(opts);
  24301. };
  24302. /**
  24303. * Get svg data url
  24304. */
  24305. ECharts.prototype.getSvgDataURL = function () {
  24306. if (!env.svgSupported) {
  24307. return;
  24308. }
  24309. var zr = this._zr;
  24310. var list = zr.storage.getDisplayList(); // Stop animations
  24311. each(list, function (el) {
  24312. el.stopAnimation(null, true);
  24313. });
  24314. return zr.painter.toDataURL();
  24315. };
  24316. ECharts.prototype.getDataURL = function (opts) {
  24317. if (this._disposed) {
  24318. disposedWarning(this.id);
  24319. return;
  24320. }
  24321. opts = opts || {};
  24322. var excludeComponents = opts.excludeComponents;
  24323. var ecModel = this._model;
  24324. var excludesComponentViews = [];
  24325. var self = this;
  24326. each$3(excludeComponents, function (componentType) {
  24327. ecModel.eachComponent({
  24328. mainType: componentType
  24329. }, function (component) {
  24330. var view = self._componentsMap[component.__viewId];
  24331. if (!view.group.ignore) {
  24332. excludesComponentViews.push(view);
  24333. view.group.ignore = true;
  24334. }
  24335. });
  24336. });
  24337. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  24338. each$3(excludesComponentViews, function (view) {
  24339. view.group.ignore = false;
  24340. });
  24341. return url;
  24342. };
  24343. ECharts.prototype.getConnectedDataURL = function (opts) {
  24344. if (this._disposed) {
  24345. disposedWarning(this.id);
  24346. return;
  24347. }
  24348. if (!env.canvasSupported) {
  24349. return;
  24350. }
  24351. var isSvg = opts.type === 'svg';
  24352. var groupId = this.group;
  24353. var mathMin = Math.min;
  24354. var mathMax = Math.max;
  24355. var MAX_NUMBER = Infinity;
  24356. if (connectedGroups[groupId]) {
  24357. var left_1 = MAX_NUMBER;
  24358. var top_1 = MAX_NUMBER;
  24359. var right_1 = -MAX_NUMBER;
  24360. var bottom_1 = -MAX_NUMBER;
  24361. var canvasList_1 = [];
  24362. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  24363. each(instances$1, function (chart, id) {
  24364. if (chart.group === groupId) {
  24365. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.getRenderedCanvas(clone(opts));
  24366. var boundingRect = chart.getDom().getBoundingClientRect();
  24367. left_1 = mathMin(boundingRect.left, left_1);
  24368. top_1 = mathMin(boundingRect.top, top_1);
  24369. right_1 = mathMax(boundingRect.right, right_1);
  24370. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  24371. canvasList_1.push({
  24372. dom: canvas,
  24373. left: boundingRect.left,
  24374. top: boundingRect.top
  24375. });
  24376. }
  24377. });
  24378. left_1 *= dpr_1;
  24379. top_1 *= dpr_1;
  24380. right_1 *= dpr_1;
  24381. bottom_1 *= dpr_1;
  24382. var width = right_1 - left_1;
  24383. var height = bottom_1 - top_1;
  24384. var targetCanvas = createCanvas();
  24385. var zr_1 = init(targetCanvas, {
  24386. renderer: isSvg ? 'svg' : 'canvas'
  24387. });
  24388. zr_1.resize({
  24389. width: width,
  24390. height: height
  24391. });
  24392. if (isSvg) {
  24393. var content_1 = '';
  24394. each$3(canvasList_1, function (item) {
  24395. var x = item.left - left_1;
  24396. var y = item.top - top_1;
  24397. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  24398. });
  24399. zr_1.painter.getSvgRoot().innerHTML = content_1;
  24400. if (opts.connectedBackgroundColor) {
  24401. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  24402. }
  24403. zr_1.refreshImmediately();
  24404. return zr_1.painter.toDataURL();
  24405. } else {
  24406. // Background between the charts
  24407. if (opts.connectedBackgroundColor) {
  24408. zr_1.add(new Rect({
  24409. shape: {
  24410. x: 0,
  24411. y: 0,
  24412. width: width,
  24413. height: height
  24414. },
  24415. style: {
  24416. fill: opts.connectedBackgroundColor
  24417. }
  24418. }));
  24419. }
  24420. each$3(canvasList_1, function (item) {
  24421. var img = new ZRImage({
  24422. style: {
  24423. x: item.left * dpr_1 - left_1,
  24424. y: item.top * dpr_1 - top_1,
  24425. image: item.dom
  24426. }
  24427. });
  24428. zr_1.add(img);
  24429. });
  24430. zr_1.refreshImmediately();
  24431. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24432. }
  24433. } else {
  24434. return this.getDataURL(opts);
  24435. }
  24436. };
  24437. ECharts.prototype.convertToPixel = function (finder, value) {
  24438. return doConvertPixel(this, 'convertToPixel', finder, value);
  24439. };
  24440. ECharts.prototype.convertFromPixel = function (finder, value) {
  24441. return doConvertPixel(this, 'convertFromPixel', finder, value);
  24442. };
  24443. /**
  24444. * Is the specified coordinate systems or components contain the given pixel point.
  24445. * @param {Array|number} value
  24446. * @return {boolean} result
  24447. */
  24448. ECharts.prototype.containPixel = function (finder, value) {
  24449. if (this._disposed) {
  24450. disposedWarning(this.id);
  24451. return;
  24452. }
  24453. var ecModel = this._model;
  24454. var result;
  24455. var findResult = parseFinder(ecModel, finder);
  24456. each(findResult, function (models, key) {
  24457. key.indexOf('Models') >= 0 && each(models, function (model) {
  24458. var coordSys = model.coordinateSystem;
  24459. if (coordSys && coordSys.containPoint) {
  24460. result = result || !!coordSys.containPoint(value);
  24461. } else if (key === 'seriesModels') {
  24462. var view = this._chartsMap[model.__viewId];
  24463. if (view && view.containPoint) {
  24464. result = result || view.containPoint(value, model);
  24465. } else {
  24466. if ("development" !== 'production') {
  24467. console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  24468. }
  24469. }
  24470. } else {
  24471. if ("development" !== 'production') {
  24472. console.warn(key + ': containPoint is not supported');
  24473. }
  24474. }
  24475. }, this);
  24476. }, this);
  24477. return !!result;
  24478. };
  24479. /**
  24480. * Get visual from series or data.
  24481. * @param finder
  24482. * If string, e.g., 'series', means {seriesIndex: 0}.
  24483. * If Object, could contain some of these properties below:
  24484. * {
  24485. * seriesIndex / seriesId / seriesName,
  24486. * dataIndex / dataIndexInside
  24487. * }
  24488. * If dataIndex is not specified, series visual will be fetched,
  24489. * but not data item visual.
  24490. * If all of seriesIndex, seriesId, seriesName are not specified,
  24491. * visual will be fetched from first series.
  24492. * @param visualType 'color', 'symbol', 'symbolSize'
  24493. */
  24494. ECharts.prototype.getVisual = function (finder, visualType) {
  24495. var ecModel = this._model;
  24496. var parsedFinder = parseFinder(ecModel, finder, {
  24497. defaultMainType: 'series'
  24498. });
  24499. var seriesModel = parsedFinder.seriesModel;
  24500. if ("development" !== 'production') {
  24501. if (!seriesModel) {
  24502. console.warn('There is no specified seires model');
  24503. }
  24504. }
  24505. var data = seriesModel.getData();
  24506. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  24507. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  24508. };
  24509. /**
  24510. * Get view of corresponding component model
  24511. */
  24512. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  24513. return this._componentsMap[componentModel.__viewId];
  24514. };
  24515. /**
  24516. * Get view of corresponding series model
  24517. */
  24518. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  24519. return this._chartsMap[seriesModel.__viewId];
  24520. };
  24521. ECharts.prototype._initEvents = function () {
  24522. var _this = this;
  24523. each$3(MOUSE_EVENT_NAMES, function (eveName) {
  24524. var handler = function (e) {
  24525. var ecModel = _this.getModel();
  24526. var el = e.target;
  24527. var params;
  24528. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  24529. if (isGlobalOut) {
  24530. params = {};
  24531. } else {
  24532. el && findEventDispatcher(el, function (parent) {
  24533. var ecData = getECData(parent);
  24534. if (ecData && ecData.dataIndex != null) {
  24535. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  24536. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  24537. return true;
  24538. } // If element has custom eventData of components
  24539. else if (ecData.eventData) {
  24540. params = extend({}, ecData.eventData);
  24541. return true;
  24542. }
  24543. }, true);
  24544. } // Contract: if params prepared in mouse event,
  24545. // these properties must be specified:
  24546. // {
  24547. // componentType: string (component main type)
  24548. // componentIndex: number
  24549. // }
  24550. // Otherwise event query can not work.
  24551. if (params) {
  24552. var componentType = params.componentType;
  24553. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  24554. // markLine/markPoint/markArea, the componentType is
  24555. // 'markLine'/'markPoint'/'markArea', but we should better
  24556. // enable them to be queried by seriesIndex, since their
  24557. // option is set in each series.
  24558. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  24559. componentType = 'series';
  24560. componentIndex = params.seriesIndex;
  24561. }
  24562. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  24563. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  24564. if ("development" !== 'production') {
  24565. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24566. // be missed, otherwise there is no way to distinguish source component.
  24567. // See `dataFormat.getDataParams`.
  24568. if (!isGlobalOut && !(model && view)) {
  24569. console.warn('model or view can not be found by params');
  24570. }
  24571. }
  24572. params.event = e;
  24573. params.type = eveName;
  24574. _this._$eventProcessor.eventInfo = {
  24575. targetEl: el,
  24576. packedEvent: params,
  24577. model: model,
  24578. view: view
  24579. };
  24580. _this.trigger(eveName, params);
  24581. }
  24582. }; // Consider that some component (like tooltip, brush, ...)
  24583. // register zr event handler, but user event handler might
  24584. // do anything, such as call `setOption` or `dispatchAction`,
  24585. // which probably update any of the content and probably
  24586. // cause problem if it is called previous other inner handlers.
  24587. handler.zrEventfulCallAtLast = true;
  24588. _this._zr.on(eveName, handler, _this);
  24589. });
  24590. each$3(eventActionMap, function (actionType, eventType) {
  24591. _this._messageCenter.on(eventType, function (event) {
  24592. this.trigger(eventType, event);
  24593. }, _this);
  24594. }); // Extra events
  24595. // TODO register?
  24596. each$3(['selectchanged'], function (eventType) {
  24597. _this._messageCenter.on(eventType, function (event) {
  24598. this.trigger(eventType, event);
  24599. }, _this);
  24600. });
  24601. handleLegacySelectEvents(this._messageCenter, this, this._api);
  24602. };
  24603. ECharts.prototype.isDisposed = function () {
  24604. return this._disposed;
  24605. };
  24606. ECharts.prototype.clear = function () {
  24607. if (this._disposed) {
  24608. disposedWarning(this.id);
  24609. return;
  24610. }
  24611. this.setOption({
  24612. series: []
  24613. }, true);
  24614. };
  24615. ECharts.prototype.dispose = function () {
  24616. if (this._disposed) {
  24617. disposedWarning(this.id);
  24618. return;
  24619. }
  24620. this._disposed = true;
  24621. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24622. var api = this._api;
  24623. var ecModel = this._model;
  24624. each$3(this._componentsViews, function (component) {
  24625. component.dispose(ecModel, api);
  24626. });
  24627. each$3(this._chartsViews, function (chart) {
  24628. chart.dispose(ecModel, api);
  24629. }); // Dispose after all views disposed
  24630. this._zr.dispose();
  24631. delete instances$1[this.id];
  24632. };
  24633. /**
  24634. * Resize the chart
  24635. */
  24636. ECharts.prototype.resize = function (opts) {
  24637. if ("development" !== 'production') {
  24638. assert$1(!this[IN_MAIN_PROCESS_KEY], '`resize` should not be called during main process.');
  24639. }
  24640. if (this._disposed) {
  24641. disposedWarning(this.id);
  24642. return;
  24643. }
  24644. this._zr.resize(opts);
  24645. var ecModel = this._model; // Resize loading effect
  24646. this._loadingFX && this._loadingFX.resize();
  24647. if (!ecModel) {
  24648. return;
  24649. }
  24650. var optionChanged = ecModel.resetOption('media');
  24651. var silent = opts && opts.silent;
  24652. this[IN_MAIN_PROCESS_KEY] = true;
  24653. optionChanged && prepare(this);
  24654. updateMethods.update.call(this, {
  24655. type: 'resize',
  24656. animation: {
  24657. // Disable animation
  24658. duration: 0
  24659. }
  24660. });
  24661. this[IN_MAIN_PROCESS_KEY] = false;
  24662. flushPendingActions.call(this, silent);
  24663. triggerUpdatedEvent.call(this, silent);
  24664. };
  24665. ECharts.prototype.showLoading = function (name, cfg) {
  24666. if (this._disposed) {
  24667. disposedWarning(this.id);
  24668. return;
  24669. }
  24670. if (isObject$2(name)) {
  24671. cfg = name;
  24672. name = '';
  24673. }
  24674. name = name || 'default';
  24675. this.hideLoading();
  24676. if (!loadingEffects[name]) {
  24677. if ("development" !== 'production') {
  24678. console.warn('Loading effects ' + name + ' not exists.');
  24679. }
  24680. return;
  24681. }
  24682. var el = loadingEffects[name](this._api, cfg);
  24683. var zr = this._zr;
  24684. this._loadingFX = el;
  24685. zr.add(el);
  24686. };
  24687. /**
  24688. * Hide loading effect
  24689. */
  24690. ECharts.prototype.hideLoading = function () {
  24691. if (this._disposed) {
  24692. disposedWarning(this.id);
  24693. return;
  24694. }
  24695. this._loadingFX && this._zr.remove(this._loadingFX);
  24696. this._loadingFX = null;
  24697. };
  24698. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  24699. var payload = extend({}, eventObj);
  24700. payload.type = eventActionMap[eventObj.type];
  24701. return payload;
  24702. };
  24703. /**
  24704. * @param opt If pass boolean, means opt.silent
  24705. * @param opt.silent Default `false`. Whether trigger events.
  24706. * @param opt.flush Default `undefined`.
  24707. * true: Flush immediately, and then pixel in canvas can be fetched
  24708. * immediately. Caution: it might affect performance.
  24709. * false: Not flush.
  24710. * undefined: Auto decide whether perform flush.
  24711. */
  24712. ECharts.prototype.dispatchAction = function (payload, opt) {
  24713. if (this._disposed) {
  24714. disposedWarning(this.id);
  24715. return;
  24716. }
  24717. if (!isObject$2(opt)) {
  24718. opt = {
  24719. silent: !!opt
  24720. };
  24721. }
  24722. if (!actions[payload.type]) {
  24723. return;
  24724. } // Avoid dispatch action before setOption. Especially in `connect`.
  24725. if (!this._model) {
  24726. return;
  24727. } // May dispatchAction in rendering procedure
  24728. if (this[IN_MAIN_PROCESS_KEY]) {
  24729. this._pendingActions.push(payload);
  24730. return;
  24731. }
  24732. var silent = opt.silent;
  24733. doDispatchAction.call(this, payload, silent);
  24734. var flush = opt.flush;
  24735. if (flush) {
  24736. this._zr.flush();
  24737. } else if (flush !== false && env.browser.weChat) {
  24738. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  24739. // hang when sliding page (on touch event), which cause that zr does not
  24740. // refresh util user interaction finished, which is not expected.
  24741. // But `dispatchAction` may be called too frequently when pan on touch
  24742. // screen, which impacts performance if do not throttle them.
  24743. this._throttledZrFlush();
  24744. }
  24745. flushPendingActions.call(this, silent);
  24746. triggerUpdatedEvent.call(this, silent);
  24747. };
  24748. ECharts.prototype.updateLabelLayout = function () {
  24749. var labelManager = this._labelManager;
  24750. labelManager.updateLayoutConfig(this._api);
  24751. labelManager.layout(this._api);
  24752. labelManager.processLabelsOverall();
  24753. };
  24754. ECharts.prototype.appendData = function (params) {
  24755. if (this._disposed) {
  24756. disposedWarning(this.id);
  24757. return;
  24758. }
  24759. var seriesIndex = params.seriesIndex;
  24760. var ecModel = this.getModel();
  24761. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24762. if ("development" !== 'production') {
  24763. assert$1(params.data && seriesModel);
  24764. }
  24765. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  24766. // system, util some scenario require that. In the expected usage of
  24767. // `appendData`, the initial extent of coordinate system should better
  24768. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24769. // the extent changed while `appendData`, the location of the painted
  24770. // graphic elements have to be changed, which make the usage of
  24771. // `appendData` meaningless.
  24772. this._scheduler.unfinished = true;
  24773. this.getZr().wakeUp();
  24774. }; // A work around for no `internal` modifier in ts yet but
  24775. // need to strictly hide private methods to JS users.
  24776. ECharts.internalField = function () {
  24777. prepare = function (ecIns) {
  24778. var scheduler = ecIns._scheduler;
  24779. scheduler.restorePipelines(ecIns._model);
  24780. scheduler.prepareStageTasks();
  24781. prepareView(ecIns, true);
  24782. prepareView(ecIns, false);
  24783. scheduler.plan();
  24784. };
  24785. /**
  24786. * Prepare view instances of charts and components
  24787. */
  24788. prepareView = function (ecIns, isComponent) {
  24789. var ecModel = ecIns._model;
  24790. var scheduler = ecIns._scheduler;
  24791. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24792. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24793. var zr = ecIns._zr;
  24794. var api = ecIns._api;
  24795. for (var i = 0; i < viewList.length; i++) {
  24796. viewList[i].__alive = false;
  24797. }
  24798. isComponent ? ecModel.eachComponent(function (componentType, model) {
  24799. componentType !== 'series' && doPrepare(model);
  24800. }) : ecModel.eachSeries(doPrepare);
  24801. function doPrepare(model) {
  24802. // By defaut view will be reused if possible for the case that `setOption` with "notMerge"
  24803. // mode and need to enable transition animation. (Usually, when they have the same id, or
  24804. // especially no id but have the same type & name & index. See the `model.id` generation
  24805. // rule in `makeIdAndName` and `viewId` generation rule here).
  24806. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  24807. // the new model has nothing to do with the old model.
  24808. var requireNewView = model.__requireNewView; // This command should not work twice.
  24809. model.__requireNewView = false; // Consider: id same and type changed.
  24810. var viewId = '_ec_' + model.id + '_' + model.type;
  24811. var view = !requireNewView && viewMap[viewId];
  24812. if (!view) {
  24813. var classType = parseClassType(model.type);
  24814. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  24815. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  24816. // For backward compat, still support a chart type declared as only subType
  24817. // like "liquidfill", but recommend "series.liquidfill"
  24818. // But need a base class to make a type series.
  24819. ChartView.getClass(classType.sub);
  24820. if ("development" !== 'production') {
  24821. assert$1(Clazz, classType.sub + ' does not exist.');
  24822. }
  24823. view = new Clazz();
  24824. view.init(ecModel, api);
  24825. viewMap[viewId] = view;
  24826. viewList.push(view);
  24827. zr.add(view.group);
  24828. }
  24829. model.__viewId = view.__id = viewId;
  24830. view.__alive = true;
  24831. view.__model = model;
  24832. view.group.__ecComponentInfo = {
  24833. mainType: model.mainType,
  24834. index: model.componentIndex
  24835. };
  24836. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24837. }
  24838. for (var i = 0; i < viewList.length;) {
  24839. var view = viewList[i];
  24840. if (!view.__alive) {
  24841. !isComponent && view.renderTask.dispose();
  24842. zr.remove(view.group);
  24843. view.dispose(ecModel, api);
  24844. viewList.splice(i, 1);
  24845. if (viewMap[view.__id] === view) {
  24846. delete viewMap[view.__id];
  24847. }
  24848. view.__id = view.group.__ecComponentInfo = null;
  24849. } else {
  24850. i++;
  24851. }
  24852. }
  24853. };
  24854. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  24855. var ecModel = ecIns._model;
  24856. ecModel.setUpdatePayload(payload); // broadcast
  24857. if (!mainType) {
  24858. // FIXME
  24859. // Chart will not be update directly here, except set dirty.
  24860. // But there is no such scenario now.
  24861. each$3([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  24862. return;
  24863. }
  24864. var query = {};
  24865. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24866. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24867. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24868. var condition = {
  24869. mainType: mainType,
  24870. query: query
  24871. };
  24872. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24873. var excludeSeriesId = payload.excludeSeriesId;
  24874. var excludeSeriesIdMap;
  24875. if (excludeSeriesId != null) {
  24876. excludeSeriesIdMap = createHashMap();
  24877. each$3(normalizeToArray(excludeSeriesId), function (id) {
  24878. var modelId = convertOptionIdName(id, null);
  24879. if (modelId != null) {
  24880. excludeSeriesIdMap.set(modelId, true);
  24881. }
  24882. });
  24883. } // If dispatchAction before setOption, do nothing.
  24884. ecModel && ecModel.eachComponent(condition, function (model) {
  24885. if (!excludeSeriesIdMap || excludeSeriesIdMap.get(model.id) == null) {
  24886. if (isHighDownPayload(payload) && !payload.notBlur) {
  24887. if (model instanceof SeriesModel) {
  24888. toggleSeriesBlurStateFromPayload(model, payload, ecIns._api);
  24889. }
  24890. } else if (isSelectChangePayload(payload)) {
  24891. // TODO geo
  24892. if (model instanceof SeriesModel) {
  24893. toggleSelectionFromPayload(model, payload, ecIns._api);
  24894. updateSeriesElementSelection(model);
  24895. markStatusToUpdate(ecIns);
  24896. }
  24897. }
  24898. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  24899. }
  24900. }, ecIns);
  24901. function callView(view) {
  24902. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  24903. }
  24904. };
  24905. updateMethods = {
  24906. prepareAndUpdate: function (payload) {
  24907. prepare(this);
  24908. updateMethods.update.call(this, payload);
  24909. },
  24910. update: function (payload) {
  24911. // console.profile && console.profile('update');
  24912. var ecModel = this._model;
  24913. var api = this._api;
  24914. var zr = this._zr;
  24915. var coordSysMgr = this._coordSysMgr;
  24916. var scheduler = this._scheduler; // update before setOption
  24917. if (!ecModel) {
  24918. return;
  24919. }
  24920. ecModel.setUpdatePayload(payload);
  24921. scheduler.restoreData(ecModel, payload);
  24922. scheduler.performSeriesTasks(ecModel); // TODO
  24923. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24924. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24925. // Create new coordinate system each update
  24926. // In LineView may save the old coordinate system and use it to get the orignal point
  24927. coordSysMgr.create(ecModel, api);
  24928. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  24929. // stream modes after data processing, where the filtered data is used to
  24930. // deteming whether use progressive rendering.
  24931. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  24932. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24933. // the drawback is the full coord info can not be fetched. Fortunately this full
  24934. // coord is not requied in stream mode updater currently.
  24935. coordSysMgr.update(ecModel, api);
  24936. clearColorPalette(ecModel);
  24937. scheduler.performVisualTasks(ecModel, payload);
  24938. render(this, ecModel, api, payload); // Set background
  24939. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24940. var darkMode = ecModel.get('darkMode'); // In IE8
  24941. if (!env.canvasSupported) {
  24942. var colorArr = parse(backgroundColor);
  24943. backgroundColor = stringify(colorArr, 'rgb');
  24944. if (colorArr[3] === 0) {
  24945. backgroundColor = 'transparent';
  24946. }
  24947. } else {
  24948. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  24949. if (darkMode != null && darkMode !== 'auto') {
  24950. zr.setDarkMode(darkMode);
  24951. }
  24952. }
  24953. performPostUpdateFuncs(ecModel, api); // console.profile && console.profileEnd('update');
  24954. },
  24955. updateTransform: function (payload) {
  24956. var _this = this;
  24957. var ecModel = this._model;
  24958. var api = this._api; // update before setOption
  24959. if (!ecModel) {
  24960. return;
  24961. }
  24962. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  24963. var componentDirtyList = [];
  24964. ecModel.eachComponent(function (componentType, componentModel) {
  24965. if (componentType === 'series') {
  24966. return;
  24967. }
  24968. var componentView = _this.getViewOfComponentModel(componentModel);
  24969. if (componentView && componentView.__alive) {
  24970. if (componentView.updateTransform) {
  24971. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24972. result && result.update && componentDirtyList.push(componentView);
  24973. } else {
  24974. componentDirtyList.push(componentView);
  24975. }
  24976. }
  24977. });
  24978. var seriesDirtyMap = createHashMap();
  24979. ecModel.eachSeries(function (seriesModel) {
  24980. var chartView = _this._chartsMap[seriesModel.__viewId];
  24981. if (chartView.updateTransform) {
  24982. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24983. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24984. } else {
  24985. seriesDirtyMap.set(seriesModel.uid, 1);
  24986. }
  24987. });
  24988. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24989. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24990. this._scheduler.performVisualTasks(ecModel, payload, {
  24991. setDirty: true,
  24992. dirtyMap: seriesDirtyMap
  24993. }); // Currently, not call render of components. Geo render cost a lot.
  24994. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24995. renderSeries(this, ecModel, api, payload, seriesDirtyMap);
  24996. performPostUpdateFuncs(ecModel, this._api);
  24997. },
  24998. updateView: function (payload) {
  24999. var ecModel = this._model; // update before setOption
  25000. if (!ecModel) {
  25001. return;
  25002. }
  25003. ecModel.setUpdatePayload(payload);
  25004. ChartView.markUpdateMethod(payload, 'updateView');
  25005. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25006. this._scheduler.performVisualTasks(ecModel, payload, {
  25007. setDirty: true
  25008. });
  25009. render(this, this._model, this._api, payload);
  25010. performPostUpdateFuncs(ecModel, this._api);
  25011. },
  25012. updateVisual: function (payload) {
  25013. // updateMethods.update.call(this, payload);
  25014. var _this = this;
  25015. var ecModel = this._model; // update before setOption
  25016. if (!ecModel) {
  25017. return;
  25018. }
  25019. ecModel.setUpdatePayload(payload); // clear all visual
  25020. ecModel.eachSeries(function (seriesModel) {
  25021. seriesModel.getData().clearAllVisual();
  25022. }); // Perform visual
  25023. ChartView.markUpdateMethod(payload, 'updateVisual');
  25024. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25025. this._scheduler.performVisualTasks(ecModel, payload, {
  25026. visualType: 'visual',
  25027. setDirty: true
  25028. });
  25029. ecModel.eachComponent(function (componentType, componentModel) {
  25030. if (componentType !== 'series') {
  25031. var componentView = _this.getViewOfComponentModel(componentModel);
  25032. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  25033. }
  25034. });
  25035. ecModel.eachSeries(function (seriesModel) {
  25036. var chartView = _this._chartsMap[seriesModel.__viewId];
  25037. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  25038. });
  25039. performPostUpdateFuncs(ecModel, this._api);
  25040. },
  25041. updateLayout: function (payload) {
  25042. updateMethods.update.call(this, payload);
  25043. }
  25044. };
  25045. doConvertPixel = function (ecIns, methodName, finder, value) {
  25046. if (ecIns._disposed) {
  25047. disposedWarning(ecIns.id);
  25048. return;
  25049. }
  25050. var ecModel = ecIns._model;
  25051. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  25052. var result;
  25053. var parsedFinder = parseFinder(ecModel, finder);
  25054. for (var i = 0; i < coordSysList.length; i++) {
  25055. var coordSys = coordSysList[i];
  25056. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  25057. return result;
  25058. }
  25059. }
  25060. if ("development" !== 'production') {
  25061. console.warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  25062. }
  25063. };
  25064. updateStreamModes = function (ecIns, ecModel) {
  25065. var chartsMap = ecIns._chartsMap;
  25066. var scheduler = ecIns._scheduler;
  25067. ecModel.eachSeries(function (seriesModel) {
  25068. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25069. });
  25070. };
  25071. doDispatchAction = function (payload, silent) {
  25072. var _this = this;
  25073. var ecModel = this.getModel();
  25074. var payloadType = payload.type;
  25075. var escapeConnect = payload.escapeConnect;
  25076. var actionWrap = actions[payloadType];
  25077. var actionInfo = actionWrap.actionInfo;
  25078. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  25079. var updateMethod = cptTypeTmp.pop();
  25080. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  25081. this[IN_MAIN_PROCESS_KEY] = true;
  25082. var payloads = [payload];
  25083. var batched = false; // Batch action
  25084. if (payload.batch) {
  25085. batched = true;
  25086. payloads = map(payload.batch, function (item) {
  25087. item = defaults(extend({}, item), payload);
  25088. item.batch = null;
  25089. return item;
  25090. });
  25091. }
  25092. var eventObjBatch = [];
  25093. var eventObj;
  25094. var isSelectChange = isSelectChangePayload(payload);
  25095. var isStatusChange = isHighDownPayload(payload) || isSelectChange;
  25096. each$3(payloads, function (batchItem) {
  25097. // Action can specify the event by return it.
  25098. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  25099. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  25100. eventObj.type = actionInfo.event || eventObj.type;
  25101. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  25102. if (isStatusChange) {
  25103. // method, payload, mainType, subType
  25104. updateDirectly(_this, updateMethod, batchItem, 'series'); // Mark status to update
  25105. markStatusToUpdate(_this);
  25106. } else if (cptType) {
  25107. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  25108. }
  25109. });
  25110. if (updateMethod !== 'none' && !isStatusChange && !cptType) {
  25111. // Still dirty
  25112. if (this[OPTION_UPDATED_KEY]) {
  25113. prepare(this);
  25114. updateMethods.update.call(this, payload);
  25115. this[OPTION_UPDATED_KEY] = false;
  25116. } else {
  25117. updateMethods[updateMethod].call(this, payload);
  25118. }
  25119. } // Follow the rule of action batch
  25120. if (batched) {
  25121. eventObj = {
  25122. type: actionInfo.event || payloadType,
  25123. escapeConnect: escapeConnect,
  25124. batch: eventObjBatch
  25125. };
  25126. } else {
  25127. eventObj = eventObjBatch[0];
  25128. }
  25129. this[IN_MAIN_PROCESS_KEY] = false;
  25130. if (!silent) {
  25131. var messageCenter = this._messageCenter;
  25132. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  25133. if (isSelectChange) {
  25134. var newObj = {
  25135. type: 'selectchanged',
  25136. escapeConnect: escapeConnect,
  25137. selected: getAllSelectedIndices(ecModel),
  25138. isFromClick: payload.isFromClick || false,
  25139. fromAction: payload.type,
  25140. fromActionPayload: payload
  25141. };
  25142. messageCenter.trigger(newObj.type, newObj);
  25143. }
  25144. }
  25145. };
  25146. flushPendingActions = function (silent) {
  25147. var pendingActions = this._pendingActions;
  25148. while (pendingActions.length) {
  25149. var payload = pendingActions.shift();
  25150. doDispatchAction.call(this, payload, silent);
  25151. }
  25152. };
  25153. triggerUpdatedEvent = function (silent) {
  25154. !silent && this.trigger('updated');
  25155. };
  25156. /**
  25157. * Event `rendered` is triggered when zr
  25158. * rendered. It is useful for realtime
  25159. * snapshot (reflect animation).
  25160. *
  25161. * Event `finished` is triggered when:
  25162. * (1) zrender rendering finished.
  25163. * (2) initial animation finished.
  25164. * (3) progressive rendering finished.
  25165. * (4) no pending action.
  25166. * (5) no delayed setOption needs to be processed.
  25167. */
  25168. bindRenderedEvent = function (zr, ecIns) {
  25169. zr.on('rendered', function (params) {
  25170. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatly,
  25171. // so it should only be triggered when rendering indeed happend
  25172. // in zrender. (Consider the case that dipatchAction is keep
  25173. // triggering when mouse move).
  25174. if ( // Although zr is dirty if initial animation is not finished
  25175. // and this checking is called on frame, we also check
  25176. // animation finished for robustness.
  25177. zr.animation.isFinished() && !ecIns[OPTION_UPDATED_KEY] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  25178. ecIns.trigger('finished');
  25179. }
  25180. });
  25181. };
  25182. bindMouseEvent = function (zr, ecIns) {
  25183. zr.on('mouseover', function (e) {
  25184. var el = e.target;
  25185. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  25186. if (dispatcher) {
  25187. var ecData = getECData(dispatcher); // Try blur all in the related series. Then emphasis the hoverred.
  25188. // TODO. progressive mode.
  25189. toggleSeriesBlurState(ecData.seriesIndex, ecData.focus, ecData.blurScope, ecIns._api, true);
  25190. enterEmphasisWhenMouseOver(dispatcher, e);
  25191. markStatusToUpdate(ecIns);
  25192. }
  25193. }).on('mouseout', function (e) {
  25194. var el = e.target;
  25195. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  25196. if (dispatcher) {
  25197. var ecData = getECData(dispatcher);
  25198. toggleSeriesBlurState(ecData.seriesIndex, ecData.focus, ecData.blurScope, ecIns._api, false);
  25199. leaveEmphasisWhenMouseOut(dispatcher, e);
  25200. markStatusToUpdate(ecIns);
  25201. }
  25202. }).on('click', function (e) {
  25203. var el = e.target;
  25204. var dispatcher = findEventDispatcher(el, function (target) {
  25205. return getECData(target).dataIndex != null;
  25206. }, true);
  25207. if (dispatcher) {
  25208. var actionType = dispatcher.selected ? 'unselect' : 'select';
  25209. var ecData = getECData(dispatcher);
  25210. ecIns._api.dispatchAction({
  25211. type: actionType,
  25212. dataType: ecData.dataType,
  25213. dataIndexInside: ecData.dataIndex,
  25214. seriesIndex: ecData.seriesIndex,
  25215. isFromClick: true
  25216. });
  25217. }
  25218. });
  25219. };
  25220. clearColorPalette = function (ecModel) {
  25221. ecModel.clearColorPalette();
  25222. ecModel.eachSeries(function (seriesModel) {
  25223. seriesModel.clearColorPalette();
  25224. });
  25225. };
  25226. render = function (ecIns, ecModel, api, payload) {
  25227. renderComponents(ecIns, ecModel, api, payload);
  25228. each$3(ecIns._chartsViews, function (chart) {
  25229. chart.__alive = false;
  25230. });
  25231. renderSeries(ecIns, ecModel, api, payload); // Remove groups of unrendered charts
  25232. each$3(ecIns._chartsViews, function (chart) {
  25233. if (!chart.__alive) {
  25234. chart.remove(ecModel, api);
  25235. }
  25236. });
  25237. };
  25238. renderComponents = function (ecIns, ecModel, api, payload, dirtyList) {
  25239. each$3(dirtyList || ecIns._componentsViews, function (componentView) {
  25240. var componentModel = componentView.__model;
  25241. clearStates(componentModel, componentView);
  25242. componentView.render(componentModel, ecModel, api, payload);
  25243. updateZ(componentModel, componentView);
  25244. updateStates(componentModel, componentView);
  25245. });
  25246. };
  25247. /**
  25248. * Render each chart and component
  25249. */
  25250. renderSeries = function (ecIns, ecModel, api, payload, dirtyMap) {
  25251. // Render all charts
  25252. var scheduler = ecIns._scheduler;
  25253. var labelManager = ecIns._labelManager;
  25254. labelManager.clearLabels();
  25255. var unfinished = false;
  25256. ecModel.eachSeries(function (seriesModel) {
  25257. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25258. chartView.__alive = true;
  25259. var renderTask = chartView.renderTask;
  25260. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  25261. clearStates(seriesModel, chartView);
  25262. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25263. renderTask.dirty();
  25264. }
  25265. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  25266. unfinished = true;
  25267. }
  25268. seriesModel.__transientTransitionOpt = null;
  25269. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  25270. // increamental render (alway render from the __startIndex each frame)
  25271. // chartView.group.markRedraw();
  25272. updateBlend(seriesModel, chartView);
  25273. updateSeriesElementSelection(seriesModel); // Add labels.
  25274. labelManager.addLabelsOfSeries(chartView);
  25275. });
  25276. scheduler.unfinished = unfinished || scheduler.unfinished;
  25277. labelManager.updateLayoutConfig(api);
  25278. labelManager.layout(api);
  25279. labelManager.processLabelsOverall();
  25280. ecModel.eachSeries(function (seriesModel) {
  25281. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  25282. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  25283. // label should be in normal status when layouting.
  25284. updateStates(seriesModel, chartView);
  25285. }); // If use hover layer
  25286. updateHoverLayerStatus(ecIns, ecModel);
  25287. };
  25288. performPostUpdateFuncs = function (ecModel, api) {
  25289. each$3(postUpdateFuncs, function (func) {
  25290. func(ecModel, api);
  25291. });
  25292. };
  25293. markStatusToUpdate = function (ecIns) {
  25294. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  25295. ecIns.getZr().wakeUp();
  25296. };
  25297. applyChangedStates = function (ecIns) {
  25298. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  25299. return;
  25300. }
  25301. ecIns.getZr().storage.traverse(function (el) {
  25302. // Not applied on removed elements, it may still in fading.
  25303. if (isElementRemoved(el)) {
  25304. return;
  25305. }
  25306. applyElementStates(el);
  25307. });
  25308. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  25309. };
  25310. function applyElementStates(el) {
  25311. var newStates = [];
  25312. var oldStates = el.currentStates; // Keep other states.
  25313. for (var i = 0; i < oldStates.length; i++) {
  25314. var stateName = oldStates[i];
  25315. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  25316. newStates.push(stateName);
  25317. }
  25318. } // Only use states when it's exists.
  25319. if (el.selected && el.states.select) {
  25320. newStates.push('select');
  25321. }
  25322. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  25323. newStates.push('emphasis');
  25324. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  25325. newStates.push('blur');
  25326. }
  25327. el.useStates(newStates);
  25328. }
  25329. function updateHoverLayerStatus(ecIns, ecModel) {
  25330. var zr = ecIns._zr;
  25331. var storage = zr.storage;
  25332. var elCount = 0;
  25333. storage.traverse(function (el) {
  25334. if (!el.isGroup) {
  25335. elCount++;
  25336. }
  25337. });
  25338. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  25339. ecModel.eachSeries(function (seriesModel) {
  25340. if (seriesModel.preventUsingHoverLayer) {
  25341. return;
  25342. }
  25343. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25344. if (chartView.__alive) {
  25345. chartView.group.traverse(function (el) {
  25346. if (el.states.emphasis) {
  25347. el.states.emphasis.hoverLayer = true;
  25348. }
  25349. });
  25350. }
  25351. });
  25352. }
  25353. }
  25354. /**
  25355. * Update chart and blend.
  25356. */
  25357. function updateBlend(seriesModel, chartView) {
  25358. var blendMode = seriesModel.get('blendMode') || null;
  25359. if ("development" !== 'production') {
  25360. if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
  25361. console.warn('Only canvas support blendMode');
  25362. }
  25363. }
  25364. chartView.group.traverse(function (el) {
  25365. // FIXME marker and other components
  25366. if (!el.isGroup) {
  25367. // DONT mark the element dirty. In case element is incremental and don't wan't to rerender.
  25368. el.style.blend = blendMode;
  25369. }
  25370. if (el.eachPendingDisplayable) {
  25371. el.eachPendingDisplayable(function (displayable) {
  25372. displayable.style.blend = blendMode;
  25373. });
  25374. }
  25375. });
  25376. }
  25377. function updateZ(model, view) {
  25378. if (model.preventAutoZ) {
  25379. return;
  25380. }
  25381. var z = model.get('z');
  25382. var zlevel = model.get('zlevel'); // Set z and zlevel
  25383. view.group.traverse(function (el) {
  25384. if (!el.isGroup) {
  25385. z != null && (el.z = z);
  25386. zlevel != null && (el.zlevel = zlevel); // TODO if textContent is on group.
  25387. var label = el.getTextContent();
  25388. var labelLine = el.getTextGuideLine();
  25389. if (label) {
  25390. label.z = el.z;
  25391. label.zlevel = el.zlevel; // lift z2 of text content
  25392. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  25393. label.z2 = el.z2 + 2;
  25394. }
  25395. if (labelLine) {
  25396. var showAbove = el.textGuideLineConfig && el.textGuideLineConfig.showAbove;
  25397. labelLine.z = el.z;
  25398. labelLine.zlevel = el.zlevel;
  25399. labelLine.z2 = el.z2 + (showAbove ? 1 : -1);
  25400. }
  25401. }
  25402. });
  25403. }
  25404. // TODO States on component.
  25405. function clearStates(model, view) {
  25406. view.group.traverse(function (el) {
  25407. // Not applied on removed elements, it may still in fading.
  25408. if (isElementRemoved(el)) {
  25409. return;
  25410. }
  25411. var textContent = el.getTextContent();
  25412. var textGuide = el.getTextGuideLine();
  25413. if (el.stateTransition) {
  25414. el.stateTransition = null;
  25415. }
  25416. if (textContent && textContent.stateTransition) {
  25417. textContent.stateTransition = null;
  25418. }
  25419. if (textGuide && textGuide.stateTransition) {
  25420. textGuide.stateTransition = null;
  25421. } // TODO If el is incremental.
  25422. if (el.hasState()) {
  25423. el.prevStates = el.currentStates;
  25424. el.clearStates();
  25425. } else if (el.prevStates) {
  25426. el.prevStates = null;
  25427. }
  25428. });
  25429. }
  25430. function updateStates(model, view) {
  25431. var stateAnimationModel = model.getModel('stateAnimation');
  25432. var enableAnimation = model.isAnimationEnabled();
  25433. var duration = stateAnimationModel.get('duration');
  25434. var stateTransition = duration > 0 ? {
  25435. duration: duration,
  25436. delay: stateAnimationModel.get('delay'),
  25437. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  25438. } : null;
  25439. view.group.traverse(function (el) {
  25440. if (el.states && el.states.emphasis) {
  25441. // Not applied on removed elements, it may still in fading.
  25442. if (isElementRemoved(el)) {
  25443. return;
  25444. }
  25445. if (el instanceof Path) {
  25446. savePathStates(el);
  25447. } // Only updated on changed element. In case element is incremental and don't wan't to rerender.
  25448. // TODO, a more proper way?
  25449. if (el.__dirty) {
  25450. var prevStates = el.prevStates; // Restore states without animation
  25451. if (prevStates) {
  25452. el.useStates(prevStates);
  25453. }
  25454. } // Update state transition and enable animation again.
  25455. if (enableAnimation) {
  25456. el.stateTransition = stateTransition;
  25457. var textContent = el.getTextContent();
  25458. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  25459. if (textContent) {
  25460. textContent.stateTransition = stateTransition;
  25461. }
  25462. if (textGuide) {
  25463. textGuide.stateTransition = stateTransition;
  25464. }
  25465. } // The use higlighted and selected flag to toggle states.
  25466. if (el.__dirty) {
  25467. applyElementStates(el);
  25468. }
  25469. }
  25470. });
  25471. }
  25472. createExtensionAPI = function (ecIns) {
  25473. return new (
  25474. /** @class */
  25475. function (_super) {
  25476. __extends(class_1, _super);
  25477. function class_1() {
  25478. return _super !== null && _super.apply(this, arguments) || this;
  25479. }
  25480. class_1.prototype.getCoordinateSystems = function () {
  25481. return ecIns._coordSysMgr.getCoordinateSystems();
  25482. };
  25483. class_1.prototype.getComponentByElement = function (el) {
  25484. while (el) {
  25485. var modelInfo = el.__ecComponentInfo;
  25486. if (modelInfo != null) {
  25487. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  25488. }
  25489. el = el.parent;
  25490. }
  25491. };
  25492. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  25493. enterEmphasis(el, highlightDigit);
  25494. markStatusToUpdate(ecIns);
  25495. };
  25496. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  25497. leaveEmphasis(el, highlightDigit);
  25498. markStatusToUpdate(ecIns);
  25499. };
  25500. class_1.prototype.enterBlur = function (el) {
  25501. enterBlur(el);
  25502. markStatusToUpdate(ecIns);
  25503. };
  25504. class_1.prototype.leaveBlur = function (el) {
  25505. leaveBlur(el);
  25506. markStatusToUpdate(ecIns);
  25507. };
  25508. class_1.prototype.enterSelect = function (el) {
  25509. enterSelect(el);
  25510. markStatusToUpdate(ecIns);
  25511. };
  25512. class_1.prototype.leaveSelect = function (el) {
  25513. leaveSelect(el);
  25514. markStatusToUpdate(ecIns);
  25515. };
  25516. class_1.prototype.getModel = function () {
  25517. return ecIns.getModel();
  25518. };
  25519. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  25520. return ecIns.getViewOfComponentModel(componentModel);
  25521. };
  25522. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  25523. return ecIns.getViewOfSeriesModel(seriesModel);
  25524. };
  25525. return class_1;
  25526. }(ExtensionAPI))(ecIns);
  25527. };
  25528. enableConnect = function (chart) {
  25529. function updateConnectedChartsStatus(charts, status) {
  25530. for (var i = 0; i < charts.length; i++) {
  25531. var otherChart = charts[i];
  25532. otherChart[CONNECT_STATUS_KEY] = status;
  25533. }
  25534. }
  25535. each$3(eventActionMap, function (actionType, eventType) {
  25536. chart._messageCenter.on(eventType, function (event) {
  25537. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  25538. if (event && event.escapeConnect) {
  25539. return;
  25540. }
  25541. var action_1 = chart.makeActionFromEvent(event);
  25542. var otherCharts_1 = [];
  25543. each$3(instances$1, function (otherChart) {
  25544. if (otherChart !== chart && otherChart.group === chart.group) {
  25545. otherCharts_1.push(otherChart);
  25546. }
  25547. });
  25548. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  25549. each$3(otherCharts_1, function (otherChart) {
  25550. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  25551. otherChart.dispatchAction(action_1);
  25552. }
  25553. });
  25554. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  25555. }
  25556. });
  25557. });
  25558. };
  25559. setTransitionOpt = function (chart, transitionOpt) {
  25560. var ecModel = chart._model;
  25561. each(normalizeToArray(transitionOpt), function (transOpt) {
  25562. var errMsg;
  25563. var fromOpt = transOpt.from;
  25564. var toOpt = transOpt.to;
  25565. if (toOpt == null) {
  25566. if ("development" !== 'production') {
  25567. errMsg = '`transition.to` must be specified.';
  25568. }
  25569. throwError(errMsg);
  25570. }
  25571. var finderOpt = {
  25572. includeMainTypes: ['series'],
  25573. enableAll: false,
  25574. enableNone: false
  25575. };
  25576. var fromResult = fromOpt ? parseFinder(ecModel, fromOpt, finderOpt) : null;
  25577. var toResult = parseFinder(ecModel, toOpt, finderOpt);
  25578. var toSeries = toResult.seriesModel;
  25579. if (toSeries == null) {
  25580. errMsg = '';
  25581. if ("development" !== 'production') {
  25582. errMsg = '`transition` is only supported on series.';
  25583. }
  25584. }
  25585. if (fromResult && fromResult.seriesModel !== toSeries) {
  25586. errMsg = '';
  25587. if ("development" !== 'production') {
  25588. errMsg = '`transition.from` and `transition.to` must be specified to the same series.';
  25589. }
  25590. }
  25591. if (errMsg != null) {
  25592. throwError(errMsg);
  25593. } // Just a temp solution: mount them on series.
  25594. toSeries.__transientTransitionOpt = {
  25595. from: fromOpt ? fromOpt.dimension : null,
  25596. to: toOpt.dimension,
  25597. dividingMethod: transOpt.dividingMethod
  25598. };
  25599. });
  25600. };
  25601. }();
  25602. return ECharts;
  25603. }(Eventful);
  25604. var echartsProto = ECharts.prototype;
  25605. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  25606. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  25607. /**
  25608. * @deprecated
  25609. */
  25610. // @ts-ignore
  25611. echartsProto.one = function (eventName, cb, ctx) {
  25612. var self = this;
  25613. deprecateLog('ECharts#one is deprecated.');
  25614. function wrapped() {
  25615. var args2 = [];
  25616. for (var _i = 0; _i < arguments.length; _i++) {
  25617. args2[_i] = arguments[_i];
  25618. }
  25619. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  25620. self.off(eventName, wrapped);
  25621. }
  25622. this.on.call(this, eventName, wrapped, ctx);
  25623. }; // /**
  25624. // * Encode visual infomation from data after data processing
  25625. // *
  25626. // * @param {module:echarts/model/Global} ecModel
  25627. // * @param {object} layout
  25628. // * @param {boolean} [layoutFilter] `true`: only layout,
  25629. // * `false`: only not layout,
  25630. // * `null`/`undefined`: all.
  25631. // * @param {string} taskBaseTag
  25632. // * @private
  25633. // */
  25634. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25635. // each(visualFuncs, function (visual, index) {
  25636. // let isLayout = visual.isLayout;
  25637. // if (layoutFilter == null
  25638. // || (layoutFilter === false && !isLayout)
  25639. // || (layoutFilter === true && isLayout)
  25640. // ) {
  25641. // visual.func(ecModel, api, payload);
  25642. // }
  25643. // });
  25644. // }
  25645. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  25646. function disposedWarning(id) {
  25647. if ("development" !== 'production') {
  25648. console.warn('Instance ' + id + ' has been disposed');
  25649. }
  25650. }
  25651. var actions = {};
  25652. /**
  25653. * Map eventType to actionType
  25654. */
  25655. var eventActionMap = {};
  25656. var dataProcessorFuncs = [];
  25657. var optionPreprocessorFuncs = [];
  25658. var postInitFuncs = [];
  25659. var postUpdateFuncs = [];
  25660. var visualFuncs = [];
  25661. var themeStorage = {};
  25662. var loadingEffects = {};
  25663. var instances$1 = {};
  25664. var connectedGroups = {};
  25665. var idBase = +new Date() - 0;
  25666. var groupIdBase = +new Date() - 0;
  25667. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25668. /**
  25669. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  25670. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  25671. * @param opts.width Use clientWidth of the input `dom` by default.
  25672. * Can be 'auto' (the same as null/undefined)
  25673. * @param opts.height Use clientHeight of the input `dom` by default.
  25674. * Can be 'auto' (the same as null/undefined)
  25675. */
  25676. function init$1(dom, theme, opts) {
  25677. if ("development" !== 'production') {
  25678. if (!dom) {
  25679. throw new Error('Initialize failed: invalid dom.');
  25680. }
  25681. }
  25682. var existInstance = getInstanceByDom(dom);
  25683. if (existInstance) {
  25684. if ("development" !== 'production') {
  25685. console.warn('There is a chart instance already initialized on the dom.');
  25686. }
  25687. return existInstance;
  25688. }
  25689. if ("development" !== 'production') {
  25690. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  25691. 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.');
  25692. }
  25693. }
  25694. var chart = new ECharts(dom, theme, opts);
  25695. chart.id = 'ec_' + idBase++;
  25696. instances$1[chart.id] = chart;
  25697. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25698. enableConnect(chart);
  25699. each$3(postInitFuncs, function (postInitFunc) {
  25700. postInitFunc(chart);
  25701. });
  25702. return chart;
  25703. }
  25704. /**
  25705. * @usage
  25706. * (A)
  25707. * ```js
  25708. * let chart1 = echarts.init(dom1);
  25709. * let chart2 = echarts.init(dom2);
  25710. * chart1.group = 'xxx';
  25711. * chart2.group = 'xxx';
  25712. * echarts.connect('xxx');
  25713. * ```
  25714. * (B)
  25715. * ```js
  25716. * let chart1 = echarts.init(dom1);
  25717. * let chart2 = echarts.init(dom2);
  25718. * echarts.connect('xxx', [chart1, chart2]);
  25719. * ```
  25720. */
  25721. function connect(groupId) {
  25722. // Is array of charts
  25723. if (isArray(groupId)) {
  25724. var charts = groupId;
  25725. groupId = null; // If any chart has group
  25726. each$3(charts, function (chart) {
  25727. if (chart.group != null) {
  25728. groupId = chart.group;
  25729. }
  25730. });
  25731. groupId = groupId || 'g_' + groupIdBase++;
  25732. each$3(charts, function (chart) {
  25733. chart.group = groupId;
  25734. });
  25735. }
  25736. connectedGroups[groupId] = true;
  25737. return groupId;
  25738. }
  25739. /**
  25740. * @deprecated
  25741. */
  25742. function disConnect(groupId) {
  25743. connectedGroups[groupId] = false;
  25744. }
  25745. /**
  25746. * Alias and backword compat
  25747. */
  25748. var disconnect = disConnect;
  25749. /**
  25750. * Dispose a chart instance
  25751. */
  25752. function dispose$1(chart) {
  25753. if (typeof chart === 'string') {
  25754. chart = instances$1[chart];
  25755. } else if (!(chart instanceof ECharts)) {
  25756. // Try to treat as dom
  25757. chart = getInstanceByDom(chart);
  25758. }
  25759. if (chart instanceof ECharts && !chart.isDisposed()) {
  25760. chart.dispose();
  25761. }
  25762. }
  25763. function getInstanceByDom(dom) {
  25764. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25765. }
  25766. function getInstanceById(key) {
  25767. return instances$1[key];
  25768. }
  25769. /**
  25770. * Register theme
  25771. */
  25772. function registerTheme(name, theme) {
  25773. themeStorage[name] = theme;
  25774. }
  25775. /**
  25776. * Register option preprocessor
  25777. */
  25778. function registerPreprocessor(preprocessorFunc) {
  25779. if (indexOf$1(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  25780. optionPreprocessorFuncs.push(preprocessorFunc);
  25781. }
  25782. }
  25783. function registerProcessor(priority, processor) {
  25784. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  25785. }
  25786. /**
  25787. * Register postIniter
  25788. * @param {Function} postInitFunc
  25789. */
  25790. function registerPostInit(postInitFunc) {
  25791. if (indexOf$1(postInitFuncs, postInitFunc) < 0) {
  25792. postInitFunc && postInitFuncs.push(postInitFunc);
  25793. }
  25794. }
  25795. /**
  25796. * Register postUpdater
  25797. * @param {Function} postUpdateFunc
  25798. */
  25799. function registerPostUpdate(postUpdateFunc) {
  25800. if (indexOf$1(postUpdateFuncs, postUpdateFunc) < 0) {
  25801. postUpdateFunc && postUpdateFuncs.push(postUpdateFunc);
  25802. }
  25803. }
  25804. function registerAction(actionInfo, eventName, action) {
  25805. if (typeof eventName === 'function') {
  25806. action = eventName;
  25807. eventName = '';
  25808. }
  25809. var actionType = isObject$2(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  25810. event: eventName
  25811. }][0]; // Event name is all lowercase
  25812. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25813. eventName = actionInfo.event;
  25814. if (eventActionMap[eventName]) {
  25815. // Already registered.
  25816. return;
  25817. } // Validate action type and event name.
  25818. assert$1(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25819. if (!actions[actionType]) {
  25820. actions[actionType] = {
  25821. action: action,
  25822. actionInfo: actionInfo
  25823. };
  25824. }
  25825. eventActionMap[eventName] = actionType;
  25826. }
  25827. function registerCoordinateSystem(type, coordSysCreator) {
  25828. CoordinateSystemManager.register(type, coordSysCreator);
  25829. }
  25830. /**
  25831. * Get dimensions of specified coordinate system.
  25832. * @param {string} type
  25833. * @return {Array.<string|Object>}
  25834. */
  25835. function getCoordinateSystemDimensions(type) {
  25836. var coordSysCreator = CoordinateSystemManager.get(type);
  25837. if (coordSysCreator) {
  25838. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  25839. }
  25840. }
  25841. function registerLayout(priority, layoutTask) {
  25842. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25843. }
  25844. function registerVisual(priority, visualTask) {
  25845. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25846. }
  25847. var registeredTasks = [];
  25848. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25849. if (isFunction$1(priority) || isObject$2(priority)) {
  25850. fn = priority;
  25851. priority = defaultPriority;
  25852. }
  25853. if ("development" !== 'production') {
  25854. if (isNaN(priority) || priority == null) {
  25855. throw new Error('Illegal priority');
  25856. } // Check duplicate
  25857. each$3(targetList, function (wrap) {
  25858. assert$1(wrap.__raw !== fn);
  25859. });
  25860. } // Already registered
  25861. if (indexOf$1(registeredTasks, fn) >= 0) {
  25862. return;
  25863. }
  25864. registeredTasks.push(fn);
  25865. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25866. stageHandler.__prio = priority;
  25867. stageHandler.__raw = fn;
  25868. targetList.push(stageHandler);
  25869. }
  25870. function registerLoading(name, loadingFx) {
  25871. loadingEffects[name] = loadingFx;
  25872. }
  25873. /**
  25874. * ZRender need a canvas context to do measureText.
  25875. * But in node environment canvas may be created by node-canvas.
  25876. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  25877. *
  25878. * Be careful of using it in the browser.
  25879. *
  25880. * @example
  25881. * let Canvas = require('canvas');
  25882. * let echarts = require('echarts');
  25883. * echarts.setCanvasCreator(function () {
  25884. * // Small size is enough.
  25885. * return new Canvas(32, 32);
  25886. * });
  25887. */
  25888. function setCanvasCreator(creator) {
  25889. $override('createCanvas', creator);
  25890. }
  25891. /**
  25892. * The parameters and usage: see `mapDataStorage.registerMap`.
  25893. * Compatible with previous `echarts.registerMap`.
  25894. */
  25895. function registerMap(mapName, geoJson, specialAreas) {
  25896. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25897. }
  25898. function getMap(mapName) {
  25899. // For backward compatibility, only return the first one.
  25900. var records = mapDataStorage.retrieveMap(mapName); // FIXME support SVG, where return not only records[0].
  25901. return records && records[0] && {
  25902. // @ts-ignore
  25903. geoJson: records[0].geoJSON,
  25904. specialAreas: records[0].specialAreas
  25905. };
  25906. }
  25907. var registerTransform = registerExternalTransform;
  25908. /**
  25909. * Globa dispatchAction to a specified chart instance.
  25910. */
  25911. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  25912. // if (!payload || !payload.chartId) {
  25913. // // Must have chartId to find chart
  25914. // return;
  25915. // }
  25916. // const chart = instances[payload.chartId];
  25917. // if (chart) {
  25918. // chart.dispatchAction(payload, opt);
  25919. // }
  25920. // }
  25921. // Buitlin global visual
  25922. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  25923. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  25924. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  25925. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  25926. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  25927. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  25928. registerPreprocessor(globalBackwardCompat);
  25929. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  25930. registerLoading('default', defaultLoading); // Default actions
  25931. registerAction({
  25932. type: HIGHLIGHT_ACTION_TYPE,
  25933. event: HIGHLIGHT_ACTION_TYPE,
  25934. update: HIGHLIGHT_ACTION_TYPE
  25935. }, noop);
  25936. registerAction({
  25937. type: DOWNPLAY_ACTION_TYPE,
  25938. event: DOWNPLAY_ACTION_TYPE,
  25939. update: DOWNPLAY_ACTION_TYPE
  25940. }, noop);
  25941. registerAction({
  25942. type: SELECT_ACTION_TYPE,
  25943. event: SELECT_ACTION_TYPE,
  25944. update: SELECT_ACTION_TYPE
  25945. }, noop);
  25946. registerAction({
  25947. type: UNSELECT_ACTION_TYPE,
  25948. event: UNSELECT_ACTION_TYPE,
  25949. update: UNSELECT_ACTION_TYPE
  25950. }, noop);
  25951. registerAction({
  25952. type: TOGGLE_SELECT_ACTION_TYPE,
  25953. event: TOGGLE_SELECT_ACTION_TYPE,
  25954. update: TOGGLE_SELECT_ACTION_TYPE
  25955. }, noop); // Default theme
  25956. registerTheme('light', lightTheme);
  25957. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  25958. // be mounted on `echarts` is the extension `dataTool` is imported.
  25959. var dataTool = {};
  25960. var extensions = [];
  25961. var extensionRegisters = {
  25962. registerPreprocessor: registerPreprocessor,
  25963. registerProcessor: registerProcessor,
  25964. registerPostInit: registerPostInit,
  25965. registerPostUpdate: registerPostUpdate,
  25966. registerAction: registerAction,
  25967. registerCoordinateSystem: registerCoordinateSystem,
  25968. registerLayout: registerLayout,
  25969. registerVisual: registerVisual,
  25970. registerTransform: registerTransform,
  25971. registerLoading: registerLoading,
  25972. registerMap: registerMap,
  25973. PRIORITY: PRIORITY,
  25974. ComponentModel: ComponentModel,
  25975. ComponentView: ComponentView,
  25976. SeriesModel: SeriesModel,
  25977. ChartView: ChartView,
  25978. // TODO Use ComponentModel and SeriesModel instead of Constructor
  25979. registerComponentModel: function (ComponentModelClass) {
  25980. ComponentModel.registerClass(ComponentModelClass);
  25981. },
  25982. registerComponentView: function (ComponentViewClass) {
  25983. ComponentView.registerClass(ComponentViewClass);
  25984. },
  25985. registerSeriesModel: function (SeriesModelClass) {
  25986. SeriesModel.registerClass(SeriesModelClass);
  25987. },
  25988. registerChartView: function (ChartViewClass) {
  25989. ChartView.registerClass(ChartViewClass);
  25990. },
  25991. registerSubTypeDefaulter: function (componentType, defaulter) {
  25992. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  25993. },
  25994. registerPainter: function (painterType, PainterCtor) {
  25995. registerPainter(painterType, PainterCtor);
  25996. }
  25997. };
  25998. function use(ext) {
  25999. if (isArray(ext)) {
  26000. // use([ChartLine, ChartBar]);
  26001. each(ext, function (singleExt) {
  26002. use(singleExt);
  26003. });
  26004. return;
  26005. }
  26006. if (indexOf(extensions, ext) >= 0) {
  26007. return;
  26008. }
  26009. extensions.push(ext);
  26010. if (isFunction(ext)) {
  26011. ext = {
  26012. install: ext
  26013. };
  26014. }
  26015. ext.install(extensionRegisters);
  26016. }
  26017. /*
  26018. * Licensed to the Apache Software Foundation (ASF) under one
  26019. * or more contributor license agreements. See the NOTICE file
  26020. * distributed with this work for additional information
  26021. * regarding copyright ownership. The ASF licenses this file
  26022. * to you under the Apache License, Version 2.0 (the
  26023. * "License"); you may not use this file except in compliance
  26024. * with the License. You may obtain a copy of the License at
  26025. *
  26026. * http://www.apache.org/licenses/LICENSE-2.0
  26027. *
  26028. * Unless required by applicable law or agreed to in writing,
  26029. * software distributed under the License is distributed on an
  26030. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26031. * KIND, either express or implied. See the License for the
  26032. * specific language governing permissions and limitations
  26033. * under the License.
  26034. */
  26035. /**
  26036. * AUTO-GENERATED FILE. DO NOT MODIFY.
  26037. */
  26038. /*
  26039. * Licensed to the Apache Software Foundation (ASF) under one
  26040. * or more contributor license agreements. See the NOTICE file
  26041. * distributed with this work for additional information
  26042. * regarding copyright ownership. The ASF licenses this file
  26043. * to you under the Apache License, Version 2.0 (the
  26044. * "License"); you may not use this file except in compliance
  26045. * with the License. You may obtain a copy of the License at
  26046. *
  26047. * http://www.apache.org/licenses/LICENSE-2.0
  26048. *
  26049. * Unless required by applicable law or agreed to in writing,
  26050. * software distributed under the License is distributed on an
  26051. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26052. * KIND, either express or implied. See the License for the
  26053. * specific language governing permissions and limitations
  26054. * under the License.
  26055. */
  26056. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  26057. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  26058. }
  26059. function defaultKeyGetter(item) {
  26060. return item;
  26061. }
  26062. var DataDiffer =
  26063. /** @class */
  26064. function () {
  26065. /**
  26066. * @param context Can be visited by this.context in callback.
  26067. */
  26068. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  26069. diffMode) {
  26070. this._old = oldArr;
  26071. this._new = newArr;
  26072. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26073. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  26074. this.context = context;
  26075. this._diffModeMultiple = diffMode === 'multiple';
  26076. }
  26077. /**
  26078. * Callback function when add a data
  26079. */
  26080. DataDiffer.prototype.add = function (func) {
  26081. this._add = func;
  26082. return this;
  26083. };
  26084. /**
  26085. * Callback function when update a data
  26086. */
  26087. DataDiffer.prototype.update = function (func) {
  26088. this._update = func;
  26089. return this;
  26090. };
  26091. /**
  26092. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  26093. */
  26094. DataDiffer.prototype.updateManyToOne = function (func) {
  26095. this._updateManyToOne = func;
  26096. return this;
  26097. };
  26098. /**
  26099. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  26100. */
  26101. DataDiffer.prototype.updateOneToMany = function (func) {
  26102. this._updateOneToMany = func;
  26103. return this;
  26104. };
  26105. /**
  26106. * Callback function when remove a data
  26107. */
  26108. DataDiffer.prototype.remove = function (func) {
  26109. this._remove = func;
  26110. return this;
  26111. };
  26112. DataDiffer.prototype.execute = function () {
  26113. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  26114. };
  26115. DataDiffer.prototype._executeOneToOne = function () {
  26116. var oldArr = this._old;
  26117. var newArr = this._new;
  26118. var newDataIndexMap = {};
  26119. var oldDataKeyArr = new Array(oldArr.length);
  26120. var newDataKeyArr = new Array(newArr.length);
  26121. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  26122. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  26123. for (var i = 0; i < oldArr.length; i++) {
  26124. var oldKey = oldDataKeyArr[i];
  26125. var newIdxMapVal = newDataIndexMap[oldKey];
  26126. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  26127. if (newIdxMapValLen > 1) {
  26128. // Consider there is duplicate key (for example, use dataItem.name as key).
  26129. // We should make sure every item in newArr and oldArr can be visited.
  26130. var newIdx = newIdxMapVal.shift();
  26131. if (newIdxMapVal.length === 1) {
  26132. newDataIndexMap[oldKey] = newIdxMapVal[0];
  26133. }
  26134. this._update && this._update(newIdx, i);
  26135. } else if (newIdxMapValLen === 1) {
  26136. newDataIndexMap[oldKey] = null;
  26137. this._update && this._update(newIdxMapVal, i);
  26138. } else {
  26139. this._remove && this._remove(i);
  26140. }
  26141. }
  26142. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  26143. };
  26144. /**
  26145. * For example, consider the case:
  26146. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  26147. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  26148. * Where:
  26149. * o0, o1, n0 has key 'a' (many to one)
  26150. * o5, n4, n5, n6 has key 'b' (one to many)
  26151. * o2, n1 has key 'c' (one to one)
  26152. * n2, n3 has key 'd' (add)
  26153. * o3, o4 has key 'e' (remove)
  26154. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  26155. * Then:
  26156. * (The order of the following directives are not ensured.)
  26157. * this._updateManyToOne(n0, [o0, o1]);
  26158. * this._updateOneToMany([n4, n5, n6], o5);
  26159. * this._update(n1, o2);
  26160. * this._remove(o3);
  26161. * this._remove(o4);
  26162. * this._remove(o6);
  26163. * this._remove(o7);
  26164. * this._add(n2);
  26165. * this._add(n3);
  26166. * this._add(n7);
  26167. * this._add(n8);
  26168. */
  26169. DataDiffer.prototype._executeMultiple = function () {
  26170. var oldArr = this._old;
  26171. var newArr = this._new;
  26172. var oldDataIndexMap = {};
  26173. var newDataIndexMap = {};
  26174. var oldDataKeyArr = [];
  26175. var newDataKeyArr = [];
  26176. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  26177. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  26178. for (var i = 0; i < oldDataKeyArr.length; i++) {
  26179. var oldKey = oldDataKeyArr[i];
  26180. var oldIdxMapVal = oldDataIndexMap[oldKey];
  26181. var newIdxMapVal = newDataIndexMap[oldKey];
  26182. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  26183. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  26184. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  26185. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  26186. newDataIndexMap[oldKey] = null;
  26187. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  26188. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  26189. newDataIndexMap[oldKey] = null;
  26190. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  26191. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  26192. newDataIndexMap[oldKey] = null;
  26193. } else if (oldIdxMapValLen > 1) {
  26194. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  26195. this._remove && this._remove(oldIdxMapVal[i_1]);
  26196. }
  26197. } else {
  26198. this._remove && this._remove(oldIdxMapVal);
  26199. }
  26200. }
  26201. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  26202. };
  26203. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  26204. for (var i = 0; i < newDataKeyArr.length; i++) {
  26205. var newKey = newDataKeyArr[i];
  26206. var newIdxMapVal = newDataIndexMap[newKey];
  26207. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  26208. if (idxMapValLen > 1) {
  26209. for (var j = 0; j < idxMapValLen; j++) {
  26210. this._add && this._add(newIdxMapVal[j]);
  26211. }
  26212. } else if (idxMapValLen === 1) {
  26213. this._add && this._add(newIdxMapVal);
  26214. } // Support both `newDataKeyArr` are duplication removed or not removed.
  26215. newDataIndexMap[newKey] = null;
  26216. }
  26217. };
  26218. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  26219. map, // In 'byKey', the output `keyArr` is duplication removed.
  26220. // In 'byIndex', the output `keyArr` is not duplication removed and
  26221. // its indices are accurately corresponding to `arr`.
  26222. keyArr, keyGetterName) {
  26223. var cbModeMultiple = this._diffModeMultiple;
  26224. for (var i = 0; i < arr.length; i++) {
  26225. // Add prefix to avoid conflict with Object.prototype.
  26226. var key = '_ec_' + this[keyGetterName](arr[i], i);
  26227. if (!cbModeMultiple) {
  26228. keyArr[i] = key;
  26229. }
  26230. if (!map) {
  26231. continue;
  26232. }
  26233. var idxMapVal = map[key];
  26234. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  26235. if (idxMapValLen === 0) {
  26236. // Simple optimize: in most cases, one index has one key,
  26237. // do not need array.
  26238. map[key] = i;
  26239. if (cbModeMultiple) {
  26240. keyArr.push(key);
  26241. }
  26242. } else if (idxMapValLen === 1) {
  26243. map[key] = [idxMapVal, i];
  26244. } else {
  26245. idxMapVal.push(i);
  26246. }
  26247. }
  26248. };
  26249. return DataDiffer;
  26250. }();
  26251. function summarizeDimensions(data) {
  26252. var summary = {};
  26253. var encode = summary.encode = {};
  26254. var notExtraCoordDimMap = createHashMap();
  26255. var defaultedLabel = [];
  26256. var defaultedTooltip = []; // See the comment of `List.js#userOutput`.
  26257. var userOutput = summary.userOutput = {
  26258. dimensionNames: data.dimensions.slice(),
  26259. encode: {}
  26260. };
  26261. each(data.dimensions, function (dimName) {
  26262. var dimItem = data.getDimensionInfo(dimName);
  26263. var coordDim = dimItem.coordDim;
  26264. if (coordDim) {
  26265. if ("development" !== 'production') {
  26266. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  26267. }
  26268. var coordDimIndex = dimItem.coordDimIndex;
  26269. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26270. if (!dimItem.isExtraCoord) {
  26271. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  26272. // because when dataset is used, it is hard to guess which dimension
  26273. // can be value dimension. If both show x, y on label is not look good,
  26274. // and conventionally y axis is focused more.
  26275. if (mayLabelDimType(dimItem.type)) {
  26276. defaultedLabel[0] = dimName;
  26277. } // User output encode do not contain generated coords.
  26278. // And it only has index. User can use index to retrieve value from the raw item array.
  26279. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26280. }
  26281. if (dimItem.defaultTooltip) {
  26282. defaultedTooltip.push(dimName);
  26283. }
  26284. }
  26285. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  26286. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26287. var dimIndex = dimItem.otherDims[otherDim];
  26288. if (dimIndex != null && dimIndex !== false) {
  26289. encodeArr[dimIndex] = dimItem.name;
  26290. }
  26291. });
  26292. });
  26293. var dataDimsOnCoord = [];
  26294. var encodeFirstDimNotExtra = {};
  26295. notExtraCoordDimMap.each(function (v, coordDim) {
  26296. var dimArr = encode[coordDim];
  26297. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  26298. // dim canot on more than one coordDim.
  26299. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26300. });
  26301. summary.dataDimsOnCoord = dataDimsOnCoord;
  26302. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26303. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  26304. // in this way. Use label.formatter instead. May be remove this approach someday.
  26305. if (encodeLabel && encodeLabel.length) {
  26306. defaultedLabel = encodeLabel.slice();
  26307. }
  26308. var encodeTooltip = encode.tooltip;
  26309. if (encodeTooltip && encodeTooltip.length) {
  26310. defaultedTooltip = encodeTooltip.slice();
  26311. } else if (!defaultedTooltip.length) {
  26312. defaultedTooltip = defaultedLabel.slice();
  26313. }
  26314. encode.defaultedLabel = defaultedLabel;
  26315. encode.defaultedTooltip = defaultedTooltip;
  26316. return summary;
  26317. }
  26318. function getOrCreateEncodeArr(encode, dim) {
  26319. if (!encode.hasOwnProperty(dim)) {
  26320. encode[dim] = [];
  26321. }
  26322. return encode[dim];
  26323. } // FIXME:TS should be type `AxisType`
  26324. function getDimensionTypeByAxis(axisType) {
  26325. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  26326. }
  26327. function mayLabelDimType(dimType) {
  26328. // In most cases, ordinal and time do not suitable for label.
  26329. // Ordinal info can be displayed on axis. Time is too long.
  26330. return !(dimType === 'ordinal' || dimType === 'time');
  26331. } // function findTheLastDimMayLabel(data) {
  26332. // // Get last value dim
  26333. // let dimensions = data.dimensions.slice();
  26334. // let valueType;
  26335. // let valueDim;
  26336. // while (dimensions.length && (
  26337. // valueDim = dimensions.pop(),
  26338. // valueType = data.getDimensionInfo(valueDim).type,
  26339. // valueType === 'ordinal' || valueType === 'time'
  26340. // )) {} // jshint ignore:line
  26341. // return valueDim;
  26342. // }
  26343. var DataDimensionInfo =
  26344. /** @class */
  26345. function () {
  26346. /**
  26347. * @param opt All of the fields will be shallow copied.
  26348. */
  26349. function DataDimensionInfo(opt) {
  26350. /**
  26351. * The format of `otherDims` is:
  26352. * ```js
  26353. * {
  26354. * tooltip: number optional,
  26355. * label: number optional,
  26356. * itemName: number optional,
  26357. * seriesName: number optional,
  26358. * }
  26359. * ```
  26360. *
  26361. * A `series.encode` can specified these fields:
  26362. * ```js
  26363. * encode: {
  26364. * // "3, 1, 5" is the index of data dimension.
  26365. * tooltip: [3, 1, 5],
  26366. * label: [0, 3],
  26367. * ...
  26368. * }
  26369. * ```
  26370. * `otherDims` is the parse result of the `series.encode` above, like:
  26371. * ```js
  26372. * // Suppose the index of this data dimension is `3`.
  26373. * this.otherDims = {
  26374. * // `3` is at the index `0` of the `encode.tooltip`
  26375. * tooltip: 0,
  26376. * // `3` is at the index `1` of the `encode.tooltip`
  26377. * label: 1
  26378. * };
  26379. * ```
  26380. *
  26381. * This prop should never be `null`/`undefined` after initialized.
  26382. */
  26383. this.otherDims = {};
  26384. if (opt != null) {
  26385. extend(this, opt);
  26386. }
  26387. }
  26388. return DataDimensionInfo;
  26389. }();
  26390. var mathFloor = Math.floor;
  26391. var isObject$3 = isObject;
  26392. var map$1 = map;
  26393. var UNDEFINED = 'undefined';
  26394. var INDEX_NOT_FOUND = -1; // Use prefix to avoid index to be the same as otherIdList[idx],
  26395. // which will cause weird udpate animation.
  26396. var ID_PREFIX = 'e\0\0';
  26397. var dataCtors = {
  26398. 'float': typeof Float64Array === UNDEFINED ? Array : Float64Array,
  26399. 'int': typeof Int32Array === UNDEFINED ? Array : Int32Array,
  26400. // Ordinal data type can be string or int
  26401. 'ordinal': Array,
  26402. 'number': Array,
  26403. 'time': Array
  26404. }; // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26405. // different from the Ctor of typed array.
  26406. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26407. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26408. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26409. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_rawData', '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  26410. var CLONE_PROPERTIES = ['_extent', '_approximateExtent', '_rawExtent']; // -----------------------------
  26411. // Internal method declarations:
  26412. // -----------------------------
  26413. var defaultDimValueGetters;
  26414. var prepareInvertedIndex;
  26415. var getIndicesCtor;
  26416. var prepareStorage;
  26417. var getRawIndexWithoutIndices;
  26418. var getRawIndexWithIndices;
  26419. var getId;
  26420. var getIdNameFromStore;
  26421. var makeIdFromName;
  26422. var normalizeDimensions;
  26423. var validateDimensions;
  26424. var cloneListForMapAndSample;
  26425. var getInitialExtent;
  26426. var setItemDataAndSeriesIndex;
  26427. var transferProperties;
  26428. var List =
  26429. /** @class */
  26430. function () {
  26431. /**
  26432. * @param dimensions
  26433. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26434. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26435. */
  26436. function List(dimensions, hostModel) {
  26437. this.type = 'list';
  26438. this._count = 0;
  26439. this._rawCount = 0;
  26440. this._storage = {}; // We have an extra array store here. It's faster to be acessed than KV structured `_storage`.
  26441. // We profile the code `storage[dim]` and it seems to be KeyedLoadIC_Megamorphic instead of fast property access.
  26442. // Not sure why this happens. But using an extra array seems leads to faster `initData`
  26443. // See https://github.com/apache/incubator-echarts/pull/13314 for more explanation.
  26444. this._storageArr = [];
  26445. this._nameList = [];
  26446. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  26447. // Never used yet (not used yet).
  26448. // private _optionModels: Model[] = [];
  26449. // Global visual properties after visual coding
  26450. this._visual = {}; // Globel layout properties.
  26451. this._layout = {}; // Item visual properties after visual coding
  26452. this._itemVisuals = []; // Item layout properties after layout
  26453. this._itemLayouts = []; // Graphic elemnents
  26454. this._graphicEls = []; // Raw extent will not be cloned, but only transfered.
  26455. // It will not be calculated util needed.
  26456. this._rawExtent = {};
  26457. this._extent = {}; // key: dim, value: extent
  26458. this._approximateExtent = {};
  26459. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  26460. // (in type `OptionDataItemObject`).
  26461. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  26462. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  26463. this.hasItemOption = true; // Methods that create a new list based on this list should be listed here.
  26464. // Notice that those method should `RETURN` the new list.
  26465. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  26466. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  26467. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  26468. /**
  26469. * Get raw data index.
  26470. * Do not initialize.
  26471. * Default `getRawIndex`. And it can be changed.
  26472. */
  26473. this.getRawIndex = getRawIndexWithoutIndices;
  26474. dimensions = dimensions || ['x', 'y'];
  26475. var dimensionInfos = {};
  26476. var dimensionNames = [];
  26477. var invertedIndicesMap = {};
  26478. for (var i = 0; i < dimensions.length; i++) {
  26479. // Use the original dimensions[i], where other flag props may exists.
  26480. var dimInfoInput = dimensions[i];
  26481. var dimensionInfo = isString(dimInfoInput) ? new DataDimensionInfo({
  26482. name: dimInfoInput
  26483. }) : !(dimInfoInput instanceof DataDimensionInfo) ? new DataDimensionInfo(dimInfoInput) : dimInfoInput;
  26484. var dimensionName = dimensionInfo.name;
  26485. dimensionInfo.type = dimensionInfo.type || 'float';
  26486. if (!dimensionInfo.coordDim) {
  26487. dimensionInfo.coordDim = dimensionName;
  26488. dimensionInfo.coordDimIndex = 0;
  26489. }
  26490. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26491. dimensionNames.push(dimensionName);
  26492. dimensionInfos[dimensionName] = dimensionInfo;
  26493. dimensionInfo.index = i;
  26494. if (dimensionInfo.createInvertedIndices) {
  26495. invertedIndicesMap[dimensionName] = [];
  26496. }
  26497. if (otherDims.itemName === 0) {
  26498. this._nameDimIdx = i;
  26499. this._nameOrdinalMeta = dimensionInfo.ordinalMeta;
  26500. }
  26501. if (otherDims.itemId === 0) {
  26502. this._idDimIdx = i;
  26503. this._idOrdinalMeta = dimensionInfo.ordinalMeta;
  26504. }
  26505. }
  26506. this.dimensions = dimensionNames;
  26507. this._dimensionInfos = dimensionInfos;
  26508. this.hostModel = hostModel; // Cache summary info for fast visit. See "dimensionHelper".
  26509. this._dimensionsSummary = summarizeDimensions(this);
  26510. this._invertedIndicesMap = invertedIndicesMap;
  26511. this.userOutput = this._dimensionsSummary.userOutput;
  26512. }
  26513. /**
  26514. * The meanings of the input parameter `dim`:
  26515. *
  26516. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26517. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26518. * + If dim is a number-like string (e.g., `"1"`):
  26519. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26520. * + If not, it will be converted to a number, which means the index of the dimension.
  26521. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26522. * dimension setting, although now it seems that it is not a good idea.)
  26523. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26524. * if no dimension name is defined as `"1"`.
  26525. * + If dim is a not-number-like string, it means the concrete dim name.
  26526. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26527. * or customized in `dimensions` property of option like `"age"`.
  26528. *
  26529. * Get dimension name
  26530. * @param dim See above.
  26531. * @return Concrete dim name.
  26532. */
  26533. List.prototype.getDimension = function (dim) {
  26534. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  26535. || !isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim)) {
  26536. dim = this.dimensions[dim];
  26537. }
  26538. return dim;
  26539. };
  26540. /**
  26541. * Get type and calculation info of particular dimension
  26542. * @param dim
  26543. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26544. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26545. */
  26546. List.prototype.getDimensionInfo = function (dim) {
  26547. // Do not clone, because there may be categories in dimInfo.
  26548. return this._dimensionInfos[this.getDimension(dim)];
  26549. };
  26550. /**
  26551. * concrete dimension name list on coord.
  26552. */
  26553. List.prototype.getDimensionsOnCoord = function () {
  26554. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26555. };
  26556. List.prototype.mapDimension = function (coordDim, idx) {
  26557. var dimensionsSummary = this._dimensionsSummary;
  26558. if (idx == null) {
  26559. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26560. }
  26561. var dims = dimensionsSummary.encode[coordDim];
  26562. return dims ? dims[idx] : null;
  26563. };
  26564. List.prototype.mapDimensionsAll = function (coordDim) {
  26565. var dimensionsSummary = this._dimensionsSummary;
  26566. var dims = dimensionsSummary.encode[coordDim];
  26567. return (dims || []).slice();
  26568. };
  26569. /**
  26570. * Initialize from data
  26571. * @param data source or data or data provider.
  26572. * @param nameList The name of a datum is used on data diff and
  26573. * default label/tooltip.
  26574. * A name can be specified in encode.itemName,
  26575. * or dataItem.name (only for series option data),
  26576. * or provided in nameList from outside.
  26577. */
  26578. List.prototype.initData = function (data, nameList, dimValueGetter) {
  26579. var notProvider = isSourceInstance(data) || isArrayLike(data);
  26580. var provider = notProvider ? new DefaultDataProvider(data, this.dimensions.length) : data;
  26581. if ("development" !== 'production') {
  26582. assert(notProvider || isFunction(provider.getItem) && isFunction(provider.count), 'Inavlid data provider.');
  26583. }
  26584. this._rawData = provider;
  26585. var sourceFormat = provider.getSource().sourceFormat; // Clear
  26586. this._storage = {};
  26587. this._indices = null;
  26588. this._dontMakeIdFromName = this._idDimIdx != null || sourceFormat === SOURCE_FORMAT_TYPED_ARRAY // Cosndier performance.
  26589. || !!provider.fillStorage;
  26590. this._nameList = (nameList || []).slice();
  26591. this._idList = [];
  26592. this._nameRepeatCount = {};
  26593. if (!dimValueGetter) {
  26594. this.hasItemOption = false;
  26595. }
  26596. this.defaultDimValueGetter = defaultDimValueGetters[sourceFormat]; // Default dim value getter
  26597. this._dimValueGetter = dimValueGetter = dimValueGetter || this.defaultDimValueGetter;
  26598. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows; // Reset raw extent.
  26599. this._rawExtent = {};
  26600. this._initDataFromProvider(0, provider.count()); // If data has no item option.
  26601. if (provider.pure) {
  26602. this.hasItemOption = false;
  26603. }
  26604. };
  26605. List.prototype.getProvider = function () {
  26606. return this._rawData;
  26607. };
  26608. /**
  26609. * Caution: Can be only called on raw data (before `this._indices` created).
  26610. */
  26611. List.prototype.appendData = function (data) {
  26612. if ("development" !== 'production') {
  26613. assert(!this._indices, 'appendData can only be called on raw data.');
  26614. }
  26615. var rawData = this._rawData;
  26616. var start = this.count();
  26617. rawData.appendData(data);
  26618. var end = rawData.count();
  26619. if (!rawData.persistent) {
  26620. end += start;
  26621. }
  26622. this._initDataFromProvider(start, end, true);
  26623. };
  26624. /**
  26625. * Caution: Can be only called on raw data (before `this._indices` created).
  26626. * This method does not modify `rawData` (`dataProvider`), but only
  26627. * add values to storage.
  26628. *
  26629. * The final count will be increased by `Math.max(values.length, names.length)`.
  26630. *
  26631. * @param values That is the SourceType: 'arrayRows', like
  26632. * [
  26633. * [12, 33, 44],
  26634. * [NaN, 43, 1],
  26635. * ['-', 'asdf', 0]
  26636. * ]
  26637. * Each item is exaclty cooresponding to a dimension.
  26638. */
  26639. List.prototype.appendValues = function (values, names) {
  26640. var storage = this._storage;
  26641. var dimensions = this.dimensions;
  26642. var dimLen = dimensions.length;
  26643. var rawExtent = this._rawExtent;
  26644. var start = this.count();
  26645. var end = start + Math.max(values.length, names ? names.length : 0);
  26646. for (var i = 0; i < dimLen; i++) {
  26647. var dim = dimensions[i];
  26648. if (!rawExtent[dim]) {
  26649. rawExtent[dim] = getInitialExtent();
  26650. }
  26651. prepareStorage(storage, this._dimensionInfos[dim], end, true);
  26652. }
  26653. var rawExtentArr = map$1(dimensions, function (dim) {
  26654. return rawExtent[dim];
  26655. });
  26656. var storageArr = this._storageArr = map$1(dimensions, function (dim) {
  26657. return storage[dim];
  26658. });
  26659. var emptyDataItem = [];
  26660. for (var idx = start; idx < end; idx++) {
  26661. var sourceIdx = idx - start; // Store the data by dimensions
  26662. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  26663. var dim = dimensions[dimIdx];
  26664. var val = this._dimValueGetterArrayRows(values[sourceIdx] || emptyDataItem, dim, sourceIdx, dimIdx);
  26665. storageArr[dimIdx][idx] = val;
  26666. var dimRawExtent = rawExtentArr[dimIdx];
  26667. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26668. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26669. }
  26670. if (names) {
  26671. this._nameList[idx] = names[sourceIdx];
  26672. if (!this._dontMakeIdFromName) {
  26673. makeIdFromName(this, idx);
  26674. }
  26675. }
  26676. }
  26677. this._rawCount = this._count = end; // Reset data extent
  26678. this._extent = {};
  26679. prepareInvertedIndex(this);
  26680. };
  26681. List.prototype._initDataFromProvider = function (start, end, append) {
  26682. if (start >= end) {
  26683. return;
  26684. }
  26685. var rawData = this._rawData;
  26686. var storage = this._storage;
  26687. var dimensions = this.dimensions;
  26688. var dimLen = dimensions.length;
  26689. var dimensionInfoMap = this._dimensionInfos;
  26690. var nameList = this._nameList;
  26691. var idList = this._idList;
  26692. var rawExtent = this._rawExtent;
  26693. var sourceFormat = rawData.getSource().sourceFormat;
  26694. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL;
  26695. for (var i = 0; i < dimLen; i++) {
  26696. var dim = dimensions[i];
  26697. if (!rawExtent[dim]) {
  26698. rawExtent[dim] = getInitialExtent();
  26699. }
  26700. prepareStorage(storage, dimensionInfoMap[dim], end, append);
  26701. }
  26702. var storageArr = this._storageArr = map$1(dimensions, function (dim) {
  26703. return storage[dim];
  26704. });
  26705. var rawExtentArr = map$1(dimensions, function (dim) {
  26706. return rawExtent[dim];
  26707. });
  26708. if (rawData.fillStorage) {
  26709. rawData.fillStorage(start, end, storageArr, rawExtentArr);
  26710. } else {
  26711. var dataItem = [];
  26712. for (var idx = start; idx < end; idx++) {
  26713. // NOTICE: Try not to write things into dataItem
  26714. dataItem = rawData.getItem(idx, dataItem); // Each data item is value
  26715. // [1, 2]
  26716. // 2
  26717. // Bar chart, line chart which uses category axis
  26718. // only gives the 'y' value. 'x' value is the indices of category
  26719. // Use a tempValue to normalize the value to be a (x, y) value
  26720. // Store the data by dimensions
  26721. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  26722. var dim = dimensions[dimIdx];
  26723. var dimStorage = storageArr[dimIdx]; // PENDING NULL is empty or zero
  26724. var val = this._dimValueGetter(dataItem, dim, idx, dimIdx);
  26725. dimStorage[idx] = val;
  26726. var dimRawExtent = rawExtentArr[dimIdx];
  26727. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26728. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26729. } // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  26730. // This kind of ids and names are always stored `_nameList` and `_idList`.
  26731. if (isFormatOriginal && !rawData.pure && dataItem) {
  26732. var itemName = dataItem.name;
  26733. if (nameList[idx] == null && itemName != null) {
  26734. nameList[idx] = convertOptionIdName(itemName, null);
  26735. }
  26736. var itemId = dataItem.id;
  26737. if (idList[idx] == null && itemId != null) {
  26738. idList[idx] = convertOptionIdName(itemId, null);
  26739. }
  26740. }
  26741. if (!this._dontMakeIdFromName) {
  26742. makeIdFromName(this, idx);
  26743. }
  26744. }
  26745. }
  26746. if (!rawData.persistent && rawData.clean) {
  26747. // Clean unused data if data source is typed array.
  26748. rawData.clean();
  26749. }
  26750. this._rawCount = this._count = end; // Reset data extent
  26751. this._extent = {};
  26752. prepareInvertedIndex(this);
  26753. };
  26754. List.prototype.count = function () {
  26755. return this._count;
  26756. };
  26757. List.prototype.getIndices = function () {
  26758. var newIndices;
  26759. var indices = this._indices;
  26760. if (indices) {
  26761. var Ctor = indices.constructor;
  26762. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  26763. if (Ctor === Array) {
  26764. newIndices = new Ctor(thisCount);
  26765. for (var i = 0; i < thisCount; i++) {
  26766. newIndices[i] = indices[i];
  26767. }
  26768. } else {
  26769. newIndices = new Ctor(indices.buffer, 0, thisCount);
  26770. }
  26771. } else {
  26772. var Ctor = getIndicesCtor(this);
  26773. newIndices = new Ctor(this.count());
  26774. for (var i = 0; i < newIndices.length; i++) {
  26775. newIndices[i] = i;
  26776. }
  26777. }
  26778. return newIndices;
  26779. }; // Get data by index of dimension.
  26780. // Because in v8 access array by number variable is faster than access object by string variable
  26781. // Not sure why but the optimization just works.
  26782. List.prototype.getByDimIdx = function (dimIdx, idx) {
  26783. if (!(idx >= 0 && idx < this._count)) {
  26784. return NaN;
  26785. }
  26786. var dimStore = this._storageArr[dimIdx];
  26787. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  26788. };
  26789. /**
  26790. * Get value. Return NaN if idx is out of range.
  26791. * @param dim Dim must be concrete name.
  26792. */
  26793. List.prototype.get = function (dim, idx) {
  26794. if (!(idx >= 0 && idx < this._count)) {
  26795. return NaN;
  26796. }
  26797. var dimStore = this._storage[dim];
  26798. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  26799. };
  26800. /**
  26801. * @param dim concrete dim
  26802. */
  26803. List.prototype.getByRawIndex = function (dim, rawIdx) {
  26804. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  26805. return NaN;
  26806. }
  26807. var dimStore = this._storage[dim];
  26808. return dimStore ? dimStore[rawIdx] : NaN;
  26809. };
  26810. List.prototype.getValues = function (dimensions, idx) {
  26811. var values = [];
  26812. if (!isArray(dimensions)) {
  26813. // stack = idx;
  26814. idx = dimensions;
  26815. dimensions = this.dimensions;
  26816. }
  26817. for (var i = 0, len = dimensions.length; i < len; i++) {
  26818. values.push(this.get(dimensions[i], idx
  26819. /*, stack */
  26820. ));
  26821. }
  26822. return values;
  26823. };
  26824. /**
  26825. * If value is NaN. Inlcuding '-'
  26826. * Only check the coord dimensions.
  26827. */
  26828. List.prototype.hasValue = function (idx) {
  26829. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  26830. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  26831. // Ordinal type originally can be string or number.
  26832. // But when an ordinal type is used on coord, it can
  26833. // not be string but only number. So we can also use isNaN.
  26834. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  26835. return false;
  26836. }
  26837. }
  26838. return true;
  26839. };
  26840. /**
  26841. * Get extent of data in one dimension
  26842. */
  26843. List.prototype.getDataExtent = function (dim) {
  26844. // Make sure use concrete dim as cache name.
  26845. dim = this.getDimension(dim);
  26846. var dimData = this._storage[dim];
  26847. var initialExtent = getInitialExtent(); // stack = !!((stack || false) && this.getCalculationInfo(dim));
  26848. if (!dimData) {
  26849. return initialExtent;
  26850. } // Make more strict checkings to ensure hitting cache.
  26851. var currEnd = this.count(); // let cacheName = [dim, !!stack].join('_');
  26852. // let cacheName = dim;
  26853. // Consider the most cases when using data zoom, `getDataExtent`
  26854. // happened before filtering. We cache raw extent, which is not
  26855. // necessary to be cleared and recalculated when restore data.
  26856. var useRaw = !this._indices; // && !stack;
  26857. var dimExtent;
  26858. if (useRaw) {
  26859. return this._rawExtent[dim].slice();
  26860. }
  26861. dimExtent = this._extent[dim];
  26862. if (dimExtent) {
  26863. return dimExtent.slice();
  26864. }
  26865. dimExtent = initialExtent;
  26866. var min = dimExtent[0];
  26867. var max = dimExtent[1];
  26868. for (var i = 0; i < currEnd; i++) {
  26869. var rawIdx = this.getRawIndex(i);
  26870. var value = dimData[rawIdx];
  26871. value < min && (min = value);
  26872. value > max && (max = value);
  26873. }
  26874. dimExtent = [min, max];
  26875. this._extent[dim] = dimExtent;
  26876. return dimExtent;
  26877. };
  26878. /**
  26879. * PENDING: In fact currently this function is only used to short-circuit
  26880. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  26881. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  26882. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  26883. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  26884. * But if we add "custom data filter" in future, which is not "axis related", this method may
  26885. * be still needed.
  26886. *
  26887. * Optimize for the scenario that data is filtered by a given extent.
  26888. * Consider that if data amount is more than hundreds of thousand,
  26889. * extent calculation will cost more than 10ms and the cache will
  26890. * be erased because of the filtering.
  26891. */
  26892. List.prototype.getApproximateExtent = function (dim) {
  26893. dim = this.getDimension(dim);
  26894. return this._approximateExtent[dim] || this.getDataExtent(dim);
  26895. };
  26896. /**
  26897. * Calculate extent on a filtered data might be time consuming.
  26898. * Approximate extent is only used for: calculte extent of filtered data outside.
  26899. */
  26900. List.prototype.setApproximateExtent = function (extent, dim) {
  26901. dim = this.getDimension(dim);
  26902. this._approximateExtent[dim] = extent.slice();
  26903. };
  26904. List.prototype.getCalculationInfo = function (key) {
  26905. return this._calculationInfo[key];
  26906. };
  26907. List.prototype.setCalculationInfo = function (key, value) {
  26908. isObject$3(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  26909. };
  26910. /**
  26911. * Get sum of data in one dimension
  26912. */
  26913. List.prototype.getSum = function (dim) {
  26914. var dimData = this._storage[dim];
  26915. var sum = 0;
  26916. if (dimData) {
  26917. for (var i = 0, len = this.count(); i < len; i++) {
  26918. var value = this.get(dim, i);
  26919. if (!isNaN(value)) {
  26920. sum += value;
  26921. }
  26922. }
  26923. }
  26924. return sum;
  26925. };
  26926. /**
  26927. * Get median of data in one dimension
  26928. */
  26929. List.prototype.getMedian = function (dim) {
  26930. var dimDataArray = []; // map all data of one dimension
  26931. this.each(dim, function (val) {
  26932. if (!isNaN(val)) {
  26933. dimDataArray.push(val);
  26934. }
  26935. }); // TODO
  26936. // Use quick select?
  26937. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  26938. return a - b;
  26939. });
  26940. var len = this.count(); // calculate median
  26941. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26942. }; // /**
  26943. // * Retreive the index with given value
  26944. // * @param {string} dim Concrete dimension.
  26945. // * @param {number} value
  26946. // * @return {number}
  26947. // */
  26948. // Currently incorrect: should return dataIndex but not rawIndex.
  26949. // Do not fix it until this method is to be used somewhere.
  26950. // FIXME Precision of float value
  26951. // indexOf(dim, value) {
  26952. // let storage = this._storage;
  26953. // let dimData = storage[dim];
  26954. // let chunkSize = this._chunkSize;
  26955. // if (dimData) {
  26956. // for (let i = 0, len = this.count(); i < len; i++) {
  26957. // let chunkIndex = mathFloor(i / chunkSize);
  26958. // let chunkOffset = i % chunkSize;
  26959. // if (dimData[chunkIndex][chunkOffset] === value) {
  26960. // return i;
  26961. // }
  26962. // }
  26963. // }
  26964. // return -1;
  26965. // }
  26966. /**
  26967. * Only support the dimension which inverted index created.
  26968. * Do not support other cases until required.
  26969. * @param dim concrete dim
  26970. * @param value ordinal index
  26971. * @return rawIndex
  26972. */
  26973. List.prototype.rawIndexOf = function (dim, value) {
  26974. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26975. if ("development" !== 'production') {
  26976. if (!invertedIndices) {
  26977. throw new Error('Do not supported yet');
  26978. }
  26979. }
  26980. var rawIndex = invertedIndices[value];
  26981. if (rawIndex == null || isNaN(rawIndex)) {
  26982. return INDEX_NOT_FOUND;
  26983. }
  26984. return rawIndex;
  26985. };
  26986. /**
  26987. * Retreive the index with given name
  26988. */
  26989. List.prototype.indexOfName = function (name) {
  26990. for (var i = 0, len = this.count(); i < len; i++) {
  26991. if (this.getName(i) === name) {
  26992. return i;
  26993. }
  26994. }
  26995. return -1;
  26996. };
  26997. /**
  26998. * Retreive the index with given raw data index
  26999. */
  27000. List.prototype.indexOfRawIndex = function (rawIndex) {
  27001. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27002. return -1;
  27003. }
  27004. if (!this._indices) {
  27005. return rawIndex;
  27006. } // Indices are ascending
  27007. var indices = this._indices; // If rawIndex === dataIndex
  27008. var rawDataIndex = indices[rawIndex];
  27009. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27010. return rawIndex;
  27011. }
  27012. var left = 0;
  27013. var right = this._count - 1;
  27014. while (left <= right) {
  27015. var mid = (left + right) / 2 | 0;
  27016. if (indices[mid] < rawIndex) {
  27017. left = mid + 1;
  27018. } else if (indices[mid] > rawIndex) {
  27019. right = mid - 1;
  27020. } else {
  27021. return mid;
  27022. }
  27023. }
  27024. return -1;
  27025. };
  27026. /**
  27027. * Retreive the index of nearest value
  27028. * @param dim
  27029. * @param value
  27030. * @param [maxDistance=Infinity]
  27031. * @return If and only if multiple indices has
  27032. * the same value, they are put to the result.
  27033. */
  27034. List.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  27035. var storage = this._storage;
  27036. var dimData = storage[dim];
  27037. var nearestIndices = [];
  27038. if (!dimData) {
  27039. return nearestIndices;
  27040. }
  27041. if (maxDistance == null) {
  27042. maxDistance = Infinity;
  27043. }
  27044. var minDist = Infinity;
  27045. var minDiff = -1;
  27046. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/List.js`.
  27047. for (var i = 0, len = this.count(); i < len; i++) {
  27048. var dataIndex = this.getRawIndex(i);
  27049. var diff = value - dimData[dataIndex];
  27050. var dist = Math.abs(diff);
  27051. if (dist <= maxDistance) {
  27052. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27053. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27054. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27055. // So we chose the one that `diff >= 0` in this csae.
  27056. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27057. // should be push to `nearestIndices`.
  27058. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  27059. minDist = dist;
  27060. minDiff = diff;
  27061. nearestIndicesLen = 0;
  27062. }
  27063. if (diff === minDiff) {
  27064. nearestIndices[nearestIndicesLen++] = i;
  27065. }
  27066. }
  27067. }
  27068. nearestIndices.length = nearestIndicesLen;
  27069. return nearestIndices;
  27070. };
  27071. /**
  27072. * Get raw data item
  27073. */
  27074. List.prototype.getRawDataItem = function (idx) {
  27075. if (!this._rawData.persistent) {
  27076. var val = [];
  27077. for (var i = 0; i < this.dimensions.length; i++) {
  27078. var dim = this.dimensions[i];
  27079. val.push(this.get(dim, idx));
  27080. }
  27081. return val;
  27082. } else {
  27083. return this._rawData.getItem(this.getRawIndex(idx));
  27084. }
  27085. };
  27086. /**
  27087. * @return Never be null/undefined. `number` will be converted to string. Becuase:
  27088. * In most cases, name is used in display, where returning a string is more convenient.
  27089. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  27090. * rule that name `2` equals to name `'2'`.
  27091. */
  27092. List.prototype.getName = function (idx) {
  27093. var rawIndex = this.getRawIndex(idx);
  27094. var name = this._nameList[rawIndex];
  27095. if (name == null && this._nameDimIdx != null) {
  27096. name = getIdNameFromStore(this, this._nameDimIdx, this._nameOrdinalMeta, rawIndex);
  27097. }
  27098. if (name == null) {
  27099. name = '';
  27100. }
  27101. return name;
  27102. };
  27103. /**
  27104. * @return Never null/undefined. `number` will be converted to string. Becuase:
  27105. * In all cases having encountered at present, id is used in making diff comparison, which
  27106. * are usually based on hash map. We can keep the rule that the internal id are always string
  27107. * (treat `2` is the same as `'2'`) to make the related logic simple.
  27108. */
  27109. List.prototype.getId = function (idx) {
  27110. return getId(this, this.getRawIndex(idx));
  27111. };
  27112. List.prototype.each = function (dims, cb, ctx, ctxCompat) {
  27113. var _this = this;
  27114. if (!this._count) {
  27115. return;
  27116. }
  27117. if (typeof dims === 'function') {
  27118. ctxCompat = ctx;
  27119. ctx = cb;
  27120. cb = dims;
  27121. dims = [];
  27122. } // ctxCompat just for compat echarts3
  27123. var fCtx = ctx || ctxCompat || this;
  27124. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  27125. if ("development" !== 'production') {
  27126. validateDimensions(this, dimNames);
  27127. }
  27128. var dimSize = dimNames.length;
  27129. var dimIndices = map$1(dimNames, function (dimName) {
  27130. return _this._dimensionInfos[dimName].index;
  27131. });
  27132. var storageArr = this._storageArr;
  27133. for (var i = 0, len = this.count(); i < len; i++) {
  27134. var rawIdx = this.getRawIndex(i); // Simple optimization
  27135. switch (dimSize) {
  27136. case 0:
  27137. cb.call(fCtx, i);
  27138. break;
  27139. case 1:
  27140. cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], i);
  27141. break;
  27142. case 2:
  27143. cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], storageArr[dimIndices[1]][rawIdx], i);
  27144. break;
  27145. default:
  27146. var k = 0;
  27147. var value = [];
  27148. for (; k < dimSize; k++) {
  27149. value[k] = storageArr[dimIndices[k]][rawIdx];
  27150. } // Index
  27151. value[k] = i;
  27152. cb.apply(fCtx, value);
  27153. }
  27154. }
  27155. };
  27156. List.prototype.filterSelf = function (dims, cb, ctx, ctxCompat) {
  27157. var _this = this;
  27158. if (!this._count) {
  27159. return;
  27160. }
  27161. if (typeof dims === 'function') {
  27162. ctxCompat = ctx;
  27163. ctx = cb;
  27164. cb = dims;
  27165. dims = [];
  27166. } // ctxCompat just for compat echarts3
  27167. var fCtx = ctx || ctxCompat || this;
  27168. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  27169. if ("development" !== 'production') {
  27170. validateDimensions(this, dimNames);
  27171. }
  27172. var count = this.count();
  27173. var Ctor = getIndicesCtor(this);
  27174. var newIndices = new Ctor(count);
  27175. var value = [];
  27176. var dimSize = dimNames.length;
  27177. var offset = 0;
  27178. var dimIndices = map$1(dimNames, function (dimName) {
  27179. return _this._dimensionInfos[dimName].index;
  27180. });
  27181. var dim0 = dimIndices[0];
  27182. var storageArr = this._storageArr;
  27183. for (var i = 0; i < count; i++) {
  27184. var keep = void 0;
  27185. var rawIdx = this.getRawIndex(i); // Simple optimization
  27186. if (dimSize === 0) {
  27187. keep = cb.call(fCtx, i);
  27188. } else if (dimSize === 1) {
  27189. var val = storageArr[dim0][rawIdx];
  27190. keep = cb.call(fCtx, val, i);
  27191. } else {
  27192. var k = 0;
  27193. for (; k < dimSize; k++) {
  27194. value[k] = storageArr[dimIndices[k]][rawIdx];
  27195. }
  27196. value[k] = i;
  27197. keep = cb.apply(fCtx, value);
  27198. }
  27199. if (keep) {
  27200. newIndices[offset++] = rawIdx;
  27201. }
  27202. } // Set indices after filtered.
  27203. if (offset < count) {
  27204. this._indices = newIndices;
  27205. }
  27206. this._count = offset; // Reset data extent
  27207. this._extent = {};
  27208. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27209. return this;
  27210. };
  27211. /**
  27212. * Select data in range. (For optimization of filter)
  27213. * (Manually inline code, support 5 million data filtering in data zoom.)
  27214. */
  27215. List.prototype.selectRange = function (range) {
  27216. var _this = this;
  27217. var len = this._count;
  27218. if (!len) {
  27219. return;
  27220. }
  27221. var dimensions = [];
  27222. for (var dim in range) {
  27223. if (range.hasOwnProperty(dim)) {
  27224. dimensions.push(dim);
  27225. }
  27226. }
  27227. if ("development" !== 'production') {
  27228. validateDimensions(this, dimensions);
  27229. }
  27230. var dimSize = dimensions.length;
  27231. if (!dimSize) {
  27232. return;
  27233. }
  27234. var originalCount = this.count();
  27235. var Ctor = getIndicesCtor(this);
  27236. var newIndices = new Ctor(originalCount);
  27237. var offset = 0;
  27238. var dim0 = dimensions[0];
  27239. var dimIndices = map$1(dimensions, function (dimName) {
  27240. return _this._dimensionInfos[dimName].index;
  27241. });
  27242. var min = range[dim0][0];
  27243. var max = range[dim0][1];
  27244. var storageArr = this._storageArr;
  27245. var quickFinished = false;
  27246. if (!this._indices) {
  27247. // Extreme optimization for common case. About 2x faster in chrome.
  27248. var idx = 0;
  27249. if (dimSize === 1) {
  27250. var dimStorage = storageArr[dimIndices[0]];
  27251. for (var i = 0; i < len; i++) {
  27252. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  27253. // value indicates the line should be broken. But for the case like
  27254. // scatter plot, a data item with empty value will not be rendered,
  27255. // but the axis extent may be effected if some other dim of the data
  27256. // item has value. Fortunately it is not a significant negative effect.
  27257. if (val >= min && val <= max || isNaN(val)) {
  27258. newIndices[offset++] = idx;
  27259. }
  27260. idx++;
  27261. }
  27262. quickFinished = true;
  27263. } else if (dimSize === 2) {
  27264. var dimStorage = storageArr[dimIndices[0]];
  27265. var dimStorage2 = storageArr[dimIndices[1]];
  27266. var min2 = range[dimensions[1]][0];
  27267. var max2 = range[dimensions[1]][1];
  27268. for (var i = 0; i < len; i++) {
  27269. var val = dimStorage[i];
  27270. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  27271. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  27272. newIndices[offset++] = idx;
  27273. }
  27274. idx++;
  27275. }
  27276. quickFinished = true;
  27277. }
  27278. }
  27279. if (!quickFinished) {
  27280. if (dimSize === 1) {
  27281. for (var i = 0; i < originalCount; i++) {
  27282. var rawIndex = this.getRawIndex(i);
  27283. var val = storageArr[dimIndices[0]][rawIndex]; // Do not filter NaN, see comment above.
  27284. if (val >= min && val <= max || isNaN(val)) {
  27285. newIndices[offset++] = rawIndex;
  27286. }
  27287. }
  27288. } else {
  27289. for (var i = 0; i < originalCount; i++) {
  27290. var keep = true;
  27291. var rawIndex = this.getRawIndex(i);
  27292. for (var k = 0; k < dimSize; k++) {
  27293. var dimk = dimensions[k];
  27294. var val = storageArr[dimIndices[k]][rawIndex]; // Do not filter NaN, see comment above.
  27295. if (val < range[dimk][0] || val > range[dimk][1]) {
  27296. keep = false;
  27297. }
  27298. }
  27299. if (keep) {
  27300. newIndices[offset++] = this.getRawIndex(i);
  27301. }
  27302. }
  27303. }
  27304. } // Set indices after filtered.
  27305. if (offset < originalCount) {
  27306. this._indices = newIndices;
  27307. }
  27308. this._count = offset; // Reset data extent
  27309. this._extent = {};
  27310. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27311. return this;
  27312. };
  27313. /* eslint-enable */
  27314. List.prototype.mapArray = function (dims, cb, ctx, ctxCompat) {
  27315. if (typeof dims === 'function') {
  27316. ctxCompat = ctx;
  27317. ctx = cb;
  27318. cb = dims;
  27319. dims = [];
  27320. } // ctxCompat just for compat echarts3
  27321. ctx = ctx || ctxCompat || this;
  27322. var result = [];
  27323. this.each(dims, function () {
  27324. result.push(cb && cb.apply(this, arguments));
  27325. }, ctx);
  27326. return result;
  27327. };
  27328. List.prototype.map = function (dims, cb, ctx, ctxCompat) {
  27329. var fCtx = ctx || ctxCompat || this;
  27330. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  27331. if ("development" !== 'production') {
  27332. validateDimensions(this, dimNames);
  27333. }
  27334. var list = cloneListForMapAndSample(this, dimNames);
  27335. var storage = list._storage; // Following properties are all immutable.
  27336. // So we can reference to the same value
  27337. list._indices = this._indices;
  27338. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27339. var tmpRetValue = [];
  27340. var dimSize = dimNames.length;
  27341. var dataCount = this.count();
  27342. var values = [];
  27343. var rawExtent = list._rawExtent;
  27344. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  27345. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  27346. values[dimIndex] = this.get(dimNames[dimIndex], dataIndex);
  27347. }
  27348. values[dimSize] = dataIndex;
  27349. var retValue = cb && cb.apply(fCtx, values);
  27350. if (retValue != null) {
  27351. // a number or string (in oridinal dimension)?
  27352. if (typeof retValue !== 'object') {
  27353. tmpRetValue[0] = retValue;
  27354. retValue = tmpRetValue;
  27355. }
  27356. var rawIndex = this.getRawIndex(dataIndex);
  27357. for (var i = 0; i < retValue.length; i++) {
  27358. var dim = dimNames[i];
  27359. var val = retValue[i];
  27360. var rawExtentOnDim = rawExtent[dim];
  27361. var dimStore = storage[dim];
  27362. if (dimStore) {
  27363. dimStore[rawIndex] = val;
  27364. }
  27365. if (val < rawExtentOnDim[0]) {
  27366. rawExtentOnDim[0] = val;
  27367. }
  27368. if (val > rawExtentOnDim[1]) {
  27369. rawExtentOnDim[1] = val;
  27370. }
  27371. }
  27372. }
  27373. }
  27374. return list;
  27375. };
  27376. /**
  27377. * Large data down sampling on given dimension
  27378. * @param sampleIndex Sample index for name and id
  27379. */
  27380. List.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27381. var list = cloneListForMapAndSample(this, [dimension]);
  27382. var targetStorage = list._storage;
  27383. var frameValues = [];
  27384. var frameSize = mathFloor(1 / rate);
  27385. var dimStore = targetStorage[dimension];
  27386. var len = this.count();
  27387. var rawExtentOnDim = list._rawExtent[dimension];
  27388. var newIndices = new (getIndicesCtor(this))(len);
  27389. var offset = 0;
  27390. for (var i = 0; i < len; i += frameSize) {
  27391. // Last frame
  27392. if (frameSize > len - i) {
  27393. frameSize = len - i;
  27394. frameValues.length = frameSize;
  27395. }
  27396. for (var k = 0; k < frameSize; k++) {
  27397. var dataIdx = this.getRawIndex(i + k);
  27398. frameValues[k] = dimStore[dataIdx];
  27399. }
  27400. var value = sampleValue(frameValues);
  27401. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  27402. dimStore[sampleFrameIdx] = value;
  27403. if (value < rawExtentOnDim[0]) {
  27404. rawExtentOnDim[0] = value;
  27405. }
  27406. if (value > rawExtentOnDim[1]) {
  27407. rawExtentOnDim[1] = value;
  27408. }
  27409. newIndices[offset++] = sampleFrameIdx;
  27410. }
  27411. list._count = offset;
  27412. list._indices = newIndices;
  27413. list.getRawIndex = getRawIndexWithIndices;
  27414. return list;
  27415. };
  27416. /**
  27417. * Large data down sampling using largest-triangle-three-buckets
  27418. * @param {string} valueDimension
  27419. * @param {number} targetCount
  27420. */
  27421. List.prototype.lttbDownSample = function (valueDimension, rate) {
  27422. var list = cloneListForMapAndSample(this, []);
  27423. var targetStorage = list._storage;
  27424. var dimStore = targetStorage[valueDimension];
  27425. var len = this.count();
  27426. var newIndices = new (getIndicesCtor(this))(len);
  27427. var sampledIndex = 0;
  27428. var frameSize = mathFloor(1 / rate);
  27429. var currentRawIndex = this.getRawIndex(0);
  27430. var maxArea;
  27431. var area;
  27432. var nextRawIndex; // First frame use the first data.
  27433. newIndices[sampledIndex++] = currentRawIndex;
  27434. for (var i = 1; i < len - 1; i += frameSize) {
  27435. var nextFrameStart = Math.min(i + frameSize, len - 1);
  27436. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  27437. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  27438. var avgY = 0;
  27439. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  27440. var rawIndex = this.getRawIndex(idx);
  27441. var y = dimStore[rawIndex];
  27442. if (isNaN(y)) {
  27443. continue;
  27444. }
  27445. avgY += y;
  27446. }
  27447. avgY /= nextFrameEnd - nextFrameStart;
  27448. var frameStart = i;
  27449. var frameEnd = Math.min(i + frameSize, len);
  27450. var pointAX = i - 1;
  27451. var pointAY = dimStore[currentRawIndex];
  27452. maxArea = -1;
  27453. nextRawIndex = frameStart; // Find a point from current frame that construct a triangel with largest area with previous selected point
  27454. // And the average of next frame.
  27455. for (var idx = frameStart; idx < frameEnd; idx++) {
  27456. var rawIndex = this.getRawIndex(idx);
  27457. var y = dimStore[rawIndex];
  27458. if (isNaN(y)) {
  27459. continue;
  27460. } // Calculate triangle area over three buckets
  27461. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  27462. if (area > maxArea) {
  27463. maxArea = area;
  27464. nextRawIndex = rawIndex; // Next a is this b
  27465. }
  27466. }
  27467. newIndices[sampledIndex++] = nextRawIndex;
  27468. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  27469. } // First frame use the last data.
  27470. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  27471. list._count = sampledIndex;
  27472. list._indices = newIndices;
  27473. list.getRawIndex = getRawIndexWithIndices;
  27474. return list;
  27475. };
  27476. /**
  27477. * Get model of one data item.
  27478. */
  27479. // TODO: Type of data item
  27480. List.prototype.getItemModel = function (idx) {
  27481. var hostModel = this.hostModel;
  27482. var dataItem = this.getRawDataItem(idx);
  27483. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  27484. };
  27485. /**
  27486. * Create a data differ
  27487. */
  27488. List.prototype.diff = function (otherList) {
  27489. var thisList = this;
  27490. return new DataDiffer(otherList ? otherList.getIndices() : [], this.getIndices(), function (idx) {
  27491. return getId(otherList, idx);
  27492. }, function (idx) {
  27493. return getId(thisList, idx);
  27494. });
  27495. };
  27496. /**
  27497. * Get visual property.
  27498. */
  27499. List.prototype.getVisual = function (key) {
  27500. var visual = this._visual;
  27501. return visual && visual[key];
  27502. };
  27503. List.prototype.setVisual = function (kvObj, val) {
  27504. this._visual = this._visual || {};
  27505. if (isObject$3(kvObj)) {
  27506. extend(this._visual, kvObj);
  27507. } else {
  27508. this._visual[kvObj] = val;
  27509. }
  27510. };
  27511. /**
  27512. * Get visual property of single data item
  27513. */
  27514. // eslint-disable-next-line
  27515. List.prototype.getItemVisual = function (idx, key) {
  27516. var itemVisual = this._itemVisuals[idx];
  27517. var val = itemVisual && itemVisual[key];
  27518. if (val == null) {
  27519. // Use global visual property
  27520. return this.getVisual(key);
  27521. }
  27522. return val;
  27523. };
  27524. /**
  27525. * If exists visual property of single data item
  27526. */
  27527. List.prototype.hasItemVisual = function () {
  27528. return this._itemVisuals.length > 0;
  27529. };
  27530. /**
  27531. * Make sure itemVisual property is unique
  27532. */
  27533. // TODO: use key to save visual to reduce memory.
  27534. List.prototype.ensureUniqueItemVisual = function (idx, key) {
  27535. var itemVisuals = this._itemVisuals;
  27536. var itemVisual = itemVisuals[idx];
  27537. if (!itemVisual) {
  27538. itemVisual = itemVisuals[idx] = {};
  27539. }
  27540. var val = itemVisual[key];
  27541. if (val == null) {
  27542. val = this.getVisual(key); // TODO Performance?
  27543. if (isArray(val)) {
  27544. val = val.slice();
  27545. } else if (isObject$3(val)) {
  27546. val = extend({}, val);
  27547. }
  27548. itemVisual[key] = val;
  27549. }
  27550. return val;
  27551. }; // eslint-disable-next-line
  27552. List.prototype.setItemVisual = function (idx, key, value) {
  27553. var itemVisual = this._itemVisuals[idx] || {};
  27554. this._itemVisuals[idx] = itemVisual;
  27555. if (isObject$3(key)) {
  27556. extend(itemVisual, key);
  27557. } else {
  27558. itemVisual[key] = value;
  27559. }
  27560. };
  27561. /**
  27562. * Clear itemVisuals and list visual.
  27563. */
  27564. List.prototype.clearAllVisual = function () {
  27565. this._visual = {};
  27566. this._itemVisuals = [];
  27567. };
  27568. List.prototype.setLayout = function (key, val) {
  27569. if (isObject$3(key)) {
  27570. for (var name_1 in key) {
  27571. if (key.hasOwnProperty(name_1)) {
  27572. this.setLayout(name_1, key[name_1]);
  27573. }
  27574. }
  27575. return;
  27576. }
  27577. this._layout[key] = val;
  27578. };
  27579. /**
  27580. * Get layout property.
  27581. */
  27582. List.prototype.getLayout = function (key) {
  27583. return this._layout[key];
  27584. };
  27585. /**
  27586. * Get layout of single data item
  27587. */
  27588. List.prototype.getItemLayout = function (idx) {
  27589. return this._itemLayouts[idx];
  27590. };
  27591. /**
  27592. * Set layout of single data item
  27593. */
  27594. List.prototype.setItemLayout = function (idx, layout, merge) {
  27595. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  27596. };
  27597. /**
  27598. * Clear all layout of single data item
  27599. */
  27600. List.prototype.clearItemLayouts = function () {
  27601. this._itemLayouts.length = 0;
  27602. };
  27603. /**
  27604. * Set graphic element relative to data. It can be set as null
  27605. */
  27606. List.prototype.setItemGraphicEl = function (idx, el) {
  27607. var hostModel = this.hostModel;
  27608. if (el) {
  27609. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  27610. // Useful in tooltip
  27611. ecData.dataIndex = idx;
  27612. ecData.dataType = this.dataType;
  27613. ecData.seriesIndex = hostModel && hostModel.seriesIndex; // TODO: not store dataIndex on children.
  27614. if (el.type === 'group') {
  27615. el.traverse(setItemDataAndSeriesIndex, el);
  27616. }
  27617. }
  27618. this._graphicEls[idx] = el;
  27619. };
  27620. List.prototype.getItemGraphicEl = function (idx) {
  27621. return this._graphicEls[idx];
  27622. };
  27623. List.prototype.eachItemGraphicEl = function (cb, context) {
  27624. each(this._graphicEls, function (el, idx) {
  27625. if (el) {
  27626. cb && cb.call(context, el, idx);
  27627. }
  27628. });
  27629. };
  27630. /**
  27631. * Shallow clone a new list except visual and layout properties, and graph elements.
  27632. * New list only change the indices.
  27633. */
  27634. List.prototype.cloneShallow = function (list) {
  27635. if (!list) {
  27636. var dimensionInfoList = map$1(this.dimensions, this.getDimensionInfo, this);
  27637. list = new List(dimensionInfoList, this.hostModel);
  27638. } // FIXME
  27639. list._storage = this._storage;
  27640. list._storageArr = this._storageArr;
  27641. transferProperties(list, this); // Clone will not change the data extent and indices
  27642. if (this._indices) {
  27643. var Ctor = this._indices.constructor;
  27644. if (Ctor === Array) {
  27645. var thisCount = this._indices.length;
  27646. list._indices = new Ctor(thisCount);
  27647. for (var i = 0; i < thisCount; i++) {
  27648. list._indices[i] = this._indices[i];
  27649. }
  27650. } else {
  27651. list._indices = new Ctor(this._indices);
  27652. }
  27653. } else {
  27654. list._indices = null;
  27655. }
  27656. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27657. return list;
  27658. };
  27659. /**
  27660. * Wrap some method to add more feature
  27661. */
  27662. List.prototype.wrapMethod = function (methodName, injectFunction) {
  27663. var originalMethod = this[methodName];
  27664. if (typeof originalMethod !== 'function') {
  27665. return;
  27666. }
  27667. this.__wrappedMethods = this.__wrappedMethods || [];
  27668. this.__wrappedMethods.push(methodName);
  27669. this[methodName] = function () {
  27670. var res = originalMethod.apply(this, arguments);
  27671. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27672. };
  27673. }; // ----------------------------------------------------------
  27674. // A work around for internal method visiting private member.
  27675. // ----------------------------------------------------------
  27676. List.internalField = function () {
  27677. defaultDimValueGetters = {
  27678. arrayRows: getDimValueSimply,
  27679. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  27680. return parseDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  27681. },
  27682. keyedColumns: getDimValueSimply,
  27683. original: function (dataItem, dimName, dataIndex, dimIndex) {
  27684. // Performance sensitive, do not use modelUtil.getDataItemValue.
  27685. // If dataItem is an plain object with no value field, the let `value`
  27686. // will be assigned with the object, but it will be tread correctly
  27687. // in the `convertValue`.
  27688. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value); // If any dataItem is like { value: 10 }
  27689. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  27690. this.hasItemOption = true;
  27691. }
  27692. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  27693. : value, this._dimensionInfos[dimName]);
  27694. },
  27695. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  27696. return dataItem[dimIndex];
  27697. }
  27698. };
  27699. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  27700. return parseDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  27701. }
  27702. prepareInvertedIndex = function (list) {
  27703. var invertedIndicesMap = list._invertedIndicesMap;
  27704. each(invertedIndicesMap, function (invertedIndices, dim) {
  27705. var dimInfo = list._dimensionInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27706. var ordinalMeta = dimInfo.ordinalMeta;
  27707. if (ordinalMeta) {
  27708. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  27709. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27710. for (var i = 0; i < invertedIndices.length; i++) {
  27711. invertedIndices[i] = INDEX_NOT_FOUND;
  27712. }
  27713. for (var i = 0; i < list._count; i++) {
  27714. // Only support the case that all values are distinct.
  27715. invertedIndices[list.get(dim, i)] = i;
  27716. }
  27717. }
  27718. });
  27719. };
  27720. getIdNameFromStore = function (list, dimIdx, ordinalMeta, rawIndex) {
  27721. var val;
  27722. var chunk = list._storageArr[dimIdx];
  27723. if (chunk) {
  27724. val = chunk[rawIndex];
  27725. if (ordinalMeta && ordinalMeta.categories.length) {
  27726. val = ordinalMeta.categories[val];
  27727. }
  27728. }
  27729. return convertOptionIdName(val, null);
  27730. };
  27731. getIndicesCtor = function (list) {
  27732. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  27733. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  27734. };
  27735. prepareStorage = function (storage, dimInfo, end, append) {
  27736. var DataCtor = dataCtors[dimInfo.type];
  27737. var dim = dimInfo.name;
  27738. if (append) {
  27739. var oldStore = storage[dim];
  27740. var oldLen = oldStore && oldStore.length;
  27741. if (!(oldLen === end)) {
  27742. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  27743. // within the initial chunkSize.
  27744. for (var j = 0; j < oldLen; j++) {
  27745. newStore[j] = oldStore[j];
  27746. }
  27747. storage[dim] = newStore;
  27748. }
  27749. } else {
  27750. storage[dim] = new DataCtor(end);
  27751. }
  27752. };
  27753. getRawIndexWithoutIndices = function (idx) {
  27754. return idx;
  27755. };
  27756. getRawIndexWithIndices = function (idx) {
  27757. if (idx < this._count && idx >= 0) {
  27758. return this._indices[idx];
  27759. }
  27760. return -1;
  27761. };
  27762. /**
  27763. * @see the comment of `List['getId']`.
  27764. */
  27765. getId = function (list, rawIndex) {
  27766. var id = list._idList[rawIndex];
  27767. if (id == null && list._idDimIdx != null) {
  27768. id = getIdNameFromStore(list, list._idDimIdx, list._idOrdinalMeta, rawIndex);
  27769. }
  27770. if (id == null) {
  27771. id = ID_PREFIX + rawIndex;
  27772. }
  27773. return id;
  27774. };
  27775. normalizeDimensions = function (dimensions) {
  27776. if (!isArray(dimensions)) {
  27777. dimensions = dimensions != null ? [dimensions] : [];
  27778. }
  27779. return dimensions;
  27780. };
  27781. validateDimensions = function (list, dims) {
  27782. for (var i = 0; i < dims.length; i++) {
  27783. // stroage may be empty when no data, so use
  27784. // dimensionInfos to check.
  27785. if (!list._dimensionInfos[dims[i]]) {
  27786. console.error('Unkown dimension ' + dims[i]);
  27787. }
  27788. }
  27789. }; // Data in excludeDimensions is copied, otherwise transfered.
  27790. cloneListForMapAndSample = function (original, excludeDimensions) {
  27791. var allDimensions = original.dimensions;
  27792. var list = new List(map$1(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  27793. transferProperties(list, original);
  27794. var storage = list._storage = {};
  27795. var originalStorage = original._storage;
  27796. var storageArr = list._storageArr = []; // Init storage
  27797. for (var i = 0; i < allDimensions.length; i++) {
  27798. var dim = allDimensions[i];
  27799. if (originalStorage[dim]) {
  27800. // Notice that we do not reset invertedIndicesMap here, becuase
  27801. // there is no scenario of mapping or sampling ordinal dimension.
  27802. if (indexOf(excludeDimensions, dim) >= 0) {
  27803. storage[dim] = cloneChunk(originalStorage[dim]);
  27804. list._rawExtent[dim] = getInitialExtent();
  27805. list._extent[dim] = null;
  27806. } else {
  27807. // Direct reference for other dimensions
  27808. storage[dim] = originalStorage[dim];
  27809. }
  27810. storageArr.push(storage[dim]);
  27811. }
  27812. }
  27813. return list;
  27814. };
  27815. function cloneChunk(originalChunk) {
  27816. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  27817. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  27818. }
  27819. getInitialExtent = function () {
  27820. return [Infinity, -Infinity];
  27821. };
  27822. setItemDataAndSeriesIndex = function (child) {
  27823. var childECData = getECData(child);
  27824. var thisECData = getECData(this);
  27825. childECData.seriesIndex = thisECData.seriesIndex;
  27826. childECData.dataIndex = thisECData.dataIndex;
  27827. childECData.dataType = thisECData.dataType;
  27828. };
  27829. transferProperties = function (target, source) {
  27830. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  27831. if (source.hasOwnProperty(propName)) {
  27832. target[propName] = source[propName];
  27833. }
  27834. });
  27835. target.__wrappedMethods = source.__wrappedMethods;
  27836. each(CLONE_PROPERTIES, function (propName) {
  27837. target[propName] = clone(source[propName]);
  27838. });
  27839. target._calculationInfo = extend({}, source._calculationInfo);
  27840. };
  27841. makeIdFromName = function (list, idx) {
  27842. var nameList = list._nameList;
  27843. var idList = list._idList;
  27844. var nameDimIdx = list._nameDimIdx;
  27845. var idDimIdx = list._idDimIdx;
  27846. var name = nameList[idx];
  27847. var id = idList[idx];
  27848. if (name == null && nameDimIdx != null) {
  27849. nameList[idx] = name = getIdNameFromStore(list, nameDimIdx, list._nameOrdinalMeta, idx);
  27850. }
  27851. if (id == null && idDimIdx != null) {
  27852. idList[idx] = id = getIdNameFromStore(list, idDimIdx, list._idOrdinalMeta, idx);
  27853. }
  27854. if (id == null && name != null) {
  27855. var nameRepeatCount = list._nameRepeatCount;
  27856. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  27857. id = name;
  27858. if (nmCnt > 1) {
  27859. id += '__ec__' + nmCnt;
  27860. }
  27861. idList[idx] = id;
  27862. }
  27863. };
  27864. }();
  27865. return List;
  27866. }();
  27867. /**
  27868. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  27869. *
  27870. * This method builds the relationship between:
  27871. * + "what the coord sys or series requires (see `sysDims`)",
  27872. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  27873. * + "what the data source provids (see `source`)".
  27874. *
  27875. * Some guess strategy will be adapted if user does not define something.
  27876. * If no 'value' dimension specified, the first no-named dimension will be
  27877. * named as 'value'.
  27878. *
  27879. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  27880. * provides not only dim template, but also default order.
  27881. * properties: 'name', 'type', 'displayName'.
  27882. * `name` of each item provides default coord name.
  27883. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  27884. * provide dims count that the sysDim required.
  27885. * [{ordinalMeta}] can be specified.
  27886. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  27887. * @param {Object} [opt]
  27888. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  27889. * For example: ['asdf', {name, type}, ...].
  27890. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  27891. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  27892. * If not specified, auto find the next available data dim.
  27893. * param source {module:data/Source}
  27894. * param dimCount {number}
  27895. * return {Object} encode Never be `null/undefined`.
  27896. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  27897. * If not specified, extra dim names will be:
  27898. * 'value', 'value0', 'value1', ...
  27899. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  27900. * If `generateCoordCount` specified, the generated dim names will be:
  27901. * `generateCoord` + 0, `generateCoord` + 1, ...
  27902. * can be Infinity, indicate that use all of the remain columns.
  27903. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  27904. * @return {Array.<module:data/DataDimensionInfo>}
  27905. */
  27906. function completeDimensions(sysDims, source, opt) {
  27907. if (!isSourceInstance(source)) {
  27908. source = createSourceFromSeriesDataOption(source);
  27909. }
  27910. opt = opt || {};
  27911. sysDims = (sysDims || []).slice();
  27912. var dimsDef = (opt.dimsDef || []).slice();
  27913. var dataDimNameMap = createHashMap();
  27914. var coordDimNameMap = createHashMap(); // let valueCandidate;
  27915. var result = [];
  27916. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount); // Apply user defined dims (`name` and `type`) and init result.
  27917. for (var i = 0; i < dimCount; i++) {
  27918. var dimDefItemRaw = dimsDef[i];
  27919. var dimDefItem = dimsDef[i] = extend({}, isObject(dimDefItemRaw) ? dimDefItemRaw : {
  27920. name: dimDefItemRaw
  27921. });
  27922. var userDimName = dimDefItem.name;
  27923. var resultItem = result[i] = new DataDimensionInfo(); // Name will be applied later for avoiding duplication.
  27924. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27925. // Only if `series.dimensions` is defined in option
  27926. // displayName, will be set, and dimension will be diplayed vertically in
  27927. // tooltip by default.
  27928. resultItem.name = resultItem.displayName = userDimName;
  27929. dataDimNameMap.set(userDimName, i);
  27930. }
  27931. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27932. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27933. }
  27934. var encodeDef = opt.encodeDef;
  27935. if (!encodeDef && opt.encodeDefaulter) {
  27936. encodeDef = opt.encodeDefaulter(source, dimCount);
  27937. }
  27938. var encodeDefMap = createHashMap(encodeDef); // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  27939. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  27940. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27941. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27942. // this case.
  27943. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  27944. encodeDefMap.set(coordDim, false);
  27945. return;
  27946. }
  27947. var validDataDims = encodeDefMap.set(coordDim, []);
  27948. each(dataDims, function (resultDimIdxOrName, idx) {
  27949. // The input resultDimIdx can be dim name or index.
  27950. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  27951. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27952. validDataDims[idx] = resultDimIdx;
  27953. applyDim(result[resultDimIdx], coordDim, idx);
  27954. }
  27955. });
  27956. }); // Apply templetes and default order from `sysDims`.
  27957. var availDimIdx = 0;
  27958. each(sysDims, function (sysDimItemRaw) {
  27959. var coordDim;
  27960. var sysDimItemDimsDef;
  27961. var sysDimItemOtherDims;
  27962. var sysDimItem;
  27963. if (isString(sysDimItemRaw)) {
  27964. coordDim = sysDimItemRaw;
  27965. sysDimItem = {};
  27966. } else {
  27967. sysDimItem = sysDimItemRaw;
  27968. coordDim = sysDimItem.name;
  27969. var ordinalMeta = sysDimItem.ordinalMeta;
  27970. sysDimItem.ordinalMeta = null;
  27971. sysDimItem = clone(sysDimItem);
  27972. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  27973. sysDimItemDimsDef = sysDimItem.dimsDef;
  27974. sysDimItemOtherDims = sysDimItem.otherDims;
  27975. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27976. }
  27977. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  27978. if (dataDims === false) {
  27979. return;
  27980. }
  27981. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  27982. if (!dataDims.length) {
  27983. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27984. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27985. availDimIdx++;
  27986. }
  27987. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27988. }
  27989. } // Apply templates.
  27990. each(dataDims, function (resultDimIdx, coordDimIndex) {
  27991. var resultItem = result[resultDimIdx];
  27992. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27993. if (resultItem.name == null && sysDimItemDimsDef) {
  27994. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27995. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  27996. name: sysDimItemDimsDefItem
  27997. });
  27998. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27999. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28000. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28001. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28002. });
  28003. });
  28004. function applyDim(resultItem, coordDim, coordDimIndex) {
  28005. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  28006. resultItem.otherDims[coordDim] = coordDimIndex;
  28007. } else {
  28008. resultItem.coordDim = coordDim;
  28009. resultItem.coordDimIndex = coordDimIndex;
  28010. coordDimNameMap.set(coordDim, true);
  28011. }
  28012. } // Make sure the first extra dim is 'value'.
  28013. var generateCoord = opt.generateCoord;
  28014. var generateCoordCount = opt.generateCoordCount;
  28015. var fromZero = generateCoordCount != null;
  28016. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  28017. var extra = generateCoord || 'value'; // Set dim `name` and other `coordDim` and other props.
  28018. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28019. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28020. var coordDim = resultItem.coordDim;
  28021. if (coordDim == null) {
  28022. resultItem.coordDim = genName(extra, coordDimNameMap, fromZero);
  28023. resultItem.coordDimIndex = 0;
  28024. if (!generateCoord || generateCoordCount <= 0) {
  28025. resultItem.isExtraCoord = true;
  28026. }
  28027. generateCoordCount--;
  28028. }
  28029. resultItem.name == null && (resultItem.name = genName(resultItem.coordDim, dataDimNameMap, false));
  28030. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  28031. // {
  28032. // dataset: {source: [
  28033. // ['2001', 123],
  28034. // ['2002', 456],
  28035. // ...
  28036. // ['The others', 987],
  28037. // ]},
  28038. // series: {type: 'pie'}
  28039. // }
  28040. // The first colum should better be treated as a "ordinal" although it
  28041. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28042. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  28043. resultItem.type = 'ordinal';
  28044. }
  28045. }
  28046. return result;
  28047. } // ??? TODO
  28048. // Originally detect dimCount by data[0]. Should we
  28049. // optimize it to only by sysDims and dimensions and encode.
  28050. // So only necessary dims will be initialized.
  28051. // But
  28052. // (1) custom series should be considered. where other dims
  28053. // may be visited.
  28054. // (2) sometimes user need to calcualte bubble size or use visualMap
  28055. // on other dimensions besides coordSys needed.
  28056. // So, dims that is not used by system, should be shared in storage?
  28057. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28058. // Note that the result dimCount should not small than columns count
  28059. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28060. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  28061. each(sysDims, function (sysDimItem) {
  28062. var sysDimItemDimsDef;
  28063. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  28064. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  28065. }
  28066. });
  28067. return dimCount;
  28068. }
  28069. function genName(name, map, fromZero) {
  28070. if (fromZero || map.get(name) != null) {
  28071. var i = 0;
  28072. while (map.get(name + i) != null) {
  28073. i++;
  28074. }
  28075. name += i;
  28076. }
  28077. map.set(name, true);
  28078. return name;
  28079. }
  28080. /**
  28081. * @param opt.coordDimensions
  28082. * @param opt.dimensionsDefine By default `source.dimensionsDefine` Overwrite source define.
  28083. * @param opt.encodeDefine By default `source.encodeDefine` Overwrite source define.
  28084. * @param opt.encodeDefaulter Make default encode if user not specified.
  28085. */
  28086. function createDimensions( // TODO: TYPE completeDimensions type
  28087. source, opt) {
  28088. opt = opt || {};
  28089. return completeDimensions(opt.coordDimensions || [], source, {
  28090. // FIXME:TS detect whether source then call `.dimensionsDefine` and `.encodeDefine`?
  28091. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28092. encodeDef: opt.encodeDefine || source.encodeDefine,
  28093. dimCount: opt.dimensionsCount,
  28094. encodeDefaulter: opt.encodeDefaulter,
  28095. generateCoord: opt.generateCoord,
  28096. generateCoordCount: opt.generateCoordCount
  28097. });
  28098. }
  28099. /**
  28100. * @class
  28101. * For example:
  28102. * {
  28103. * coordSysName: 'cartesian2d',
  28104. * coordSysDims: ['x', 'y', ...],
  28105. * axisMap: HashMap({
  28106. * x: xAxisModel,
  28107. * y: yAxisModel
  28108. * }),
  28109. * categoryAxisMap: HashMap({
  28110. * x: xAxisModel,
  28111. * y: undefined
  28112. * }),
  28113. * // The index of the first category axis in `coordSysDims`.
  28114. * // `null/undefined` means no category axis exists.
  28115. * firstCategoryDimIndex: 1,
  28116. * // To replace user specified encode.
  28117. * }
  28118. */
  28119. var CoordSysInfo =
  28120. /** @class */
  28121. function () {
  28122. function CoordSysInfo(coordSysName) {
  28123. this.coordSysDims = [];
  28124. this.axisMap = createHashMap();
  28125. this.categoryAxisMap = createHashMap();
  28126. this.coordSysName = coordSysName;
  28127. }
  28128. return CoordSysInfo;
  28129. }();
  28130. function getCoordSysInfoBySeries(seriesModel) {
  28131. var coordSysName = seriesModel.get('coordinateSystem');
  28132. var result = new CoordSysInfo(coordSysName);
  28133. var fetch = fetchers[coordSysName];
  28134. if (fetch) {
  28135. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28136. return result;
  28137. }
  28138. }
  28139. var fetchers = {
  28140. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28141. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  28142. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  28143. if ("development" !== 'production') {
  28144. if (!xAxisModel) {
  28145. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  28146. }
  28147. if (!yAxisModel) {
  28148. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  28149. }
  28150. }
  28151. result.coordSysDims = ['x', 'y'];
  28152. axisMap.set('x', xAxisModel);
  28153. axisMap.set('y', yAxisModel);
  28154. if (isCategory(xAxisModel)) {
  28155. categoryAxisMap.set('x', xAxisModel);
  28156. result.firstCategoryDimIndex = 0;
  28157. }
  28158. if (isCategory(yAxisModel)) {
  28159. categoryAxisMap.set('y', yAxisModel);
  28160. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28161. }
  28162. },
  28163. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28164. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  28165. if ("development" !== 'production') {
  28166. if (!singleAxisModel) {
  28167. throw new Error('singleAxis should be specified.');
  28168. }
  28169. }
  28170. result.coordSysDims = ['single'];
  28171. axisMap.set('single', singleAxisModel);
  28172. if (isCategory(singleAxisModel)) {
  28173. categoryAxisMap.set('single', singleAxisModel);
  28174. result.firstCategoryDimIndex = 0;
  28175. }
  28176. },
  28177. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28178. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  28179. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28180. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28181. if ("development" !== 'production') {
  28182. if (!angleAxisModel) {
  28183. throw new Error('angleAxis option not found');
  28184. }
  28185. if (!radiusAxisModel) {
  28186. throw new Error('radiusAxis option not found');
  28187. }
  28188. }
  28189. result.coordSysDims = ['radius', 'angle'];
  28190. axisMap.set('radius', radiusAxisModel);
  28191. axisMap.set('angle', angleAxisModel);
  28192. if (isCategory(radiusAxisModel)) {
  28193. categoryAxisMap.set('radius', radiusAxisModel);
  28194. result.firstCategoryDimIndex = 0;
  28195. }
  28196. if (isCategory(angleAxisModel)) {
  28197. categoryAxisMap.set('angle', angleAxisModel);
  28198. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28199. }
  28200. },
  28201. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28202. result.coordSysDims = ['lng', 'lat'];
  28203. },
  28204. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28205. var ecModel = seriesModel.ecModel;
  28206. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  28207. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28208. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28209. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28210. var axisDim = coordSysDims[index];
  28211. axisMap.set(axisDim, axisModel);
  28212. if (isCategory(axisModel)) {
  28213. categoryAxisMap.set(axisDim, axisModel);
  28214. if (result.firstCategoryDimIndex == null) {
  28215. result.firstCategoryDimIndex = index;
  28216. }
  28217. }
  28218. });
  28219. }
  28220. };
  28221. function isCategory(axisModel) {
  28222. return axisModel.get('type') === 'category';
  28223. }
  28224. /**
  28225. * Note that it is too complicated to support 3d stack by value
  28226. * (have to create two-dimension inverted index), so in 3d case
  28227. * we just support that stacked by index.
  28228. *
  28229. * @param seriesModel
  28230. * @param dimensionInfoList The same as the input of <module:echarts/data/List>.
  28231. * The input dimensionInfoList will be modified.
  28232. * @param opt
  28233. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  28234. * @param opt.byIndex=false
  28235. * @return calculationInfo
  28236. * {
  28237. * stackedDimension: string
  28238. * stackedByDimension: string
  28239. * isStackedByIndex: boolean
  28240. * stackedOverDimension: string
  28241. * stackResultDimension: string
  28242. * }
  28243. */
  28244. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28245. opt = opt || {};
  28246. var byIndex = opt.byIndex;
  28247. var stackedCoordDimension = opt.stackedCoordDimension; // Compatibal: when `stack` is set as '', do not stack.
  28248. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28249. var stackedByDimInfo;
  28250. var stackedDimInfo;
  28251. var stackResultDimension;
  28252. var stackedOverDimension;
  28253. each(dimensionInfoList, function (dimensionInfo, index) {
  28254. if (isString(dimensionInfo)) {
  28255. dimensionInfoList[index] = dimensionInfo = {
  28256. name: dimensionInfo
  28257. };
  28258. }
  28259. if (mayStack && !dimensionInfo.isExtraCoord) {
  28260. // Find the first ordinal dimension as the stackedByDimInfo.
  28261. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28262. stackedByDimInfo = dimensionInfo;
  28263. } // Find the first stackable dimension as the stackedDimInfo.
  28264. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  28265. stackedDimInfo = dimensionInfo;
  28266. }
  28267. }
  28268. });
  28269. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28270. // Compatible with previous design, value axis (time axis) only stack by index.
  28271. // It may make sense if the user provides elaborately constructed data.
  28272. byIndex = true;
  28273. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28274. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28275. // might not be a good way.
  28276. if (stackedDimInfo) {
  28277. // Use a weird name that not duplicated with other names.
  28278. stackResultDimension = '__\0ecstackresult';
  28279. stackedOverDimension = '__\0ecstackedover'; // Create inverted index to fast query index by value.
  28280. if (stackedByDimInfo) {
  28281. stackedByDimInfo.createInvertedIndices = true;
  28282. }
  28283. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  28284. var stackedDimType = stackedDimInfo.type;
  28285. var stackedDimCoordIndex_1 = 0;
  28286. each(dimensionInfoList, function (dimensionInfo) {
  28287. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  28288. stackedDimCoordIndex_1++;
  28289. }
  28290. });
  28291. dimensionInfoList.push({
  28292. name: stackResultDimension,
  28293. coordDim: stackedDimCoordDim_1,
  28294. coordDimIndex: stackedDimCoordIndex_1,
  28295. type: stackedDimType,
  28296. isExtraCoord: true,
  28297. isCalculationCoord: true
  28298. });
  28299. stackedDimCoordIndex_1++;
  28300. dimensionInfoList.push({
  28301. name: stackedOverDimension,
  28302. // This dimension contains stack base (generally, 0), so do not set it as
  28303. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28304. coordDim: stackedOverDimension,
  28305. coordDimIndex: stackedDimCoordIndex_1,
  28306. type: stackedDimType,
  28307. isExtraCoord: true,
  28308. isCalculationCoord: true
  28309. });
  28310. }
  28311. return {
  28312. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28313. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28314. isStackedByIndex: byIndex,
  28315. stackedOverDimension: stackedOverDimension,
  28316. stackResultDimension: stackResultDimension
  28317. };
  28318. }
  28319. function isDimensionStacked(data, stackedDim
  28320. /*, stackedByDim*/
  28321. ) {
  28322. // Each single series only maps to one pair of axis. So we do not need to
  28323. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28324. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension'); // && (
  28325. // stackedByDim != null
  28326. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28327. // : data.getCalculationInfo('isStackedByIndex')
  28328. // );
  28329. }
  28330. function getStackedDimension(data, targetDim) {
  28331. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  28332. }
  28333. function createListFromArray(source, seriesModel, opt) {
  28334. opt = opt || {};
  28335. if (!isSourceInstance(source)) {
  28336. source = createSourceFromSeriesDataOption(source);
  28337. }
  28338. var coordSysName = seriesModel.get('coordinateSystem');
  28339. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28340. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28341. var coordSysDimDefs;
  28342. if (coordSysInfo && coordSysInfo.coordSysDims) {
  28343. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28344. var dimInfo = {
  28345. name: dim
  28346. };
  28347. var axisModel = coordSysInfo.axisMap.get(dim);
  28348. if (axisModel) {
  28349. var axisType = axisModel.get('type');
  28350. dimInfo.type = getDimensionTypeByAxis(axisType); // dimInfo.stackable = isStackable(axisType);
  28351. }
  28352. return dimInfo;
  28353. });
  28354. }
  28355. if (!coordSysDimDefs) {
  28356. // Get dimensions from registered coordinate system
  28357. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  28358. }
  28359. var useEncodeDefaulter = opt.useEncodeDefaulter;
  28360. var dimInfoList = createDimensions(source, {
  28361. coordDimensions: coordSysDimDefs,
  28362. generateCoord: opt.generateCoord,
  28363. encodeDefaulter: isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null
  28364. });
  28365. var firstCategoryDimIndex;
  28366. var hasNameEncode;
  28367. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  28368. var coordDim = dimInfo.coordDim;
  28369. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  28370. if (categoryAxisModel) {
  28371. if (firstCategoryDimIndex == null) {
  28372. firstCategoryDimIndex = dimIndex;
  28373. }
  28374. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  28375. if (opt.createInvertedIndices) {
  28376. dimInfo.createInvertedIndices = true;
  28377. }
  28378. }
  28379. if (dimInfo.otherDims.itemName != null) {
  28380. hasNameEncode = true;
  28381. }
  28382. });
  28383. if (!hasNameEncode && firstCategoryDimIndex != null) {
  28384. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  28385. }
  28386. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  28387. var list = new List(dimInfoList, seriesModel);
  28388. list.setCalculationInfo(stackCalculationInfo);
  28389. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  28390. // Use dataIndex as ordinal value in categoryAxis
  28391. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  28392. } : null;
  28393. list.hasItemOption = false;
  28394. list.initData(source, null, dimValueGetter);
  28395. return list;
  28396. }
  28397. function isNeedCompleteOrdinalData(source) {
  28398. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  28399. var sampleItem = firstDataNotNull(source.data || []);
  28400. return sampleItem != null && !isArray(getDataItemValue(sampleItem));
  28401. }
  28402. }
  28403. function firstDataNotNull(data) {
  28404. var i = 0;
  28405. while (i < data.length && data[i] == null) {
  28406. i++;
  28407. }
  28408. return data[i];
  28409. }
  28410. var Scale =
  28411. /** @class */
  28412. function () {
  28413. function Scale(setting) {
  28414. this._setting = setting || {};
  28415. this._extent = [Infinity, -Infinity];
  28416. }
  28417. Scale.prototype.getSetting = function (name) {
  28418. return this._setting[name];
  28419. };
  28420. /**
  28421. * Set extent from data
  28422. */
  28423. Scale.prototype.unionExtent = function (other) {
  28424. var extent = this._extent;
  28425. other[0] < extent[0] && (extent[0] = other[0]);
  28426. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  28427. // this.setExtent(extent[0], extent[1]);
  28428. };
  28429. /**
  28430. * Set extent from data
  28431. */
  28432. Scale.prototype.unionExtentFromData = function (data, dim) {
  28433. this.unionExtent(data.getApproximateExtent(dim));
  28434. };
  28435. /**
  28436. * Get extent
  28437. *
  28438. * Extent is always in increase order.
  28439. */
  28440. Scale.prototype.getExtent = function () {
  28441. return this._extent.slice();
  28442. };
  28443. /**
  28444. * Set extent
  28445. */
  28446. Scale.prototype.setExtent = function (start, end) {
  28447. var thisExtent = this._extent;
  28448. if (!isNaN(start)) {
  28449. thisExtent[0] = start;
  28450. }
  28451. if (!isNaN(end)) {
  28452. thisExtent[1] = end;
  28453. }
  28454. };
  28455. /**
  28456. * If value is in extent range
  28457. */
  28458. Scale.prototype.isInExtentRange = function (value) {
  28459. return this._extent[0] <= value && this._extent[1] >= value;
  28460. };
  28461. /**
  28462. * When axis extent depends on data and no data exists,
  28463. * axis ticks should not be drawn, which is named 'blank'.
  28464. */
  28465. Scale.prototype.isBlank = function () {
  28466. return this._isBlank;
  28467. };
  28468. /**
  28469. * When axis extent depends on data and no data exists,
  28470. * axis ticks should not be drawn, which is named 'blank'.
  28471. */
  28472. Scale.prototype.setBlank = function (isBlank) {
  28473. this._isBlank = isBlank;
  28474. };
  28475. return Scale;
  28476. }();
  28477. enableClassManagement(Scale);
  28478. var OrdinalMeta =
  28479. /** @class */
  28480. function () {
  28481. function OrdinalMeta(opt) {
  28482. this.categories = opt.categories || [];
  28483. this._needCollect = opt.needCollect;
  28484. this._deduplication = opt.deduplication;
  28485. }
  28486. OrdinalMeta.createByAxisModel = function (axisModel) {
  28487. var option = axisModel.option;
  28488. var data = option.data;
  28489. var categories = data && map(data, getName);
  28490. return new OrdinalMeta({
  28491. categories: categories,
  28492. needCollect: !categories,
  28493. // deduplication is default in axis.
  28494. deduplication: option.dedplication !== false
  28495. });
  28496. };
  28497. OrdinalMeta.prototype.getOrdinal = function (category) {
  28498. // @ts-ignore
  28499. return this._getOrCreateMap().get(category);
  28500. };
  28501. /**
  28502. * @return The ordinal. If not found, return NaN.
  28503. */
  28504. OrdinalMeta.prototype.parseAndCollect = function (category) {
  28505. var index;
  28506. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  28507. // This feature is only supported when !needCollect, because we should
  28508. // consider a common case: a value is 2017, which is a number but is
  28509. // expected to be tread as a category. This case usually happen in dataset,
  28510. // where it happent to be no need of the index feature.
  28511. if (typeof category !== 'string' && !needCollect) {
  28512. return category;
  28513. } // Optimize for the scenario:
  28514. // category is ['2012-01-01', '2012-01-02', ...], where the input
  28515. // data has been ensured not duplicate and is large data.
  28516. // Notice, if a dataset dimension provide categroies, usually echarts
  28517. // should remove duplication except user tell echarts dont do that
  28518. // (set axis.deduplication = false), because echarts do not know whether
  28519. // the values in the category dimension has duplication (consider the
  28520. // parallel-aqi example)
  28521. if (needCollect && !this._deduplication) {
  28522. index = this.categories.length;
  28523. this.categories[index] = category;
  28524. return index;
  28525. }
  28526. var map = this._getOrCreateMap(); // @ts-ignore
  28527. index = map.get(category);
  28528. if (index == null) {
  28529. if (needCollect) {
  28530. index = this.categories.length;
  28531. this.categories[index] = category; // @ts-ignore
  28532. map.set(category, index);
  28533. } else {
  28534. index = NaN;
  28535. }
  28536. }
  28537. return index;
  28538. }; // Consider big data, do not create map until needed.
  28539. OrdinalMeta.prototype._getOrCreateMap = function () {
  28540. return this._map || (this._map = createHashMap(this.categories));
  28541. };
  28542. return OrdinalMeta;
  28543. }();
  28544. function getName(obj) {
  28545. if (isObject(obj) && obj.value != null) {
  28546. return obj.value;
  28547. } else {
  28548. return obj + '';
  28549. }
  28550. }
  28551. var roundNumber = round;
  28552. /**
  28553. * @param extent Both extent[0] and extent[1] should be valid number.
  28554. * Should be extent[0] < extent[1].
  28555. * @param splitNumber splitNumber should be >= 1.
  28556. */
  28557. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  28558. var result = {};
  28559. var span = extent[1] - extent[0];
  28560. var interval = result.interval = nice(span / splitNumber, true);
  28561. if (minInterval != null && interval < minInterval) {
  28562. interval = result.interval = minInterval;
  28563. }
  28564. if (maxInterval != null && interval > maxInterval) {
  28565. interval = result.interval = maxInterval;
  28566. } // Tow more digital for tick.
  28567. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  28568. var niceTickExtent = result.niceTickExtent = [roundNumber(Math.ceil(extent[0] / interval) * interval, precision), roundNumber(Math.floor(extent[1] / interval) * interval, precision)];
  28569. fixExtent(niceTickExtent, extent);
  28570. return result;
  28571. }
  28572. /**
  28573. * @return interval precision
  28574. */
  28575. function getIntervalPrecision(interval) {
  28576. // Tow more digital for tick.
  28577. return getPrecisionSafe(interval) + 2;
  28578. }
  28579. function clamp(niceTickExtent, idx, extent) {
  28580. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  28581. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  28582. function fixExtent(niceTickExtent, extent) {
  28583. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  28584. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  28585. clamp(niceTickExtent, 0, extent);
  28586. clamp(niceTickExtent, 1, extent);
  28587. if (niceTickExtent[0] > niceTickExtent[1]) {
  28588. niceTickExtent[0] = niceTickExtent[1];
  28589. }
  28590. }
  28591. function contain$1(val, extent) {
  28592. return val >= extent[0] && val <= extent[1];
  28593. }
  28594. function normalize$1(val, extent) {
  28595. if (extent[1] === extent[0]) {
  28596. return 0.5;
  28597. }
  28598. return (val - extent[0]) / (extent[1] - extent[0]);
  28599. }
  28600. function scale$2(val, extent) {
  28601. return val * (extent[1] - extent[0]) + extent[0];
  28602. }
  28603. var OrdinalScale =
  28604. /** @class */
  28605. function (_super) {
  28606. __extends(OrdinalScale, _super);
  28607. function OrdinalScale(setting) {
  28608. var _this = _super.call(this, setting) || this;
  28609. _this.type = 'ordinal';
  28610. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  28611. // import approach to get OrdinalMeta class.
  28612. if (!ordinalMeta) {
  28613. ordinalMeta = new OrdinalMeta({});
  28614. }
  28615. if (isArray(ordinalMeta)) {
  28616. ordinalMeta = new OrdinalMeta({
  28617. categories: map(ordinalMeta, function (item) {
  28618. return isObject(item) ? item.value : item;
  28619. })
  28620. });
  28621. }
  28622. _this._ordinalMeta = ordinalMeta;
  28623. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  28624. return _this;
  28625. }
  28626. OrdinalScale.prototype.parse = function (val) {
  28627. return typeof val === 'string' ? this._ordinalMeta.getOrdinal(val) // val might be float.
  28628. : Math.round(val);
  28629. };
  28630. OrdinalScale.prototype.contain = function (rank) {
  28631. rank = this.parse(rank);
  28632. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  28633. };
  28634. /**
  28635. * Normalize given rank or name to linear [0, 1]
  28636. * @param val raw ordinal number.
  28637. * @return normalized value in [0, 1].
  28638. */
  28639. OrdinalScale.prototype.normalize = function (val) {
  28640. val = this._getTickNumber(this.parse(val));
  28641. return normalize$1(val, this._extent);
  28642. };
  28643. /**
  28644. * @param val normalized value in [0, 1].
  28645. * @return raw ordinal number.
  28646. */
  28647. OrdinalScale.prototype.scale = function (val) {
  28648. val = Math.round(scale$2(val, this._extent));
  28649. return this.getRawOrdinalNumber(val);
  28650. };
  28651. OrdinalScale.prototype.getTicks = function () {
  28652. var ticks = [];
  28653. var extent = this._extent;
  28654. var rank = extent[0];
  28655. while (rank <= extent[1]) {
  28656. ticks.push({
  28657. value: rank
  28658. });
  28659. rank++;
  28660. }
  28661. return ticks;
  28662. };
  28663. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  28664. // Not support.
  28665. return;
  28666. };
  28667. /**
  28668. * @see `Ordinal['_ordinalNumbersByTick']`
  28669. */
  28670. OrdinalScale.prototype.setSortInfo = function (info) {
  28671. if (info == null) {
  28672. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  28673. return;
  28674. }
  28675. var infoOrdinalNumbers = info.ordinalNumbers;
  28676. var ordinalsByTick = this._ordinalNumbersByTick = [];
  28677. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  28678. var tickNum = 0;
  28679. var allCategoryLen = this._ordinalMeta.categories.length;
  28680. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  28681. var ordinalNumber = infoOrdinalNumbers[tickNum];
  28682. ordinalsByTick[tickNum] = ordinalNumber;
  28683. ticksByOrdinal[ordinalNumber] = tickNum;
  28684. } // Handle that `series.data` only covers part of the `axis.category.data`.
  28685. var unusedOrdinal = 0;
  28686. for (; tickNum < allCategoryLen; ++tickNum) {
  28687. while (ticksByOrdinal[unusedOrdinal] != null) {
  28688. unusedOrdinal++;
  28689. }
  28690. ordinalsByTick.push(unusedOrdinal);
  28691. ticksByOrdinal[unusedOrdinal] = tickNum;
  28692. }
  28693. };
  28694. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  28695. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  28696. // where ordinal numbers are used as tick value directly.
  28697. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  28698. };
  28699. /**
  28700. * @usage
  28701. * ```js
  28702. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  28703. *
  28704. * // case0
  28705. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  28706. * // case1
  28707. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  28708. * // case2
  28709. * const coord = axis.dataToCoord(ordinalNumber);
  28710. * ```
  28711. *
  28712. * @param {OrdinalNumber} tickNumber index of display
  28713. */
  28714. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  28715. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  28716. // where ordinal numbers are used as tick value directly.
  28717. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  28718. };
  28719. /**
  28720. * Get item on tick
  28721. */
  28722. OrdinalScale.prototype.getLabel = function (tick) {
  28723. if (!this.isBlank()) {
  28724. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  28725. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  28726. // Return empty if it's not exist.
  28727. return cateogry == null ? '' : cateogry + '';
  28728. }
  28729. };
  28730. OrdinalScale.prototype.count = function () {
  28731. return this._extent[1] - this._extent[0] + 1;
  28732. };
  28733. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  28734. this.unionExtent(data.getApproximateExtent(dim));
  28735. };
  28736. /**
  28737. * @override
  28738. * If value is in extent range
  28739. */
  28740. OrdinalScale.prototype.isInExtentRange = function (value) {
  28741. value = this._getTickNumber(value);
  28742. return this._extent[0] <= value && this._extent[1] >= value;
  28743. };
  28744. OrdinalScale.prototype.getOrdinalMeta = function () {
  28745. return this._ordinalMeta;
  28746. };
  28747. OrdinalScale.prototype.niceTicks = function () {};
  28748. OrdinalScale.prototype.niceExtent = function () {};
  28749. OrdinalScale.type = 'ordinal';
  28750. return OrdinalScale;
  28751. }(Scale);
  28752. Scale.registerClass(OrdinalScale);
  28753. var roundNumber$1 = round;
  28754. var IntervalScale =
  28755. /** @class */
  28756. function (_super) {
  28757. __extends(IntervalScale, _super);
  28758. function IntervalScale() {
  28759. var _this = _super !== null && _super.apply(this, arguments) || this;
  28760. _this.type = 'interval'; // Step is calculated in adjustExtent.
  28761. _this._interval = 0;
  28762. _this._intervalPrecision = 2;
  28763. return _this;
  28764. }
  28765. IntervalScale.prototype.parse = function (val) {
  28766. return val;
  28767. };
  28768. IntervalScale.prototype.contain = function (val) {
  28769. return contain$1(val, this._extent);
  28770. };
  28771. IntervalScale.prototype.normalize = function (val) {
  28772. return normalize$1(val, this._extent);
  28773. };
  28774. IntervalScale.prototype.scale = function (val) {
  28775. return scale$2(val, this._extent);
  28776. };
  28777. IntervalScale.prototype.setExtent = function (start, end) {
  28778. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  28779. if (!isNaN(start)) {
  28780. thisExtent[0] = parseFloat(start);
  28781. }
  28782. if (!isNaN(end)) {
  28783. thisExtent[1] = parseFloat(end);
  28784. }
  28785. };
  28786. IntervalScale.prototype.unionExtent = function (other) {
  28787. var extent = this._extent;
  28788. other[0] < extent[0] && (extent[0] = other[0]);
  28789. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  28790. this.setExtent(extent[0], extent[1]);
  28791. };
  28792. IntervalScale.prototype.getInterval = function () {
  28793. return this._interval;
  28794. };
  28795. IntervalScale.prototype.setInterval = function (interval) {
  28796. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  28797. // We assume user wan't to set both interval, min, max to get a better result
  28798. this._niceExtent = this._extent.slice();
  28799. this._intervalPrecision = getIntervalPrecision(interval);
  28800. };
  28801. /**
  28802. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  28803. */
  28804. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  28805. var interval = this._interval;
  28806. var extent = this._extent;
  28807. var niceTickExtent = this._niceExtent;
  28808. var intervalPrecision = this._intervalPrecision;
  28809. var ticks = []; // If interval is 0, return [];
  28810. if (!interval) {
  28811. return ticks;
  28812. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  28813. var safeLimit = 10000;
  28814. if (extent[0] < niceTickExtent[0]) {
  28815. if (expandToNicedExtent) {
  28816. ticks.push({
  28817. value: roundNumber$1(niceTickExtent[0] - interval, intervalPrecision)
  28818. });
  28819. } else {
  28820. ticks.push({
  28821. value: extent[0]
  28822. });
  28823. }
  28824. }
  28825. var tick = niceTickExtent[0];
  28826. while (tick <= niceTickExtent[1]) {
  28827. ticks.push({
  28828. value: tick
  28829. }); // Avoid rounding error
  28830. tick = roundNumber$1(tick + interval, intervalPrecision);
  28831. if (tick === ticks[ticks.length - 1].value) {
  28832. // Consider out of safe float point, e.g.,
  28833. // -3711126.9907707 + 2e-10 === -3711126.9907707
  28834. break;
  28835. }
  28836. if (ticks.length > safeLimit) {
  28837. return [];
  28838. }
  28839. } // Consider this case: the last item of ticks is smaller
  28840. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  28841. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  28842. if (extent[1] > lastNiceTick) {
  28843. if (expandToNicedExtent) {
  28844. ticks.push({
  28845. value: roundNumber$1(lastNiceTick + interval, intervalPrecision)
  28846. });
  28847. } else {
  28848. ticks.push({
  28849. value: extent[1]
  28850. });
  28851. }
  28852. }
  28853. return ticks;
  28854. };
  28855. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  28856. var ticks = this.getTicks(true);
  28857. var minorTicks = [];
  28858. var extent = this.getExtent();
  28859. for (var i = 1; i < ticks.length; i++) {
  28860. var nextTick = ticks[i];
  28861. var prevTick = ticks[i - 1];
  28862. var count = 0;
  28863. var minorTicksGroup = [];
  28864. var interval = nextTick.value - prevTick.value;
  28865. var minorInterval = interval / splitNumber;
  28866. while (count < splitNumber - 1) {
  28867. var minorTick = roundNumber$1(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  28868. if (minorTick > extent[0] && minorTick < extent[1]) {
  28869. minorTicksGroup.push(minorTick);
  28870. }
  28871. count++;
  28872. }
  28873. minorTicks.push(minorTicksGroup);
  28874. }
  28875. return minorTicks;
  28876. };
  28877. /**
  28878. * @param opt.precision If 'auto', use nice presision.
  28879. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  28880. */
  28881. IntervalScale.prototype.getLabel = function (data, opt) {
  28882. if (data == null) {
  28883. return '';
  28884. }
  28885. var precision = opt && opt.precision;
  28886. if (precision == null) {
  28887. precision = getPrecisionSafe(data.value) || 0;
  28888. } else if (precision === 'auto') {
  28889. // Should be more precise then tick.
  28890. precision = this._intervalPrecision;
  28891. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  28892. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  28893. var dataNum = roundNumber$1(data.value, precision, true);
  28894. return addCommas(dataNum);
  28895. };
  28896. /**
  28897. * @param splitNumber By default `5`.
  28898. */
  28899. IntervalScale.prototype.niceTicks = function (splitNumber, minInterval, maxInterval) {
  28900. splitNumber = splitNumber || 5;
  28901. var extent = this._extent;
  28902. var span = extent[1] - extent[0];
  28903. if (!isFinite(span)) {
  28904. return;
  28905. } // User may set axis min 0 and data are all negative
  28906. // FIXME If it needs to reverse ?
  28907. if (span < 0) {
  28908. span = -span;
  28909. extent.reverse();
  28910. }
  28911. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  28912. this._intervalPrecision = result.intervalPrecision;
  28913. this._interval = result.interval;
  28914. this._niceExtent = result.niceTickExtent;
  28915. };
  28916. IntervalScale.prototype.niceExtent = function (opt) {
  28917. var extent = this._extent; // If extent start and end are same, expand them
  28918. if (extent[0] === extent[1]) {
  28919. if (extent[0] !== 0) {
  28920. // Expand extent
  28921. var expandSize = extent[0]; // In the fowllowing case
  28922. // Axis has been fixed max 100
  28923. // Plus data are all 100 and axis extent are [100, 100].
  28924. // Extend to the both side will cause expanded max is larger than fixed max.
  28925. // So only expand to the smaller side.
  28926. if (!opt.fixMax) {
  28927. extent[1] += expandSize / 2;
  28928. extent[0] -= expandSize / 2;
  28929. } else {
  28930. extent[0] -= expandSize / 2;
  28931. }
  28932. } else {
  28933. extent[1] = 1;
  28934. }
  28935. }
  28936. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  28937. if (!isFinite(span)) {
  28938. extent[0] = 0;
  28939. extent[1] = 1;
  28940. }
  28941. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  28942. var interval = this._interval;
  28943. if (!opt.fixMin) {
  28944. extent[0] = roundNumber$1(Math.floor(extent[0] / interval) * interval);
  28945. }
  28946. if (!opt.fixMax) {
  28947. extent[1] = roundNumber$1(Math.ceil(extent[1] / interval) * interval);
  28948. }
  28949. };
  28950. IntervalScale.type = 'interval';
  28951. return IntervalScale;
  28952. }(Scale);
  28953. Scale.registerClass(IntervalScale);
  28954. var STACK_PREFIX = '__ec_stack_';
  28955. var LARGE_BAR_MIN_WIDTH = 0.5;
  28956. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  28957. function getSeriesStackId(seriesModel) {
  28958. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  28959. }
  28960. function getAxisKey(axis) {
  28961. return axis.dim + axis.index;
  28962. }
  28963. function prepareLayoutBarSeries(seriesType, ecModel) {
  28964. var seriesModels = [];
  28965. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  28966. // Check series coordinate, do layout for cartesian2d only
  28967. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  28968. seriesModels.push(seriesModel);
  28969. }
  28970. });
  28971. return seriesModels;
  28972. }
  28973. /**
  28974. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  28975. * values.
  28976. * This works for time axes, value axes, and log axes.
  28977. * For a single time axis, return value is in the form like
  28978. * {'x_0': [1000000]}.
  28979. * The value of 1000000 is in milliseconds.
  28980. */
  28981. function getValueAxesMinGaps(barSeries) {
  28982. /**
  28983. * Map from axis.index to values.
  28984. * For a single time axis, axisValues is in the form like
  28985. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  28986. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  28987. * series.
  28988. */
  28989. var axisValues = {};
  28990. each(barSeries, function (seriesModel) {
  28991. var cartesian = seriesModel.coordinateSystem;
  28992. var baseAxis = cartesian.getBaseAxis();
  28993. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  28994. return;
  28995. }
  28996. var data = seriesModel.getData();
  28997. var key = baseAxis.dim + '_' + baseAxis.index;
  28998. var dim = data.mapDimension(baseAxis.dim);
  28999. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29000. var value = data.get(dim, i);
  29001. if (!axisValues[key]) {
  29002. // No previous data for the axis
  29003. axisValues[key] = [value];
  29004. } else {
  29005. // No value in previous series
  29006. axisValues[key].push(value);
  29007. } // Ignore duplicated time values in the same axis
  29008. }
  29009. });
  29010. var axisMinGaps = {};
  29011. for (var key in axisValues) {
  29012. if (axisValues.hasOwnProperty(key)) {
  29013. var valuesInAxis = axisValues[key];
  29014. if (valuesInAxis) {
  29015. // Sort axis values into ascending order to calculate gaps
  29016. valuesInAxis.sort(function (a, b) {
  29017. return a - b;
  29018. });
  29019. var min = null;
  29020. for (var j = 1; j < valuesInAxis.length; ++j) {
  29021. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29022. if (delta > 0) {
  29023. // Ignore 0 delta because they are of the same axis value
  29024. min = min === null ? delta : Math.min(min, delta);
  29025. }
  29026. } // Set to null if only have one data
  29027. axisMinGaps[key] = min;
  29028. }
  29029. }
  29030. }
  29031. return axisMinGaps;
  29032. }
  29033. function makeColumnLayout(barSeries) {
  29034. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29035. var seriesInfoList = [];
  29036. each(barSeries, function (seriesModel) {
  29037. var cartesian = seriesModel.coordinateSystem;
  29038. var baseAxis = cartesian.getBaseAxis();
  29039. var axisExtent = baseAxis.getExtent();
  29040. var bandWidth;
  29041. if (baseAxis.type === 'category') {
  29042. bandWidth = baseAxis.getBandWidth();
  29043. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29044. var key = baseAxis.dim + '_' + baseAxis.index;
  29045. var minGap = axisMinGaps[key];
  29046. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29047. var scale = baseAxis.scale.getExtent();
  29048. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29049. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  29050. } else {
  29051. var data = seriesModel.getData();
  29052. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29053. }
  29054. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  29055. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  29056. var barMinWidth = parsePercent$1( // barMinWidth by default is 1 in cartesian. Because in value axis,
  29057. // the auto-calculated bar width might be less than 1.
  29058. seriesModel.get('barMinWidth') || 1, bandWidth);
  29059. var barGap = seriesModel.get('barGap');
  29060. var barCategoryGap = seriesModel.get('barCategoryGap');
  29061. seriesInfoList.push({
  29062. bandWidth: bandWidth,
  29063. barWidth: barWidth,
  29064. barMaxWidth: barMaxWidth,
  29065. barMinWidth: barMinWidth,
  29066. barGap: barGap,
  29067. barCategoryGap: barCategoryGap,
  29068. axisKey: getAxisKey(baseAxis),
  29069. stackId: getSeriesStackId(seriesModel)
  29070. });
  29071. });
  29072. return doCalBarWidthAndOffset(seriesInfoList);
  29073. }
  29074. function doCalBarWidthAndOffset(seriesInfoList) {
  29075. // Columns info on each category axis. Key is cartesian name
  29076. var columnsMap = {};
  29077. each(seriesInfoList, function (seriesInfo, idx) {
  29078. var axisKey = seriesInfo.axisKey;
  29079. var bandWidth = seriesInfo.bandWidth;
  29080. var columnsOnAxis = columnsMap[axisKey] || {
  29081. bandWidth: bandWidth,
  29082. remainedWidth: bandWidth,
  29083. autoWidthCount: 0,
  29084. categoryGap: null,
  29085. gap: '20%',
  29086. stacks: {}
  29087. };
  29088. var stacks = columnsOnAxis.stacks;
  29089. columnsMap[axisKey] = columnsOnAxis;
  29090. var stackId = seriesInfo.stackId;
  29091. if (!stacks[stackId]) {
  29092. columnsOnAxis.autoWidthCount++;
  29093. }
  29094. stacks[stackId] = stacks[stackId] || {
  29095. width: 0,
  29096. maxWidth: 0
  29097. }; // Caution: In a single coordinate system, these barGrid attributes
  29098. // will be shared by series. Consider that they have default values,
  29099. // only the attributes set on the last series will work.
  29100. // Do not change this fact unless there will be a break change.
  29101. var barWidth = seriesInfo.barWidth;
  29102. if (barWidth && !stacks[stackId].width) {
  29103. // See #6312, do not restrict width.
  29104. stacks[stackId].width = barWidth;
  29105. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29106. columnsOnAxis.remainedWidth -= barWidth;
  29107. }
  29108. var barMaxWidth = seriesInfo.barMaxWidth;
  29109. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  29110. var barMinWidth = seriesInfo.barMinWidth;
  29111. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  29112. var barGap = seriesInfo.barGap;
  29113. barGap != null && (columnsOnAxis.gap = barGap);
  29114. var barCategoryGap = seriesInfo.barCategoryGap;
  29115. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  29116. });
  29117. var result = {};
  29118. each(columnsMap, function (columnsOnAxis, coordSysName) {
  29119. result[coordSysName] = {};
  29120. var stacks = columnsOnAxis.stacks;
  29121. var bandWidth = columnsOnAxis.bandWidth;
  29122. var categoryGapPercent = columnsOnAxis.categoryGap;
  29123. if (categoryGapPercent == null) {
  29124. var columnCount = keys(stacks).length; // More columns in one group
  29125. // the spaces between group is smaller. Or the column will be too thin.
  29126. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  29127. }
  29128. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  29129. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  29130. var remainedWidth = columnsOnAxis.remainedWidth;
  29131. var autoWidthCount = columnsOnAxis.autoWidthCount;
  29132. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29133. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  29134. each(stacks, function (column) {
  29135. var maxWidth = column.maxWidth;
  29136. var minWidth = column.minWidth;
  29137. if (!column.width) {
  29138. var finalWidth = autoWidth;
  29139. if (maxWidth && maxWidth < finalWidth) {
  29140. finalWidth = Math.min(maxWidth, remainedWidth);
  29141. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  29142. // bar is able to be visible. So `minWidth` should not be restricted
  29143. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  29144. // the extreme cases for `value` axis, bars are allowed to overlap
  29145. // with each other if `minWidth` specified.
  29146. if (minWidth && minWidth > finalWidth) {
  29147. finalWidth = minWidth;
  29148. }
  29149. if (finalWidth !== autoWidth) {
  29150. column.width = finalWidth;
  29151. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29152. autoWidthCount--;
  29153. }
  29154. } else {
  29155. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  29156. // CSS does. Becuase barWidth can be a percent value, where
  29157. // `barMaxWidth` can be used to restrict the final width.
  29158. var finalWidth = column.width;
  29159. if (maxWidth) {
  29160. finalWidth = Math.min(finalWidth, maxWidth);
  29161. } // `minWidth` has higher priority, as described above
  29162. if (minWidth) {
  29163. finalWidth = Math.max(finalWidth, minWidth);
  29164. }
  29165. column.width = finalWidth;
  29166. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29167. autoWidthCount--;
  29168. }
  29169. }); // Recalculate width again
  29170. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29171. autoWidth = Math.max(autoWidth, 0);
  29172. var widthSum = 0;
  29173. var lastColumn;
  29174. each(stacks, function (column, idx) {
  29175. if (!column.width) {
  29176. column.width = autoWidth;
  29177. }
  29178. lastColumn = column;
  29179. widthSum += column.width * (1 + barGapPercent);
  29180. });
  29181. if (lastColumn) {
  29182. widthSum -= lastColumn.width * barGapPercent;
  29183. }
  29184. var offset = -widthSum / 2;
  29185. each(stacks, function (column, stackId) {
  29186. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  29187. bandWidth: bandWidth,
  29188. offset: offset,
  29189. width: column.width
  29190. };
  29191. offset += column.width * (1 + barGapPercent);
  29192. });
  29193. });
  29194. return result;
  29195. }
  29196. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  29197. if (barWidthAndOffset && axis) {
  29198. var result = barWidthAndOffset[getAxisKey(axis)];
  29199. if (result != null && seriesModel != null) {
  29200. return result[getSeriesStackId(seriesModel)];
  29201. }
  29202. return result;
  29203. }
  29204. }
  29205. function layout(seriesType, ecModel) {
  29206. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  29207. var barWidthAndOffset = makeColumnLayout(seriesModels);
  29208. var lastStackCoords = {};
  29209. each(seriesModels, function (seriesModel) {
  29210. var data = seriesModel.getData();
  29211. var cartesian = seriesModel.coordinateSystem;
  29212. var baseAxis = cartesian.getBaseAxis();
  29213. var stackId = getSeriesStackId(seriesModel);
  29214. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  29215. var columnOffset = columnLayoutInfo.offset;
  29216. var columnWidth = columnLayoutInfo.width;
  29217. var valueAxis = cartesian.getOtherAxis(baseAxis);
  29218. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  29219. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  29220. data.setLayout({
  29221. bandWidth: columnLayoutInfo.bandWidth,
  29222. offset: columnOffset,
  29223. size: columnWidth
  29224. });
  29225. var valueDim = data.mapDimension(valueAxis.dim);
  29226. var baseDim = data.mapDimension(baseAxis.dim);
  29227. var stacked = isDimensionStacked(data, valueDim
  29228. /*, baseDim*/
  29229. );
  29230. var isValueAxisH = valueAxis.isHorizontal();
  29231. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  29232. for (var idx = 0, len = data.count(); idx < len; idx++) {
  29233. var value = data.get(valueDim, idx);
  29234. var baseValue = data.get(baseDim, idx);
  29235. var sign = value >= 0 ? 'p' : 'n';
  29236. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  29237. // stackResultDimension directly.
  29238. if (stacked) {
  29239. // Only ordinal axis can be stacked.
  29240. if (!lastStackCoords[stackId][baseValue]) {
  29241. lastStackCoords[stackId][baseValue] = {
  29242. p: valueAxisStart,
  29243. n: valueAxisStart // Negative stack
  29244. };
  29245. } // Should also consider #4243
  29246. baseCoord = lastStackCoords[stackId][baseValue][sign];
  29247. }
  29248. var x = void 0;
  29249. var y = void 0;
  29250. var width = void 0;
  29251. var height = void 0;
  29252. if (isValueAxisH) {
  29253. var coord = cartesian.dataToPoint([value, baseValue]);
  29254. x = baseCoord;
  29255. y = coord[1] + columnOffset;
  29256. width = coord[0] - valueAxisStart;
  29257. height = columnWidth;
  29258. if (Math.abs(width) < barMinHeight) {
  29259. width = (width < 0 ? -1 : 1) * barMinHeight;
  29260. } // Ignore stack from NaN value
  29261. if (!isNaN(width)) {
  29262. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  29263. }
  29264. } else {
  29265. var coord = cartesian.dataToPoint([baseValue, value]);
  29266. x = coord[0] + columnOffset;
  29267. y = baseCoord;
  29268. width = columnWidth;
  29269. height = coord[1] - valueAxisStart;
  29270. if (Math.abs(height) < barMinHeight) {
  29271. // Include zero to has a positive bar
  29272. height = (height <= 0 ? -1 : 1) * barMinHeight;
  29273. } // Ignore stack from NaN value
  29274. if (!isNaN(height)) {
  29275. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  29276. }
  29277. }
  29278. data.setItemLayout(idx, {
  29279. x: x,
  29280. y: y,
  29281. width: width,
  29282. height: height
  29283. });
  29284. }
  29285. });
  29286. } // TODO: Do not support stack in large mode yet.
  29287. var largeLayout = {
  29288. seriesType: 'bar',
  29289. plan: createRenderPlanner(),
  29290. reset: function (seriesModel) {
  29291. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  29292. return;
  29293. }
  29294. var data = seriesModel.getData();
  29295. var cartesian = seriesModel.coordinateSystem;
  29296. var coordLayout = cartesian.master.getRect();
  29297. var baseAxis = cartesian.getBaseAxis();
  29298. var valueAxis = cartesian.getOtherAxis(baseAxis);
  29299. var valueDim = data.mapDimension(valueAxis.dim);
  29300. var baseDim = data.mapDimension(baseAxis.dim);
  29301. var valueAxisHorizontal = valueAxis.isHorizontal();
  29302. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  29303. var barWidth = retrieveColumnLayout(makeColumnLayout([seriesModel]), baseAxis, seriesModel).width;
  29304. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) {
  29305. // jshint ignore:line
  29306. barWidth = LARGE_BAR_MIN_WIDTH;
  29307. }
  29308. return {
  29309. progress: function (params, data) {
  29310. var count = params.count;
  29311. var largePoints = new LargeArr(count * 2);
  29312. var largeBackgroundPoints = new LargeArr(count * 2);
  29313. var largeDataIndices = new LargeArr(count);
  29314. var dataIndex;
  29315. var coord = [];
  29316. var valuePair = [];
  29317. var pointsOffset = 0;
  29318. var idxOffset = 0;
  29319. while ((dataIndex = params.next()) != null) {
  29320. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  29321. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  29322. coord = cartesian.dataToPoint(valuePair, null, coord); // Data index might not be in order, depends on `progressiveChunkMode`.
  29323. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];
  29324. largePoints[pointsOffset++] = coord[0];
  29325. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height;
  29326. largePoints[pointsOffset++] = coord[1];
  29327. largeDataIndices[idxOffset++] = dataIndex;
  29328. }
  29329. data.setLayout({
  29330. largePoints: largePoints,
  29331. largeDataIndices: largeDataIndices,
  29332. largeBackgroundPoints: largeBackgroundPoints,
  29333. barWidth: barWidth,
  29334. valueAxisStart: getValueAxisStart(baseAxis, valueAxis),
  29335. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  29336. valueAxisHorizontal: valueAxisHorizontal
  29337. });
  29338. }
  29339. };
  29340. }
  29341. };
  29342. function isOnCartesian(seriesModel) {
  29343. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  29344. }
  29345. function isInLargeMode(seriesModel) {
  29346. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  29347. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  29348. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  29349. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  29350. }
  29351. var bisect = function (a, x, lo, hi) {
  29352. while (lo < hi) {
  29353. var mid = lo + hi >>> 1;
  29354. if (a[mid][1] < x) {
  29355. lo = mid + 1;
  29356. } else {
  29357. hi = mid;
  29358. }
  29359. }
  29360. return lo;
  29361. };
  29362. var TimeScale =
  29363. /** @class */
  29364. function (_super) {
  29365. __extends(TimeScale, _super);
  29366. function TimeScale(settings) {
  29367. var _this = _super.call(this, settings) || this;
  29368. _this.type = 'time';
  29369. return _this;
  29370. }
  29371. /**
  29372. * Get label is mainly for other components like dataZoom, tooltip.
  29373. */
  29374. TimeScale.prototype.getLabel = function (tick) {
  29375. var useUTC = this.getSetting('useUTC');
  29376. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  29377. };
  29378. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  29379. var isUTC = this.getSetting('useUTC');
  29380. var lang = this.getSetting('locale');
  29381. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  29382. };
  29383. /**
  29384. * @override
  29385. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  29386. */
  29387. TimeScale.prototype.getTicks = function (expandToNicedExtent) {
  29388. var interval = this._interval;
  29389. var extent = this._extent;
  29390. var ticks = []; // If interval is 0, return [];
  29391. if (!interval) {
  29392. return ticks;
  29393. }
  29394. ticks.push({
  29395. value: extent[0],
  29396. level: 0
  29397. });
  29398. var useUTC = this.getSetting('useUTC');
  29399. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  29400. ticks = ticks.concat(innerTicks);
  29401. ticks.push({
  29402. value: extent[1],
  29403. level: 0
  29404. });
  29405. return ticks;
  29406. };
  29407. TimeScale.prototype.niceExtent = function (opt) {
  29408. var extent = this._extent; // If extent start and end are same, expand them
  29409. if (extent[0] === extent[1]) {
  29410. // Expand extent
  29411. extent[0] -= ONE_DAY;
  29412. extent[1] += ONE_DAY;
  29413. } // If there are no data and extent are [Infinity, -Infinity]
  29414. if (extent[1] === -Infinity && extent[0] === Infinity) {
  29415. var d = new Date();
  29416. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  29417. extent[0] = extent[1] - ONE_DAY;
  29418. }
  29419. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29420. };
  29421. TimeScale.prototype.niceTicks = function (approxTickNum, minInterval, maxInterval) {
  29422. approxTickNum = approxTickNum || 10;
  29423. var extent = this._extent;
  29424. var span = extent[1] - extent[0];
  29425. this._approxInterval = span / approxTickNum;
  29426. if (minInterval != null && this._approxInterval < minInterval) {
  29427. this._approxInterval = minInterval;
  29428. }
  29429. if (maxInterval != null && this._approxInterval > maxInterval) {
  29430. this._approxInterval = maxInterval;
  29431. }
  29432. var scaleIntervalsLen = scaleIntervals.length;
  29433. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  29434. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  29435. // We check one more level to avoid the ticks are to sparse in some case.
  29436. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  29437. };
  29438. TimeScale.prototype.parse = function (val) {
  29439. // val might be float.
  29440. return typeof val === 'number' ? val : +parseDate(val);
  29441. };
  29442. TimeScale.prototype.contain = function (val) {
  29443. return contain$1(this.parse(val), this._extent);
  29444. };
  29445. TimeScale.prototype.normalize = function (val) {
  29446. return normalize$1(this.parse(val), this._extent);
  29447. };
  29448. TimeScale.prototype.scale = function (val) {
  29449. return scale$2(val, this._extent);
  29450. };
  29451. TimeScale.type = 'time';
  29452. return TimeScale;
  29453. }(IntervalScale);
  29454. /**
  29455. * This implementation was originally copied from "d3.js"
  29456. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  29457. * with some modifications made for this program.
  29458. * See the license statement at the head of this file.
  29459. */
  29460. var scaleIntervals = [// Format interval
  29461. ['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
  29462. ];
  29463. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  29464. var dateA = parseDate(valueA);
  29465. var dateB = parseDate(valueB);
  29466. var isSame = function (unit) {
  29467. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  29468. };
  29469. var isSameYear = function () {
  29470. return isSame('year');
  29471. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  29472. // const isSameQuater = () => isSameYear() && isSame('quarter');
  29473. var isSameMonth = function () {
  29474. return isSameYear() && isSame('month');
  29475. };
  29476. var isSameDay = function () {
  29477. return isSameMonth() && isSame('day');
  29478. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  29479. var isSameHour = function () {
  29480. return isSameDay() && isSame('hour');
  29481. };
  29482. var isSameMinute = function () {
  29483. return isSameHour() && isSame('minute');
  29484. };
  29485. var isSameSecond = function () {
  29486. return isSameMinute() && isSame('second');
  29487. };
  29488. var isSameMilliSecond = function () {
  29489. return isSameSecond() && isSame('millisecond');
  29490. };
  29491. switch (unit) {
  29492. case 'year':
  29493. return isSameYear();
  29494. case 'month':
  29495. return isSameMonth();
  29496. case 'day':
  29497. return isSameDay();
  29498. case 'hour':
  29499. return isSameHour();
  29500. case 'minute':
  29501. return isSameMinute();
  29502. case 'second':
  29503. return isSameSecond();
  29504. case 'millisecond':
  29505. return isSameMilliSecond();
  29506. }
  29507. } // const primaryUnitGetters = {
  29508. // year: fullYearGetterName(),
  29509. // month: monthGetterName(),
  29510. // day: dateGetterName(),
  29511. // hour: hoursGetterName(),
  29512. // minute: minutesGetterName(),
  29513. // second: secondsGetterName(),
  29514. // millisecond: millisecondsGetterName()
  29515. // };
  29516. // const primaryUnitUTCGetters = {
  29517. // year: fullYearGetterName(true),
  29518. // month: monthGetterName(true),
  29519. // day: dateGetterName(true),
  29520. // hour: hoursGetterName(true),
  29521. // minute: minutesGetterName(true),
  29522. // second: secondsGetterName(true),
  29523. // millisecond: millisecondsGetterName(true)
  29524. // };
  29525. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  29526. // step = step || 1;
  29527. // switch (getPrimaryTimeUnit(unitName)) {
  29528. // case 'year':
  29529. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  29530. // break;
  29531. // case 'month':
  29532. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  29533. // break;
  29534. // case 'day':
  29535. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  29536. // break;
  29537. // case 'hour':
  29538. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  29539. // break;
  29540. // case 'minute':
  29541. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  29542. // break;
  29543. // case 'second':
  29544. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  29545. // break;
  29546. // case 'millisecond':
  29547. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  29548. // break;
  29549. // }
  29550. // return date.getTime();
  29551. // }
  29552. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  29553. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  29554. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  29555. function getDateInterval(approxInterval, daysInMonth) {
  29556. approxInterval /= ONE_DAY;
  29557. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick betwen two month.
  29558. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  29559. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  29560. }
  29561. function getMonthInterval(approxInterval) {
  29562. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  29563. approxInterval /= APPROX_ONE_MONTH;
  29564. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  29565. }
  29566. function getHourInterval(approxInterval) {
  29567. approxInterval /= ONE_HOUR;
  29568. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  29569. }
  29570. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  29571. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  29572. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  29573. }
  29574. function getMillisecondsInterval(approxInterval) {
  29575. return nice(approxInterval, true);
  29576. }
  29577. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  29578. var outDate = new Date(date);
  29579. switch (getPrimaryTimeUnit(unitName)) {
  29580. case 'year':
  29581. case 'month':
  29582. outDate[monthSetterName(isUTC)](0);
  29583. case 'day':
  29584. outDate[dateSetterName(isUTC)](1);
  29585. case 'hour':
  29586. outDate[hoursSetterName(isUTC)](0);
  29587. case 'minute':
  29588. outDate[minutesSetterName(isUTC)](0);
  29589. case 'second':
  29590. outDate[secondsSetterName(isUTC)](0);
  29591. outDate[millisecondsSetterName(isUTC)](0);
  29592. }
  29593. return outDate.getTime();
  29594. }
  29595. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  29596. var safeLimit = 10000;
  29597. var unitNames = timeUnits;
  29598. var iter = 0;
  29599. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  29600. var date = new Date(minTimestamp);
  29601. var dateTime = minTimestamp;
  29602. var d = date[getMethodName](); // if (isDate) {
  29603. // d -= 1; // Starts with 0; PENDING
  29604. // }
  29605. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  29606. out.push({
  29607. value: dateTime
  29608. });
  29609. d += interval;
  29610. date[setMethodName](d);
  29611. dateTime = date.getTime();
  29612. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  29613. out.push({
  29614. value: dateTime,
  29615. notAdd: true
  29616. });
  29617. }
  29618. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  29619. var newAddedTicks = [];
  29620. var isFirstLevel = !lastLevelTicks.length;
  29621. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  29622. return;
  29623. }
  29624. if (isFirstLevel) {
  29625. lastLevelTicks = [{
  29626. // TODO Optimize. Not include so may ticks.
  29627. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  29628. }, {
  29629. value: extent[1]
  29630. }];
  29631. }
  29632. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  29633. var startTick = lastLevelTicks[i].value;
  29634. var endTick = lastLevelTicks[i + 1].value;
  29635. if (startTick === endTick) {
  29636. continue;
  29637. }
  29638. var interval = void 0;
  29639. var getterName = void 0;
  29640. var setterName = void 0;
  29641. var isDate = false;
  29642. switch (unitName) {
  29643. case 'year':
  29644. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  29645. getterName = fullYearGetterName(isUTC);
  29646. setterName = fullYearSetterName(isUTC);
  29647. break;
  29648. case 'half-year':
  29649. case 'quarter':
  29650. case 'month':
  29651. interval = getMonthInterval(approxInterval);
  29652. getterName = monthGetterName(isUTC);
  29653. setterName = monthSetterName(isUTC);
  29654. break;
  29655. case 'week': // PENDING If week is added. Ignore day.
  29656. case 'half-week':
  29657. case 'day':
  29658. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  29659. getterName = dateGetterName(isUTC);
  29660. setterName = dateSetterName(isUTC);
  29661. isDate = true;
  29662. break;
  29663. case 'half-day':
  29664. case 'quarter-day':
  29665. case 'hour':
  29666. interval = getHourInterval(approxInterval);
  29667. getterName = hoursGetterName(isUTC);
  29668. setterName = hoursSetterName(isUTC);
  29669. break;
  29670. case 'minute':
  29671. interval = getMinutesAndSecondsInterval(approxInterval, true);
  29672. getterName = minutesGetterName(isUTC);
  29673. setterName = minutesSetterName(isUTC);
  29674. break;
  29675. case 'second':
  29676. interval = getMinutesAndSecondsInterval(approxInterval, false);
  29677. getterName = secondsGetterName(isUTC);
  29678. setterName = secondsSetterName(isUTC);
  29679. break;
  29680. case 'millisecond':
  29681. interval = getMillisecondsInterval(approxInterval);
  29682. getterName = millisecondsGetterName(isUTC);
  29683. setterName = millisecondsSetterName(isUTC);
  29684. break;
  29685. }
  29686. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  29687. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  29688. // Add nearest years to the left extent.
  29689. levelTicks.unshift({
  29690. value: levelTicks[0].value - interval
  29691. });
  29692. }
  29693. }
  29694. for (var i = 0; i < newAddedTicks.length; i++) {
  29695. levelTicks.push(newAddedTicks[i]);
  29696. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  29697. return newAddedTicks;
  29698. }
  29699. var levelsTicks = [];
  29700. var currentLevelTicks = [];
  29701. var tickCount = 0;
  29702. var lastLevelTickCount = 0;
  29703. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  29704. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  29705. if (!isPrimaryTimeUnit(unitNames[i])) {
  29706. // TODO
  29707. continue;
  29708. }
  29709. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  29710. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  29711. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  29712. if (currentLevelTicks.length) {
  29713. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  29714. currentLevelTicks.sort(function (a, b) {
  29715. return a.value - b.value;
  29716. });
  29717. var levelTicksRemoveDuplicated = [];
  29718. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  29719. var tickValue = currentLevelTicks[i_1].value;
  29720. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  29721. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  29722. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  29723. tickCount++;
  29724. }
  29725. }
  29726. }
  29727. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  29728. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  29729. break;
  29730. } // Only treat primary time unit as one level.
  29731. levelsTicks.push(levelTicksRemoveDuplicated);
  29732. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  29733. break;
  29734. }
  29735. } // Reset if next unitName is primary
  29736. currentLevelTicks = [];
  29737. }
  29738. }
  29739. if ("development" !== 'production') {
  29740. if (iter >= safeLimit) {
  29741. warn('Exceed safe limit.');
  29742. }
  29743. }
  29744. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  29745. return filter(levelTicks, function (tick) {
  29746. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  29747. });
  29748. }), function (levelTicks) {
  29749. return levelTicks.length > 0;
  29750. });
  29751. var ticks = [];
  29752. var maxLevel = levelsTicksInExtent.length - 1;
  29753. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  29754. var levelTicks = levelsTicksInExtent[i];
  29755. for (var k = 0; k < levelTicks.length; ++k) {
  29756. ticks.push({
  29757. value: levelTicks[k].value,
  29758. level: maxLevel - i
  29759. });
  29760. }
  29761. }
  29762. ticks.sort(function (a, b) {
  29763. return a.value - b.value;
  29764. }); // Remove duplicates
  29765. var result = [];
  29766. for (var i = 0; i < ticks.length; ++i) {
  29767. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  29768. result.push(ticks[i]);
  29769. }
  29770. }
  29771. return result;
  29772. }
  29773. Scale.registerClass(TimeScale);
  29774. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  29775. var intervalScaleProto = IntervalScale.prototype;
  29776. var getPrecisionSafe$1 = getPrecisionSafe;
  29777. var roundingErrorFix = round;
  29778. var mathFloor$1 = Math.floor;
  29779. var mathCeil = Math.ceil;
  29780. var mathPow$1 = Math.pow;
  29781. var mathLog = Math.log;
  29782. var LogScale =
  29783. /** @class */
  29784. function (_super) {
  29785. __extends(LogScale, _super);
  29786. function LogScale() {
  29787. var _this = _super !== null && _super.apply(this, arguments) || this;
  29788. _this.type = 'log';
  29789. _this.base = 10;
  29790. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  29791. _this._interval = 0;
  29792. return _this;
  29793. }
  29794. /**
  29795. * @param Whether expand the ticks to niced extent.
  29796. */
  29797. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  29798. var originalScale = this._originalScale;
  29799. var extent = this._extent;
  29800. var originalExtent = originalScale.getExtent();
  29801. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  29802. return map(ticks, function (tick) {
  29803. var val = tick.value;
  29804. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  29805. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  29806. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  29807. return {
  29808. value: powVal
  29809. };
  29810. }, this);
  29811. };
  29812. LogScale.prototype.setExtent = function (start, end) {
  29813. var base = this.base;
  29814. start = mathLog(start) / mathLog(base);
  29815. end = mathLog(end) / mathLog(base);
  29816. intervalScaleProto.setExtent.call(this, start, end);
  29817. };
  29818. /**
  29819. * @return {number} end
  29820. */
  29821. LogScale.prototype.getExtent = function () {
  29822. var base = this.base;
  29823. var extent = scaleProto.getExtent.call(this);
  29824. extent[0] = mathPow$1(base, extent[0]);
  29825. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  29826. var originalScale = this._originalScale;
  29827. var originalExtent = originalScale.getExtent();
  29828. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  29829. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  29830. return extent;
  29831. };
  29832. LogScale.prototype.unionExtent = function (extent) {
  29833. this._originalScale.unionExtent(extent);
  29834. var base = this.base;
  29835. extent[0] = mathLog(extent[0]) / mathLog(base);
  29836. extent[1] = mathLog(extent[1]) / mathLog(base);
  29837. scaleProto.unionExtent.call(this, extent);
  29838. };
  29839. LogScale.prototype.unionExtentFromData = function (data, dim) {
  29840. // TODO
  29841. // filter value that <= 0
  29842. this.unionExtent(data.getApproximateExtent(dim));
  29843. };
  29844. /**
  29845. * Update interval and extent of intervals for nice ticks
  29846. * @param approxTickNum default 10 Given approx tick number
  29847. */
  29848. LogScale.prototype.niceTicks = function (approxTickNum) {
  29849. approxTickNum = approxTickNum || 10;
  29850. var extent = this._extent;
  29851. var span = extent[1] - extent[0];
  29852. if (span === Infinity || span <= 0) {
  29853. return;
  29854. }
  29855. var interval = quantity(span);
  29856. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  29857. if (err <= 0.5) {
  29858. interval *= 10;
  29859. } // Interval should be integer
  29860. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  29861. interval *= 10;
  29862. }
  29863. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor$1(extent[1] / interval) * interval)];
  29864. this._interval = interval;
  29865. this._niceExtent = niceExtent;
  29866. };
  29867. LogScale.prototype.niceExtent = function (opt) {
  29868. intervalScaleProto.niceExtent.call(this, opt);
  29869. this._fixMin = opt.fixMin;
  29870. this._fixMax = opt.fixMax;
  29871. };
  29872. LogScale.prototype.parse = function (val) {
  29873. return val;
  29874. };
  29875. LogScale.prototype.contain = function (val) {
  29876. val = mathLog(val) / mathLog(this.base);
  29877. return contain$1(val, this._extent);
  29878. };
  29879. LogScale.prototype.normalize = function (val) {
  29880. val = mathLog(val) / mathLog(this.base);
  29881. return normalize$1(val, this._extent);
  29882. };
  29883. LogScale.prototype.scale = function (val) {
  29884. val = scale$2(val, this._extent);
  29885. return mathPow$1(this.base, val);
  29886. };
  29887. LogScale.type = 'log';
  29888. return LogScale;
  29889. }(Scale);
  29890. var proto = LogScale.prototype;
  29891. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  29892. proto.getLabel = intervalScaleProto.getLabel;
  29893. function fixRoundingError(val, originalVal) {
  29894. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  29895. }
  29896. Scale.registerClass(LogScale);
  29897. var ScaleRawExtentInfo =
  29898. /** @class */
  29899. function () {
  29900. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  29901. originalExtent) {
  29902. this._prepareParams(scale, model, originalExtent);
  29903. }
  29904. /**
  29905. * Parameters depending on ouside (like model, user callback)
  29906. * are prepared and fixed here.
  29907. */
  29908. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  29909. dataExtent) {
  29910. if (dataExtent[1] < dataExtent[0]) {
  29911. dataExtent = [NaN, NaN];
  29912. }
  29913. this._dataMin = dataExtent[0];
  29914. this._dataMax = dataExtent[1];
  29915. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  29916. this._needCrossZero = model.getNeedCrossZero && model.getNeedCrossZero();
  29917. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  29918. if (isFunction(modelMinRaw)) {
  29919. // This callback alway provide users the full data extent (before data filtered).
  29920. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  29921. min: dataExtent[0],
  29922. max: dataExtent[1]
  29923. }));
  29924. } else if (modelMinRaw !== 'dataMin') {
  29925. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  29926. }
  29927. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  29928. if (isFunction(modelMaxRaw)) {
  29929. // This callback alway provide users the full data extent (before data filtered).
  29930. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  29931. min: dataExtent[0],
  29932. max: dataExtent[1]
  29933. }));
  29934. } else if (modelMaxRaw !== 'dataMax') {
  29935. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  29936. }
  29937. if (isOrdinal) {
  29938. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  29939. // and progressive rendering is using, here the category result might just only contain
  29940. // the processed chunk rather than the entire result.
  29941. this._axisDataLen = model.getCategories().length;
  29942. } else {
  29943. var boundaryGap = model.get('boundaryGap');
  29944. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  29945. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  29946. if ("development" !== 'production') {
  29947. 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.');
  29948. }
  29949. this._boundaryGapInner = [0, 0];
  29950. } else {
  29951. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  29952. }
  29953. }
  29954. };
  29955. /**
  29956. * Calculate extent by prepared parameters.
  29957. * This method has no external dependency and can be called duplicatedly,
  29958. * getting the same result.
  29959. * If parameters changed, should call this method to recalcuate.
  29960. */
  29961. ScaleRawExtentInfo.prototype.calculate = function () {
  29962. // Notice: When min/max is not set (that is, when there are null/undefined,
  29963. // which is the most common case), these cases should be ensured:
  29964. // (1) For 'ordinal', show all axis.data.
  29965. // (2) For others:
  29966. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  29967. // disabled).
  29968. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  29969. // be the result that originalExtent enlarged by boundaryGap.
  29970. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  29971. var isOrdinal = this._isOrdinal;
  29972. var dataMin = this._dataMin;
  29973. var dataMax = this._dataMax;
  29974. var axisDataLen = this._axisDataLen;
  29975. var boundaryGapInner = this._boundaryGapInner;
  29976. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  29977. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  29978. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  29979. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  29980. var minFixed = min != null;
  29981. var maxFixed = max != null;
  29982. if (min == null) {
  29983. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  29984. }
  29985. if (max == null) {
  29986. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  29987. }
  29988. (min == null || !isFinite(min)) && (min = NaN);
  29989. (max == null || !isFinite(max)) && (max = NaN);
  29990. if (min > max) {
  29991. min = NaN;
  29992. max = NaN;
  29993. }
  29994. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  29995. if (this._needCrossZero) {
  29996. // Axis is over zero and min is not set
  29997. if (min > 0 && max > 0 && !minFixed) {
  29998. min = 0; // minFixed = true;
  29999. } // Axis is under zero and max is not set
  30000. if (min < 0 && max < 0 && !maxFixed) {
  30001. max = 0; // maxFixed = true;
  30002. } // PENDING:
  30003. // When `needCrossZero` and all data is positive/negative, should it be ensured
  30004. // that the results processed by boundaryGap are positive/negative?
  30005. // If so, here `minFixed`/`maxFixed` need to be set.
  30006. }
  30007. var determinedMin = this._determinedMin;
  30008. var determinedMax = this._determinedMax;
  30009. if (determinedMin != null) {
  30010. min = determinedMin;
  30011. minFixed = true;
  30012. }
  30013. if (determinedMax != null) {
  30014. max = determinedMax;
  30015. maxFixed = true;
  30016. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  30017. // `NaN` means min/max axis is blank.
  30018. return {
  30019. min: min,
  30020. max: max,
  30021. minFixed: minFixed,
  30022. maxFixed: maxFixed,
  30023. isBlank: isBlank
  30024. };
  30025. };
  30026. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  30027. if ("development" !== 'production') {
  30028. assert(!this.frozen);
  30029. }
  30030. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  30031. };
  30032. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  30033. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  30034. if ("development" !== 'production') {
  30035. assert(!this.frozen // Earse them usually means logic flaw.
  30036. && this[attr] == null);
  30037. }
  30038. this[attr] = val;
  30039. };
  30040. ScaleRawExtentInfo.prototype.freeze = function () {
  30041. // @ts-ignore
  30042. this.frozen = true;
  30043. };
  30044. return ScaleRawExtentInfo;
  30045. }();
  30046. var DETERMINED_MIN_MAX_ATTR = {
  30047. min: '_determinedMin',
  30048. max: '_determinedMax'
  30049. };
  30050. var DATA_MIN_MAX_ATTR = {
  30051. min: '_dataMin',
  30052. max: '_dataMax'
  30053. };
  30054. /**
  30055. * Get scale min max and related info only depends on model settings.
  30056. * This method can be called after coordinate system created.
  30057. * For example, in data processing stage.
  30058. *
  30059. * Scale extent info probably be required multiple times during a workflow.
  30060. * For example:
  30061. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  30062. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  30063. * (3) `coordSys.update` use it to finally decide the scale extent.
  30064. * But the callback of `min`/`max` should not be called multiple times.
  30065. * The code below should not be implemented repeatedly either.
  30066. * So we cache the result in the scale instance, which will be recreated at the begining
  30067. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  30068. */
  30069. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  30070. originalExtent) {
  30071. // Do not permit to recreate.
  30072. var rawExtentInfo = scale.rawExtentInfo;
  30073. if (rawExtentInfo) {
  30074. return rawExtentInfo;
  30075. }
  30076. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  30077. scale.rawExtentInfo = rawExtentInfo;
  30078. return rawExtentInfo;
  30079. }
  30080. function parseAxisModelMinMax(scale, minMax) {
  30081. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  30082. }
  30083. /**
  30084. * Get axis scale extent before niced.
  30085. * Item of returned array can only be number (including Infinity and NaN).
  30086. *
  30087. * Caution:
  30088. * Precondition of calling this method:
  30089. * The scale extent has been initialized using series data extent via
  30090. * `scale.setExtent` or `scale.unionExtentFromData`;
  30091. */
  30092. function getScaleExtent(scale, model) {
  30093. var scaleType = scale.type;
  30094. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  30095. scale.setBlank(rawExtentResult.isBlank);
  30096. var min = rawExtentResult.min;
  30097. 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
  30098. // is base axis
  30099. // FIXME
  30100. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30101. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30102. // Should not depend on series type `bar`?
  30103. // (3) Fix that might overlap when using dataZoom.
  30104. // (4) Consider other chart types using `barGrid`?
  30105. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30106. var ecModel = model.ecModel;
  30107. if (ecModel && scaleType === 'time'
  30108. /*|| scaleType === 'interval' */
  30109. ) {
  30110. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30111. var isBaseAxisAndHasBarSeries_1 = false;
  30112. each(barSeriesModels, function (seriesModel) {
  30113. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  30114. });
  30115. if (isBaseAxisAndHasBarSeries_1) {
  30116. // Calculate placement of bars on axis. TODO should be decoupled
  30117. // with barLayout
  30118. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  30119. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30120. min = adjustedScale.min;
  30121. max = adjustedScale.max;
  30122. }
  30123. }
  30124. return {
  30125. extent: [min, max],
  30126. // "fix" means "fixed", the value should not be
  30127. // changed in the subsequent steps.
  30128. fixMin: rawExtentResult.minFixed,
  30129. fixMax: rawExtentResult.maxFixed
  30130. };
  30131. }
  30132. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  30133. barWidthAndOffset) {
  30134. // Get Axis Length
  30135. var axisExtent = model.axis.getExtent();
  30136. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  30137. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30138. if (barsOnCurrentAxis === undefined) {
  30139. return {
  30140. min: min,
  30141. max: max
  30142. };
  30143. }
  30144. var minOverflow = Infinity;
  30145. each(barsOnCurrentAxis, function (item) {
  30146. minOverflow = Math.min(item.offset, minOverflow);
  30147. });
  30148. var maxOverflow = -Infinity;
  30149. each(barsOnCurrentAxis, function (item) {
  30150. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30151. });
  30152. minOverflow = Math.abs(minOverflow);
  30153. maxOverflow = Math.abs(maxOverflow);
  30154. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  30155. var oldRange = max - min;
  30156. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  30157. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  30158. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30159. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30160. return {
  30161. min: min,
  30162. max: max
  30163. };
  30164. } // Precondition of calling this method:
  30165. // The scale extent has been initailized using series data extent via
  30166. // `scale.setExtent` or `scale.unionExtentFromData`;
  30167. function niceScaleExtent(scale, model) {
  30168. var extentInfo = getScaleExtent(scale, model);
  30169. var extent = extentInfo.extent;
  30170. var splitNumber = model.get('splitNumber');
  30171. if (scale instanceof LogScale) {
  30172. scale.base = model.get('logBase');
  30173. }
  30174. var scaleType = scale.type;
  30175. scale.setExtent(extent[0], extent[1]);
  30176. scale.niceExtent({
  30177. splitNumber: splitNumber,
  30178. fixMin: extentInfo.fixMin,
  30179. fixMax: extentInfo.fixMax,
  30180. minInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('minInterval') : null,
  30181. maxInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('maxInterval') : null
  30182. }); // If some one specified the min, max. And the default calculated interval
  30183. // is not good enough. He can specify the interval. It is often appeared
  30184. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30185. // to be 60.
  30186. // FIXME
  30187. var interval = model.get('interval');
  30188. if (interval != null) {
  30189. scale.setInterval && scale.setInterval(interval);
  30190. }
  30191. }
  30192. /**
  30193. * @param axisType Default retrieve from model.type
  30194. */
  30195. function createScaleByModel(model, axisType) {
  30196. axisType = axisType || model.get('type');
  30197. if (axisType) {
  30198. switch (axisType) {
  30199. // Buildin scale
  30200. case 'category':
  30201. return new OrdinalScale({
  30202. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  30203. extent: [Infinity, -Infinity]
  30204. });
  30205. case 'time':
  30206. return new TimeScale({
  30207. locale: model.ecModel.getLocaleModel(),
  30208. useUTC: model.ecModel.get('useUTC')
  30209. });
  30210. default:
  30211. // case 'value'/'interval', 'log', or others.
  30212. return new (Scale.getClass(axisType) || IntervalScale)();
  30213. }
  30214. }
  30215. }
  30216. /**
  30217. * Check if the axis cross 0
  30218. */
  30219. function ifAxisCrossZero(axis) {
  30220. var dataExtent = axis.scale.getExtent();
  30221. var min = dataExtent[0];
  30222. var max = dataExtent[1];
  30223. return !(min > 0 && max > 0 || min < 0 && max < 0);
  30224. }
  30225. /**
  30226. * @param axis
  30227. * @return Label formatter function.
  30228. * param: {number} tickValue,
  30229. * param: {number} idx, the index in all ticks.
  30230. * If category axis, this param is not required.
  30231. * return: {string} label string.
  30232. */
  30233. function makeLabelFormatter(axis) {
  30234. var labelFormatter = axis.getLabelModel().get('formatter');
  30235. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30236. if (axis.scale.type === 'time') {
  30237. return function (tpl) {
  30238. return function (tick, idx) {
  30239. return axis.scale.getFormattedLabel(tick, idx, tpl);
  30240. };
  30241. }(labelFormatter);
  30242. } else if (typeof labelFormatter === 'string') {
  30243. return function (tpl) {
  30244. return function (tick) {
  30245. // For category axis, get raw value; for numeric axis,
  30246. // get formatted label like '1,333,444'.
  30247. var label = axis.scale.getLabel(tick);
  30248. var text = tpl.replace('{value}', label != null ? label : '');
  30249. return text;
  30250. };
  30251. }(labelFormatter);
  30252. } else if (typeof labelFormatter === 'function') {
  30253. return function (cb) {
  30254. return function (tick, idx) {
  30255. // The original intention of `idx` is "the index of the tick in all ticks".
  30256. // But the previous implementation of category axis do not consider the
  30257. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30258. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30259. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30260. // the definition here for back compatibility.
  30261. if (categoryTickStart != null) {
  30262. idx = tick.value - categoryTickStart;
  30263. }
  30264. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  30265. level: tick.level
  30266. } : null);
  30267. };
  30268. }(labelFormatter);
  30269. } else {
  30270. return function (tick) {
  30271. return axis.scale.getLabel(tick);
  30272. };
  30273. }
  30274. }
  30275. function getAxisRawValue(axis, tick) {
  30276. // In category axis with data zoom, tick is not the original
  30277. // index of axis.data. So tick should not be exposed to user
  30278. // in category axis.
  30279. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  30280. }
  30281. /**
  30282. * @param axis
  30283. * @return Be null/undefined if no labels.
  30284. */
  30285. function estimateLabelUnionRect(axis) {
  30286. var axisModel = axis.model;
  30287. var scale = axis.scale;
  30288. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  30289. return;
  30290. }
  30291. var realNumberScaleTicks;
  30292. var tickCount;
  30293. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  30294. if (scale instanceof OrdinalScale) {
  30295. tickCount = scale.count();
  30296. } else {
  30297. realNumberScaleTicks = scale.getTicks();
  30298. tickCount = realNumberScaleTicks.length;
  30299. }
  30300. var axisLabelModel = axis.getLabelModel();
  30301. var labelFormatter = makeLabelFormatter(axis);
  30302. var rect;
  30303. var step = 1; // Simple optimization for large amount of labels
  30304. if (tickCount > 40) {
  30305. step = Math.ceil(tickCount / 40);
  30306. }
  30307. for (var i = 0; i < tickCount; i += step) {
  30308. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  30309. value: categoryScaleExtent[0] + i
  30310. };
  30311. var label = labelFormatter(tick, i);
  30312. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  30313. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  30314. rect ? rect.union(singleRect) : rect = singleRect;
  30315. }
  30316. return rect;
  30317. }
  30318. function rotateTextRect(textRect, rotate) {
  30319. var rotateRadians = rotate * Math.PI / 180;
  30320. var beforeWidth = textRect.width;
  30321. var beforeHeight = textRect.height;
  30322. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  30323. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  30324. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  30325. return rotatedRect;
  30326. }
  30327. /**
  30328. * @param model axisLabelModel or axisTickModel
  30329. * @return {number|String} Can be null|'auto'|number|function
  30330. */
  30331. function getOptionCategoryInterval(model) {
  30332. var interval = model.get('interval');
  30333. return interval == null ? 'auto' : interval;
  30334. }
  30335. /**
  30336. * Set `categoryInterval` as 0 implicitly indicates that
  30337. * show all labels reguardless of overlap.
  30338. * @param {Object} axis axisModel.axis
  30339. */
  30340. function shouldShowAllLabels(axis) {
  30341. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  30342. }
  30343. function getDataDimensionsOnAxis(data, axisDim) {
  30344. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  30345. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  30346. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  30347. // there has been stacked result dim?
  30348. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  30349. // For example, the extent of the original dimension
  30350. // is [0.1, 0.5], the extent of the `stackResultDimension`
  30351. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  30352. // because there is no graphic corresponding to [0.1, 0.5].
  30353. // See the case in `test/area-stack.html` `main1`, where area line
  30354. // stack needs `yAxis` not start from 0.
  30355. dataDimMap[getStackedDimension(data, dataDim)] = true;
  30356. });
  30357. return keys(dataDimMap);
  30358. }
  30359. /*
  30360. * Licensed to the Apache Software Foundation (ASF) under one
  30361. * or more contributor license agreements. See the NOTICE file
  30362. * distributed with this work for additional information
  30363. * regarding copyright ownership. The ASF licenses this file
  30364. * to you under the Apache License, Version 2.0 (the
  30365. * "License"); you may not use this file except in compliance
  30366. * with the License. You may obtain a copy of the License at
  30367. *
  30368. * http://www.apache.org/licenses/LICENSE-2.0
  30369. *
  30370. * Unless required by applicable law or agreed to in writing,
  30371. * software distributed under the License is distributed on an
  30372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30373. * KIND, either express or implied. See the License for the
  30374. * specific language governing permissions and limitations
  30375. * under the License.
  30376. */
  30377. /**
  30378. * AUTO-GENERATED FILE. DO NOT MODIFY.
  30379. */
  30380. /*
  30381. * Licensed to the Apache Software Foundation (ASF) under one
  30382. * or more contributor license agreements. See the NOTICE file
  30383. * distributed with this work for additional information
  30384. * regarding copyright ownership. The ASF licenses this file
  30385. * to you under the Apache License, Version 2.0 (the
  30386. * "License"); you may not use this file except in compliance
  30387. * with the License. You may obtain a copy of the License at
  30388. *
  30389. * http://www.apache.org/licenses/LICENSE-2.0
  30390. *
  30391. * Unless required by applicable law or agreed to in writing,
  30392. * software distributed under the License is distributed on an
  30393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30394. * KIND, either express or implied. See the License for the
  30395. * specific language governing permissions and limitations
  30396. * under the License.
  30397. */
  30398. var AxisModelCommonMixin =
  30399. /** @class */
  30400. function () {
  30401. function AxisModelCommonMixin() {}
  30402. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  30403. var option = this.option;
  30404. return !option.scale;
  30405. };
  30406. /**
  30407. * Should be implemented by each axis model if necessary.
  30408. * @return coordinate system model
  30409. */
  30410. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  30411. return;
  30412. };
  30413. return AxisModelCommonMixin;
  30414. }();
  30415. /**
  30416. * Create a muti dimension List structure from seriesModel.
  30417. */
  30418. function createList(seriesModel) {
  30419. return createListFromArray(seriesModel.getSource(), seriesModel);
  30420. } // export function createGraph(seriesModel) {
  30421. var dataStack$1 = {
  30422. isDimensionStacked: isDimensionStacked,
  30423. enableDataStack: enableDataStack,
  30424. getStackedDimension: getStackedDimension
  30425. };
  30426. /**
  30427. * Create scale
  30428. * @param {Array.<number>} dataExtent
  30429. * @param {Object|module:echarts/Model} option If `optoin.type`
  30430. * is secified, it can only be `'value'` currently.
  30431. */
  30432. function createScale(dataExtent, option) {
  30433. var axisModel = option;
  30434. if (!(option instanceof Model)) {
  30435. axisModel = new Model(option); // FIXME
  30436. // Currently AxisModelCommonMixin has nothing to do with the
  30437. // the requirements of `axisHelper.createScaleByModel`. For
  30438. // example the method `getCategories` and `getOrdinalMeta`
  30439. // are required for `'category'` axis, and ecModel are required
  30440. // for `'time'` axis. But occationally echarts-gl happened
  30441. // to only use `'value'` axis.
  30442. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  30443. }
  30444. var scale = createScaleByModel(axisModel);
  30445. scale.setExtent(dataExtent[0], dataExtent[1]);
  30446. niceScaleExtent(scale, axisModel);
  30447. return scale;
  30448. }
  30449. /**
  30450. * Mixin common methods to axis model,
  30451. *
  30452. * Inlcude methods
  30453. * `getFormattedLabels() => Array.<string>`
  30454. * `getCategories() => Array.<string>`
  30455. * `getMin(origin: boolean) => number`
  30456. * `getMax(origin: boolean) => number`
  30457. * `getNeedCrossZero() => boolean`
  30458. */
  30459. function mixinAxisModelCommonMethods(Model) {
  30460. mixin(Model, AxisModelCommonMixin);
  30461. }
  30462. function createTextStyle$1(textStyleModel, opts) {
  30463. opts = opts || {};
  30464. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  30465. }
  30466. var helper = /*#__PURE__*/Object.freeze({
  30467. __proto__: null,
  30468. createList: createList,
  30469. getLayoutRect: getLayoutRect,
  30470. dataStack: dataStack$1,
  30471. createScale: createScale,
  30472. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  30473. getECData: getECData,
  30474. createTextStyle: createTextStyle$1,
  30475. createDimensions: createDimensions,
  30476. createSymbol: createSymbol,
  30477. enableHoverEmphasis: enableHoverEmphasis
  30478. });
  30479. var EPSILON$3 = 1e-8;
  30480. function isAroundEqual$1(a, b) {
  30481. return Math.abs(a - b) < EPSILON$3;
  30482. }
  30483. function contain$2(points, x, y) {
  30484. var w = 0;
  30485. var p = points[0];
  30486. if (!p) {
  30487. return false;
  30488. }
  30489. for (var i = 1; i < points.length; i++) {
  30490. var p2 = points[i];
  30491. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  30492. p = p2;
  30493. }
  30494. var p0 = points[0];
  30495. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  30496. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  30497. }
  30498. return w !== 0;
  30499. }
  30500. var Region =
  30501. /** @class */
  30502. function () {
  30503. function Region(name, geometries, cp) {
  30504. this.name = name;
  30505. this.geometries = geometries;
  30506. if (!cp) {
  30507. var rect = this.getBoundingRect();
  30508. cp = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  30509. } else {
  30510. cp = [cp[0], cp[1]];
  30511. }
  30512. this.center = cp;
  30513. }
  30514. Region.prototype.getBoundingRect = function () {
  30515. var rect = this._rect;
  30516. if (rect) {
  30517. return rect;
  30518. }
  30519. var MAX_NUMBER = Number.MAX_VALUE;
  30520. var min$1 = [MAX_NUMBER, MAX_NUMBER];
  30521. var max$1 = [-MAX_NUMBER, -MAX_NUMBER];
  30522. var min2 = [];
  30523. var max2 = [];
  30524. var geometries = this.geometries;
  30525. var i = 0;
  30526. for (; i < geometries.length; i++) {
  30527. // Only support polygon
  30528. if (geometries[i].type !== 'polygon') {
  30529. continue;
  30530. } // Doesn't consider hole
  30531. var exterior = geometries[i].exterior;
  30532. fromPoints(exterior, min2, max2);
  30533. min(min$1, min$1, min2);
  30534. max(max$1, max$1, max2);
  30535. } // No data
  30536. if (i === 0) {
  30537. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  30538. }
  30539. return this._rect = new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  30540. };
  30541. Region.prototype.contain = function (coord) {
  30542. var rect = this.getBoundingRect();
  30543. var geometries = this.geometries;
  30544. if (!rect.contain(coord[0], coord[1])) {
  30545. return false;
  30546. }
  30547. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  30548. // Only support polygon.
  30549. if (geometries[i].type !== 'polygon') {
  30550. continue;
  30551. }
  30552. var exterior = geometries[i].exterior;
  30553. var interiors = geometries[i].interiors;
  30554. if (contain$2(exterior, coord[0], coord[1])) {
  30555. // Not in the region if point is in the hole.
  30556. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  30557. if (contain$2(interiors[k], coord[0], coord[1])) {
  30558. continue loopGeo;
  30559. }
  30560. }
  30561. return true;
  30562. }
  30563. }
  30564. return false;
  30565. };
  30566. Region.prototype.transformTo = function (x, y, width, height) {
  30567. var rect = this.getBoundingRect();
  30568. var aspect = rect.width / rect.height;
  30569. if (!width) {
  30570. width = aspect * height;
  30571. } else if (!height) {
  30572. height = width / aspect;
  30573. }
  30574. var target = new BoundingRect(x, y, width, height);
  30575. var transform = rect.calculateTransform(target);
  30576. var geometries = this.geometries;
  30577. for (var i = 0; i < geometries.length; i++) {
  30578. // Only support polygon.
  30579. if (geometries[i].type !== 'polygon') {
  30580. continue;
  30581. }
  30582. var exterior = geometries[i].exterior;
  30583. var interiors = geometries[i].interiors;
  30584. for (var p = 0; p < exterior.length; p++) {
  30585. applyTransform(exterior[p], exterior[p], transform);
  30586. }
  30587. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  30588. for (var p = 0; p < interiors[h].length; p++) {
  30589. applyTransform(interiors[h][p], interiors[h][p], transform);
  30590. }
  30591. }
  30592. }
  30593. rect = this._rect;
  30594. rect.copy(target); // Update center
  30595. this.center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  30596. };
  30597. Region.prototype.cloneShallow = function (name) {
  30598. name == null && (name = this.name);
  30599. var newRegion = new Region(name, this.geometries, this.center);
  30600. newRegion._rect = this._rect;
  30601. newRegion.transformTo = null; // Simply avoid to be called.
  30602. return newRegion;
  30603. };
  30604. return Region;
  30605. }();
  30606. function decode(json) {
  30607. if (!json.UTF8Encoding) {
  30608. return json;
  30609. }
  30610. var jsonCompressed = json;
  30611. var encodeScale = jsonCompressed.UTF8Scale;
  30612. if (encodeScale == null) {
  30613. encodeScale = 1024;
  30614. }
  30615. var features = jsonCompressed.features;
  30616. for (var f = 0; f < features.length; f++) {
  30617. var feature = features[f];
  30618. var geometry = feature.geometry;
  30619. if (geometry.type === 'Polygon') {
  30620. var coordinates = geometry.coordinates;
  30621. for (var c = 0; c < coordinates.length; c++) {
  30622. coordinates[c] = decodePolygon(coordinates[c], geometry.encodeOffsets[c], encodeScale);
  30623. }
  30624. } else if (geometry.type === 'MultiPolygon') {
  30625. var coordinates = geometry.coordinates;
  30626. for (var c = 0; c < coordinates.length; c++) {
  30627. var coordinate = coordinates[c];
  30628. for (var c2 = 0; c2 < coordinate.length; c2++) {
  30629. coordinate[c2] = decodePolygon(coordinate[c2], geometry.encodeOffsets[c][c2], encodeScale);
  30630. }
  30631. }
  30632. }
  30633. } // Has been decoded
  30634. jsonCompressed.UTF8Encoding = false;
  30635. return jsonCompressed;
  30636. }
  30637. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  30638. var result = [];
  30639. var prevX = encodeOffsets[0];
  30640. var prevY = encodeOffsets[1];
  30641. for (var i = 0; i < coordinate.length; i += 2) {
  30642. var x = coordinate.charCodeAt(i) - 64;
  30643. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  30644. x = x >> 1 ^ -(x & 1);
  30645. y = y >> 1 ^ -(y & 1); // Delta deocding
  30646. x += prevX;
  30647. y += prevY;
  30648. prevX = x;
  30649. prevY = y; // Dequantize
  30650. result.push([x / encodeScale, y / encodeScale]);
  30651. }
  30652. return result;
  30653. }
  30654. function parseGeoJSON(geoJson, nameProperty) {
  30655. geoJson = decode(geoJson);
  30656. return map(filter(geoJson.features, function (featureObj) {
  30657. // Output of mapshaper may have geometry null
  30658. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  30659. }), function (featureObj) {
  30660. var properties = featureObj.properties;
  30661. var geo = featureObj.geometry;
  30662. var geometries = [];
  30663. if (geo.type === 'Polygon') {
  30664. var coordinates = geo.coordinates;
  30665. geometries.push({
  30666. type: 'polygon',
  30667. // According to the GeoJSON specification.
  30668. // First must be exterior, and the rest are all interior(holes).
  30669. exterior: coordinates[0],
  30670. interiors: coordinates.slice(1)
  30671. });
  30672. }
  30673. if (geo.type === 'MultiPolygon') {
  30674. var coordinates = geo.coordinates;
  30675. each(coordinates, function (item) {
  30676. if (item[0]) {
  30677. geometries.push({
  30678. type: 'polygon',
  30679. exterior: item[0],
  30680. interiors: item.slice(1)
  30681. });
  30682. }
  30683. });
  30684. }
  30685. var region = new Region(properties[nameProperty || 'name'], geometries, properties.cp);
  30686. region.properties = properties;
  30687. return region;
  30688. });
  30689. }
  30690. var number = /*#__PURE__*/Object.freeze({
  30691. __proto__: null,
  30692. linearMap: linearMap,
  30693. round: round,
  30694. asc: asc,
  30695. getPrecision: getPrecision,
  30696. getPrecisionSafe: getPrecisionSafe,
  30697. getPixelPrecision: getPixelPrecision,
  30698. getPercentWithPrecision: getPercentWithPrecision,
  30699. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  30700. remRadian: remRadian,
  30701. isRadianAroundZero: isRadianAroundZero,
  30702. parseDate: parseDate,
  30703. quantity: quantity,
  30704. quantityExponent: quantityExponent,
  30705. nice: nice,
  30706. quantile: quantile,
  30707. reformIntervals: reformIntervals,
  30708. isNumeric: isNumeric,
  30709. numericToNumber: numericToNumber
  30710. });
  30711. var time = /*#__PURE__*/Object.freeze({
  30712. __proto__: null,
  30713. parse: parseDate,
  30714. format: format
  30715. });
  30716. var graphic = /*#__PURE__*/Object.freeze({
  30717. __proto__: null,
  30718. extendShape: extendShape,
  30719. extendPath: extendPath,
  30720. makePath: makePath,
  30721. makeImage: makeImage,
  30722. mergePath: mergePath$1,
  30723. resizePath: resizePath,
  30724. createIcon: createIcon,
  30725. updateProps: updateProps,
  30726. initProps: initProps,
  30727. getTransform: getTransform,
  30728. clipPointsByRect: clipPointsByRect,
  30729. clipRectByRect: clipRectByRect,
  30730. registerShape: registerShape,
  30731. getShapeClass: getShapeClass,
  30732. Group: Group,
  30733. Image: ZRImage,
  30734. Text: ZRText,
  30735. Circle: Circle,
  30736. Ellipse: Ellipse,
  30737. Sector: Sector,
  30738. Ring: Ring,
  30739. Polygon: Polygon,
  30740. Polyline: Polyline,
  30741. Rect: Rect,
  30742. Line: Line,
  30743. BezierCurve: BezierCurve,
  30744. Arc: Arc,
  30745. IncrementalDisplayable: IncrementalDisplayable,
  30746. CompoundPath: CompoundPath,
  30747. LinearGradient: LinearGradient,
  30748. RadialGradient: RadialGradient,
  30749. BoundingRect: BoundingRect
  30750. });
  30751. var format$1 = /*#__PURE__*/Object.freeze({
  30752. __proto__: null,
  30753. addCommas: addCommas,
  30754. toCamelCase: toCamelCase,
  30755. normalizeCssArray: normalizeCssArray$1,
  30756. encodeHTML: encodeHTML,
  30757. formatTpl: formatTpl,
  30758. getTooltipMarker: getTooltipMarker,
  30759. formatTime: formatTime,
  30760. capitalFirst: capitalFirst,
  30761. truncateText: truncateText,
  30762. getTextRect: getTextRect
  30763. });
  30764. var util$1 = /*#__PURE__*/Object.freeze({
  30765. __proto__: null,
  30766. map: map,
  30767. each: each,
  30768. indexOf: indexOf,
  30769. inherits: inherits,
  30770. reduce: reduce,
  30771. filter: filter,
  30772. bind: bind,
  30773. curry: curry,
  30774. isArray: isArray,
  30775. isString: isString,
  30776. isObject: isObject,
  30777. isFunction: isFunction,
  30778. extend: extend,
  30779. defaults: defaults,
  30780. clone: clone,
  30781. merge: merge
  30782. });
  30783. var inner$4 = makeInner();
  30784. function createAxisLabels(axis) {
  30785. // Only ordinal scale support tick interval
  30786. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  30787. }
  30788. /**
  30789. * @param {module:echats/coord/Axis} axis
  30790. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  30791. * @return {Object} {
  30792. * ticks: Array.<number>
  30793. * tickCategoryInterval: number
  30794. * }
  30795. */
  30796. function createAxisTicks(axis, tickModel) {
  30797. // Only ordinal scale support tick interval
  30798. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  30799. ticks: map(axis.scale.getTicks(), function (tick) {
  30800. return tick.value;
  30801. })
  30802. };
  30803. }
  30804. function makeCategoryLabels(axis) {
  30805. var labelModel = axis.getLabelModel();
  30806. var result = makeCategoryLabelsActually(axis, labelModel);
  30807. return !labelModel.get('show') || axis.scale.isBlank() ? {
  30808. labels: [],
  30809. labelCategoryInterval: result.labelCategoryInterval
  30810. } : result;
  30811. }
  30812. function makeCategoryLabelsActually(axis, labelModel) {
  30813. var labelsCache = getListCache(axis, 'labels');
  30814. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  30815. var result = listCacheGet(labelsCache, optionLabelInterval);
  30816. if (result) {
  30817. return result;
  30818. }
  30819. var labels;
  30820. var numericLabelInterval;
  30821. if (isFunction(optionLabelInterval)) {
  30822. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  30823. } else {
  30824. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  30825. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  30826. } // Cache to avoid calling interval function repeatly.
  30827. return listCacheSet(labelsCache, optionLabelInterval, {
  30828. labels: labels,
  30829. labelCategoryInterval: numericLabelInterval
  30830. });
  30831. }
  30832. function makeCategoryTicks(axis, tickModel) {
  30833. var ticksCache = getListCache(axis, 'ticks');
  30834. var optionTickInterval = getOptionCategoryInterval(tickModel);
  30835. var result = listCacheGet(ticksCache, optionTickInterval);
  30836. if (result) {
  30837. return result;
  30838. }
  30839. var ticks;
  30840. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  30841. // we should not return all ticks.
  30842. if (!tickModel.get('show') || axis.scale.isBlank()) {
  30843. ticks = [];
  30844. }
  30845. if (isFunction(optionTickInterval)) {
  30846. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  30847. } // Always use label interval by default despite label show. Consider this
  30848. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  30849. // labels. `splitLine` and `axisTick` should be consistent in this case.
  30850. else if (optionTickInterval === 'auto') {
  30851. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  30852. tickCategoryInterval = labelsResult.labelCategoryInterval;
  30853. ticks = map(labelsResult.labels, function (labelItem) {
  30854. return labelItem.tickValue;
  30855. });
  30856. } else {
  30857. tickCategoryInterval = optionTickInterval;
  30858. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  30859. } // Cache to avoid calling interval function repeatly.
  30860. return listCacheSet(ticksCache, optionTickInterval, {
  30861. ticks: ticks,
  30862. tickCategoryInterval: tickCategoryInterval
  30863. });
  30864. }
  30865. function makeRealNumberLabels(axis) {
  30866. var ticks = axis.scale.getTicks();
  30867. var labelFormatter = makeLabelFormatter(axis);
  30868. return {
  30869. labels: map(ticks, function (tick, idx) {
  30870. return {
  30871. formattedLabel: labelFormatter(tick, idx),
  30872. rawLabel: axis.scale.getLabel(tick),
  30873. tickValue: tick.value
  30874. };
  30875. })
  30876. };
  30877. }
  30878. function getListCache(axis, prop) {
  30879. // Because key can be funciton, and cache size always be small, we use array cache.
  30880. return inner$4(axis)[prop] || (inner$4(axis)[prop] = []);
  30881. }
  30882. function listCacheGet(cache, key) {
  30883. for (var i = 0; i < cache.length; i++) {
  30884. if (cache[i].key === key) {
  30885. return cache[i].value;
  30886. }
  30887. }
  30888. }
  30889. function listCacheSet(cache, key, value) {
  30890. cache.push({
  30891. key: key,
  30892. value: value
  30893. });
  30894. return value;
  30895. }
  30896. function makeAutoCategoryInterval(axis) {
  30897. var result = inner$4(axis).autoInterval;
  30898. return result != null ? result : inner$4(axis).autoInterval = axis.calculateCategoryInterval();
  30899. }
  30900. /**
  30901. * Calculate interval for category axis ticks and labels.
  30902. * To get precise result, at least one of `getRotate` and `isHorizontal`
  30903. * should be implemented in axis.
  30904. */
  30905. function calculateCategoryInterval(axis) {
  30906. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  30907. var labelFormatter = makeLabelFormatter(axis);
  30908. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  30909. var ordinalScale = axis.scale;
  30910. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  30911. // avoid generating a long array by `getTicks`
  30912. // in large category data case.
  30913. var tickCount = ordinalScale.count();
  30914. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  30915. return 0;
  30916. }
  30917. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  30918. if (tickCount > 40) {
  30919. step = Math.max(1, Math.floor(tickCount / 40));
  30920. }
  30921. var tickValue = ordinalExtent[0];
  30922. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  30923. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  30924. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  30925. var maxW = 0;
  30926. var maxH = 0; // Caution: Performance sensitive for large category data.
  30927. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  30928. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30929. var width = 0;
  30930. var height = 0; // Not precise, do not consider align and vertical align
  30931. // and each distance from axis line yet.
  30932. var rect = getBoundingRect(labelFormatter({
  30933. value: tickValue
  30934. }), params.font, 'center', 'top'); // Magic number
  30935. width = rect.width * 1.3;
  30936. height = rect.height * 1.3; // Min size, void long loop.
  30937. maxW = Math.max(maxW, width, 7);
  30938. maxH = Math.max(maxH, height, 7);
  30939. }
  30940. var dw = maxW / unitW;
  30941. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  30942. isNaN(dw) && (dw = Infinity);
  30943. isNaN(dh) && (dh = Infinity);
  30944. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  30945. var cache = inner$4(axis.model);
  30946. var axisExtent = axis.getExtent();
  30947. var lastAutoInterval = cache.lastAutoInterval;
  30948. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  30949. // otherwise the calculated interval might jitter when the zoom
  30950. // window size is close to the interval-changing size.
  30951. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  30952. // The jitter will cause that sometimes the displayed labels are
  30953. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  30954. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  30955. // point is not the same when zooming in or zooming out.
  30956. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  30957. // be used. Otherwise some hiden labels might not be shown again.
  30958. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  30959. interval = lastAutoInterval;
  30960. } // Only update cache if cache not used, otherwise the
  30961. // changing of interval is too insensitive.
  30962. else {
  30963. cache.lastTickCount = tickCount;
  30964. cache.lastAutoInterval = interval;
  30965. cache.axisExtent0 = axisExtent[0];
  30966. cache.axisExtent1 = axisExtent[1];
  30967. }
  30968. return interval;
  30969. }
  30970. function fetchAutoCategoryIntervalCalculationParams(axis) {
  30971. var labelModel = axis.getLabelModel();
  30972. return {
  30973. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  30974. labelRotate: labelModel.get('rotate') || 0,
  30975. font: labelModel.getFont()
  30976. };
  30977. }
  30978. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  30979. var labelFormatter = makeLabelFormatter(axis);
  30980. var ordinalScale = axis.scale;
  30981. var ordinalExtent = ordinalScale.getExtent();
  30982. var labelModel = axis.getLabelModel();
  30983. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  30984. var step = Math.max((categoryInterval || 0) + 1, 1);
  30985. var startTick = ordinalExtent[0];
  30986. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  30987. // while zooming and moving while interval > 0. Otherwise the selection
  30988. // of displayable ticks and symbols probably keep changing.
  30989. // 3 is empirical value.
  30990. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  30991. startTick = Math.round(Math.ceil(startTick / step) * step);
  30992. } // (1) Only add min max label here but leave overlap checking
  30993. // to render stage, which also ensure the returned list
  30994. // suitable for splitLine and splitArea rendering.
  30995. // (2) Scales except category always contain min max label so
  30996. // do not need to perform this process.
  30997. var showAllLabel = shouldShowAllLabels(axis);
  30998. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  30999. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31000. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31001. addItem(ordinalExtent[0]);
  31002. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  31003. var tickValue = startTick;
  31004. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31005. addItem(tickValue);
  31006. }
  31007. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  31008. addItem(ordinalExtent[1]);
  31009. }
  31010. function addItem(tickValue) {
  31011. var tickObj = {
  31012. value: tickValue
  31013. };
  31014. result.push(onlyTick ? tickValue : {
  31015. formattedLabel: labelFormatter(tickObj),
  31016. rawLabel: ordinalScale.getLabel(tickObj),
  31017. tickValue: tickValue
  31018. });
  31019. }
  31020. return result;
  31021. }
  31022. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  31023. var ordinalScale = axis.scale;
  31024. var labelFormatter = makeLabelFormatter(axis);
  31025. var result = [];
  31026. each(ordinalScale.getTicks(), function (tick) {
  31027. var rawLabel = ordinalScale.getLabel(tick);
  31028. var tickValue = tick.value;
  31029. if (categoryInterval(tick.value, rawLabel)) {
  31030. result.push(onlyTick ? tickValue : {
  31031. formattedLabel: labelFormatter(tick),
  31032. rawLabel: rawLabel,
  31033. tickValue: tickValue
  31034. });
  31035. }
  31036. });
  31037. return result;
  31038. }
  31039. var NORMALIZED_EXTENT = [0, 1];
  31040. /**
  31041. * Base class of Axis.
  31042. */
  31043. var Axis =
  31044. /** @class */
  31045. function () {
  31046. function Axis(dim, scale, extent) {
  31047. this.onBand = false;
  31048. this.inverse = false;
  31049. this.dim = dim;
  31050. this.scale = scale;
  31051. this._extent = extent || [0, 0];
  31052. }
  31053. /**
  31054. * If axis extent contain given coord
  31055. */
  31056. Axis.prototype.contain = function (coord) {
  31057. var extent = this._extent;
  31058. var min = Math.min(extent[0], extent[1]);
  31059. var max = Math.max(extent[0], extent[1]);
  31060. return coord >= min && coord <= max;
  31061. };
  31062. /**
  31063. * If axis extent contain given data
  31064. */
  31065. Axis.prototype.containData = function (data) {
  31066. return this.scale.contain(data);
  31067. };
  31068. /**
  31069. * Get coord extent.
  31070. */
  31071. Axis.prototype.getExtent = function () {
  31072. return this._extent.slice();
  31073. };
  31074. /**
  31075. * Get precision used for formatting
  31076. */
  31077. Axis.prototype.getPixelPrecision = function (dataExtent) {
  31078. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  31079. };
  31080. /**
  31081. * Set coord extent
  31082. */
  31083. Axis.prototype.setExtent = function (start, end) {
  31084. var extent = this._extent;
  31085. extent[0] = start;
  31086. extent[1] = end;
  31087. };
  31088. /**
  31089. * Convert data to coord. Data is the rank if it has an ordinal scale
  31090. */
  31091. Axis.prototype.dataToCoord = function (data, clamp) {
  31092. var extent = this._extent;
  31093. var scale = this.scale;
  31094. data = scale.normalize(data);
  31095. if (this.onBand && scale.type === 'ordinal') {
  31096. extent = extent.slice();
  31097. fixExtentWithBands(extent, scale.count());
  31098. }
  31099. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  31100. };
  31101. /**
  31102. * Convert coord to data. Data is the rank if it has an ordinal scale
  31103. */
  31104. Axis.prototype.coordToData = function (coord, clamp) {
  31105. var extent = this._extent;
  31106. var scale = this.scale;
  31107. if (this.onBand && scale.type === 'ordinal') {
  31108. extent = extent.slice();
  31109. fixExtentWithBands(extent, scale.count());
  31110. }
  31111. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  31112. return this.scale.scale(t);
  31113. };
  31114. /**
  31115. * Convert pixel point to data in axis
  31116. */
  31117. Axis.prototype.pointToData = function (point, clamp) {
  31118. // Should be implemented in derived class if necessary.
  31119. return;
  31120. };
  31121. /**
  31122. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  31123. * `axis.getTicksCoords` considers `onBand`, which is used by
  31124. * `boundaryGap:true` of category axis and splitLine and splitArea.
  31125. * @param opt.tickModel default: axis.model.getModel('axisTick')
  31126. * @param opt.clamp If `true`, the first and the last
  31127. * tick must be at the axis end points. Otherwise, clip ticks
  31128. * that outside the axis extent.
  31129. */
  31130. Axis.prototype.getTicksCoords = function (opt) {
  31131. opt = opt || {};
  31132. var tickModel = opt.tickModel || this.getTickModel();
  31133. var result = createAxisTicks(this, tickModel);
  31134. var ticks = result.ticks;
  31135. var ticksCoords = map(ticks, function (tickVal) {
  31136. return {
  31137. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  31138. tickValue: tickVal
  31139. };
  31140. }, this);
  31141. var alignWithLabel = tickModel.get('alignWithLabel');
  31142. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  31143. return ticksCoords;
  31144. };
  31145. Axis.prototype.getMinorTicksCoords = function () {
  31146. if (this.scale.type === 'ordinal') {
  31147. // Category axis doesn't support minor ticks
  31148. return [];
  31149. }
  31150. var minorTickModel = this.model.getModel('minorTick');
  31151. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  31152. if (!(splitNumber > 0 && splitNumber < 100)) {
  31153. splitNumber = 5;
  31154. }
  31155. var minorTicks = this.scale.getMinorTicks(splitNumber);
  31156. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  31157. return map(minorTicksGroup, function (minorTick) {
  31158. return {
  31159. coord: this.dataToCoord(minorTick),
  31160. tickValue: minorTick
  31161. };
  31162. }, this);
  31163. }, this);
  31164. return minorTicksCoords;
  31165. };
  31166. Axis.prototype.getViewLabels = function () {
  31167. return createAxisLabels(this).labels;
  31168. };
  31169. Axis.prototype.getLabelModel = function () {
  31170. return this.model.getModel('axisLabel');
  31171. };
  31172. /**
  31173. * Notice here we only get the default tick model. For splitLine
  31174. * or splitArea, we should pass the splitLineModel or splitAreaModel
  31175. * manually when calling `getTicksCoords`.
  31176. * In GL, this method may be overrided to:
  31177. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  31178. */
  31179. Axis.prototype.getTickModel = function () {
  31180. return this.model.getModel('axisTick');
  31181. };
  31182. /**
  31183. * Get width of band
  31184. */
  31185. Axis.prototype.getBandWidth = function () {
  31186. var axisExtent = this._extent;
  31187. var dataExtent = this.scale.getExtent();
  31188. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  31189. len === 0 && (len = 1);
  31190. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  31191. return Math.abs(size) / len;
  31192. };
  31193. /**
  31194. * Only be called in category axis.
  31195. * Can be overrided, consider other axes like in 3D.
  31196. * @return Auto interval for cateogry axis tick and label
  31197. */
  31198. Axis.prototype.calculateCategoryInterval = function () {
  31199. return calculateCategoryInterval(this);
  31200. };
  31201. return Axis;
  31202. }();
  31203. function fixExtentWithBands(extent, nTick) {
  31204. var size = extent[1] - extent[0];
  31205. var len = nTick;
  31206. var margin = size / len / 2;
  31207. extent[0] += margin;
  31208. extent[1] -= margin;
  31209. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  31210. // |---1---|---2---|---3---|---4---|.
  31211. // So the displayed ticks and splitLine/splitArea should between
  31212. // each data item, otherwise cause misleading (e.g., split tow bars
  31213. // of a single data item when there are two bar series).
  31214. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  31215. // splitLine/spliteArea should layout appropriately corresponding
  31216. // to displayed labels. (So we should not use `getBandWidth` in this
  31217. // case).
  31218. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  31219. var ticksLen = ticksCoords.length;
  31220. if (!axis.onBand || alignWithLabel || !ticksLen) {
  31221. return;
  31222. }
  31223. var axisExtent = axis.getExtent();
  31224. var last;
  31225. var diffSize;
  31226. if (ticksLen === 1) {
  31227. ticksCoords[0].coord = axisExtent[0];
  31228. last = ticksCoords[1] = {
  31229. coord: axisExtent[0]
  31230. };
  31231. } else {
  31232. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  31233. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  31234. each(ticksCoords, function (ticksItem) {
  31235. ticksItem.coord -= shift_1 / 2;
  31236. });
  31237. var dataExtent = axis.scale.getExtent();
  31238. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  31239. last = {
  31240. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  31241. };
  31242. ticksCoords.push(last);
  31243. }
  31244. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  31245. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  31246. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  31247. }
  31248. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  31249. ticksCoords.unshift({
  31250. coord: axisExtent[0]
  31251. });
  31252. }
  31253. if (littleThan(axisExtent[1], last.coord)) {
  31254. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  31255. }
  31256. if (clamp && littleThan(last.coord, axisExtent[1])) {
  31257. ticksCoords.push({
  31258. coord: axisExtent[1]
  31259. });
  31260. }
  31261. function littleThan(a, b) {
  31262. // Avoid rounding error cause calculated tick coord different with extent.
  31263. // It may cause an extra unecessary tick added.
  31264. a = round(a);
  31265. b = round(b);
  31266. return inverse ? a > b : a < b;
  31267. }
  31268. }
  31269. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  31270. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  31271. // class Bar3DModel extends ComponentModel {}
  31272. // export function install(registers) { regsiters.registerComponentModel(Bar3DModel); }
  31273. // echarts.use(install);
  31274. function extendComponentModel(proto) {
  31275. var Model = ComponentModel.extend(proto);
  31276. ComponentModel.registerClass(Model);
  31277. return Model;
  31278. }
  31279. function extendComponentView(proto) {
  31280. var View = ComponentView.extend(proto);
  31281. ComponentView.registerClass(View);
  31282. return View;
  31283. }
  31284. function extendSeriesModel(proto) {
  31285. var Model = SeriesModel.extend(proto);
  31286. SeriesModel.registerClass(Model);
  31287. return Model;
  31288. }
  31289. function extendChartView(proto) {
  31290. var View = ChartView.extend(proto);
  31291. ChartView.registerClass(View);
  31292. return View;
  31293. }
  31294. function returnFalse() {
  31295. return false;
  31296. }
  31297. function createDom(id, painter, dpr) {
  31298. var newDom = createCanvas();
  31299. var width = painter.getWidth();
  31300. var height = painter.getHeight();
  31301. var newDomStyle = newDom.style;
  31302. if (newDomStyle) {
  31303. newDomStyle.position = 'absolute';
  31304. newDomStyle.left = '0';
  31305. newDomStyle.top = '0';
  31306. newDomStyle.width = width + 'px';
  31307. newDomStyle.height = height + 'px';
  31308. newDom.setAttribute('data-zr-dom-id', id);
  31309. }
  31310. newDom.width = width * dpr;
  31311. newDom.height = height * dpr;
  31312. return newDom;
  31313. }
  31314. var Layer = (function (_super) {
  31315. __extends(Layer, _super);
  31316. function Layer(id, painter, dpr) {
  31317. var _this = _super.call(this) || this;
  31318. _this.motionBlur = false;
  31319. _this.lastFrameAlpha = 0.7;
  31320. _this.dpr = 1;
  31321. _this.virtual = false;
  31322. _this.config = {};
  31323. _this.incremental = false;
  31324. _this.zlevel = 0;
  31325. _this.maxRepaintRectCount = 5;
  31326. _this.__dirty = true;
  31327. _this.__firstTimePaint = true;
  31328. _this.__used = false;
  31329. _this.__drawIndex = 0;
  31330. _this.__startIndex = 0;
  31331. _this.__endIndex = 0;
  31332. _this.__prevStartIndex = null;
  31333. _this.__prevEndIndex = null;
  31334. var dom;
  31335. dpr = dpr || devicePixelRatio;
  31336. if (typeof id === 'string') {
  31337. dom = createDom(id, painter, dpr);
  31338. }
  31339. else if (isObject(id)) {
  31340. dom = id;
  31341. id = dom.id;
  31342. }
  31343. _this.id = id;
  31344. _this.dom = dom;
  31345. var domStyle = dom.style;
  31346. if (domStyle) {
  31347. dom.onselectstart = returnFalse;
  31348. domStyle.webkitUserSelect = 'none';
  31349. domStyle.userSelect = 'none';
  31350. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  31351. domStyle['-webkit-touch-callout'] = 'none';
  31352. domStyle.padding = '0';
  31353. domStyle.margin = '0';
  31354. domStyle.borderWidth = '0';
  31355. }
  31356. _this.domBack = null;
  31357. _this.ctxBack = null;
  31358. _this.painter = painter;
  31359. _this.config = null;
  31360. _this.dpr = dpr;
  31361. return _this;
  31362. }
  31363. Layer.prototype.getElementCount = function () {
  31364. return this.__endIndex - this.__startIndex;
  31365. };
  31366. Layer.prototype.afterBrush = function () {
  31367. this.__prevStartIndex = this.__startIndex;
  31368. this.__prevEndIndex = this.__endIndex;
  31369. };
  31370. Layer.prototype.initContext = function () {
  31371. this.ctx = this.dom.getContext('2d');
  31372. this.ctx.dpr = this.dpr;
  31373. };
  31374. Layer.prototype.setUnpainted = function () {
  31375. this.__firstTimePaint = true;
  31376. };
  31377. Layer.prototype.createBackBuffer = function () {
  31378. var dpr = this.dpr;
  31379. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  31380. this.ctxBack = this.domBack.getContext('2d');
  31381. if (dpr !== 1) {
  31382. this.ctxBack.scale(dpr, dpr);
  31383. }
  31384. };
  31385. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  31386. if (this.__firstTimePaint) {
  31387. this.__firstTimePaint = false;
  31388. return null;
  31389. }
  31390. var mergedRepaintRects = [];
  31391. var maxRepaintRectCount = this.maxRepaintRectCount;
  31392. var full = false;
  31393. var pendingRect = new BoundingRect(0, 0, 0, 0);
  31394. function addRectToMergePool(rect) {
  31395. if (!rect.isFinite() || rect.isZero()) {
  31396. return;
  31397. }
  31398. if (mergedRepaintRects.length === 0) {
  31399. var boundingRect = new BoundingRect(0, 0, 0, 0);
  31400. boundingRect.copy(rect);
  31401. mergedRepaintRects.push(boundingRect);
  31402. }
  31403. else {
  31404. var isMerged = false;
  31405. var minDeltaArea = Infinity;
  31406. var bestRectToMergeIdx = 0;
  31407. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  31408. var mergedRect = mergedRepaintRects[i];
  31409. if (mergedRect.intersect(rect)) {
  31410. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  31411. pendingRect_1.copy(mergedRect);
  31412. pendingRect_1.union(rect);
  31413. mergedRepaintRects[i] = pendingRect_1;
  31414. isMerged = true;
  31415. break;
  31416. }
  31417. else if (full) {
  31418. pendingRect.copy(rect);
  31419. pendingRect.union(mergedRect);
  31420. var aArea = rect.width * rect.height;
  31421. var bArea = mergedRect.width * mergedRect.height;
  31422. var pendingArea = pendingRect.width * pendingRect.height;
  31423. var deltaArea = pendingArea - aArea - bArea;
  31424. if (deltaArea < minDeltaArea) {
  31425. minDeltaArea = deltaArea;
  31426. bestRectToMergeIdx = i;
  31427. }
  31428. }
  31429. }
  31430. if (full) {
  31431. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  31432. isMerged = true;
  31433. }
  31434. if (!isMerged) {
  31435. var boundingRect = new BoundingRect(0, 0, 0, 0);
  31436. boundingRect.copy(rect);
  31437. mergedRepaintRects.push(boundingRect);
  31438. }
  31439. if (!full) {
  31440. full = mergedRepaintRects.length >= maxRepaintRectCount;
  31441. }
  31442. }
  31443. }
  31444. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  31445. var el = displayList[i];
  31446. if (el) {
  31447. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  31448. var prevRect = el.__isRendered && ((el.__dirty & Element.REDARAW_BIT) || !shouldPaint)
  31449. ? el.getPrevPaintRect()
  31450. : null;
  31451. if (prevRect) {
  31452. addRectToMergePool(prevRect);
  31453. }
  31454. var curRect = shouldPaint && ((el.__dirty & Element.REDARAW_BIT) || !el.__isRendered)
  31455. ? el.getPaintRect()
  31456. : null;
  31457. if (curRect) {
  31458. addRectToMergePool(curRect);
  31459. }
  31460. }
  31461. }
  31462. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  31463. var el = prevList[i];
  31464. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  31465. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  31466. var prevRect = el.getPrevPaintRect();
  31467. if (prevRect) {
  31468. addRectToMergePool(prevRect);
  31469. }
  31470. }
  31471. }
  31472. var hasIntersections;
  31473. do {
  31474. hasIntersections = false;
  31475. for (var i = 0; i < mergedRepaintRects.length;) {
  31476. if (mergedRepaintRects[i].isZero()) {
  31477. mergedRepaintRects.splice(i, 1);
  31478. continue;
  31479. }
  31480. for (var j = i + 1; j < mergedRepaintRects.length;) {
  31481. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  31482. hasIntersections = true;
  31483. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  31484. mergedRepaintRects.splice(j, 1);
  31485. }
  31486. else {
  31487. j++;
  31488. }
  31489. }
  31490. i++;
  31491. }
  31492. } while (hasIntersections);
  31493. this._paintRects = mergedRepaintRects;
  31494. return mergedRepaintRects;
  31495. };
  31496. Layer.prototype.debugGetPaintRects = function () {
  31497. return (this._paintRects || []).slice();
  31498. };
  31499. Layer.prototype.resize = function (width, height) {
  31500. var dpr = this.dpr;
  31501. var dom = this.dom;
  31502. var domStyle = dom.style;
  31503. var domBack = this.domBack;
  31504. if (domStyle) {
  31505. domStyle.width = width + 'px';
  31506. domStyle.height = height + 'px';
  31507. }
  31508. dom.width = width * dpr;
  31509. dom.height = height * dpr;
  31510. if (domBack) {
  31511. domBack.width = width * dpr;
  31512. domBack.height = height * dpr;
  31513. if (dpr !== 1) {
  31514. this.ctxBack.scale(dpr, dpr);
  31515. }
  31516. }
  31517. };
  31518. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  31519. var dom = this.dom;
  31520. var ctx = this.ctx;
  31521. var width = dom.width;
  31522. var height = dom.height;
  31523. clearColor = clearColor || this.clearColor;
  31524. var haveMotionBLur = this.motionBlur && !clearAll;
  31525. var lastFrameAlpha = this.lastFrameAlpha;
  31526. var dpr = this.dpr;
  31527. var self = this;
  31528. if (haveMotionBLur) {
  31529. if (!this.domBack) {
  31530. this.createBackBuffer();
  31531. }
  31532. this.ctxBack.globalCompositeOperation = 'copy';
  31533. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  31534. }
  31535. var domBack = this.domBack;
  31536. function doClear(x, y, width, height) {
  31537. ctx.clearRect(x, y, width, height);
  31538. if (clearColor && clearColor !== 'transparent') {
  31539. var clearColorGradientOrPattern = void 0;
  31540. if (isGradientObject(clearColor)) {
  31541. clearColorGradientOrPattern = clearColor.__canvasGradient
  31542. || getCanvasGradient(ctx, clearColor, {
  31543. x: 0,
  31544. y: 0,
  31545. width: width,
  31546. height: height
  31547. });
  31548. clearColor.__canvasGradient = clearColorGradientOrPattern;
  31549. }
  31550. else if (isPatternObject(clearColor)) {
  31551. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  31552. dirty: function () {
  31553. self.setUnpainted();
  31554. self.__painter.refresh();
  31555. }
  31556. });
  31557. }
  31558. ctx.save();
  31559. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  31560. ctx.fillRect(x, y, width, height);
  31561. ctx.restore();
  31562. }
  31563. if (haveMotionBLur) {
  31564. ctx.save();
  31565. ctx.globalAlpha = lastFrameAlpha;
  31566. ctx.drawImage(domBack, x, y, width, height);
  31567. ctx.restore();
  31568. }
  31569. }
  31570. if (!repaintRects || haveMotionBLur) {
  31571. doClear(0, 0, width, height);
  31572. }
  31573. else if (repaintRects.length) {
  31574. each(repaintRects, function (rect) {
  31575. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  31576. });
  31577. }
  31578. };
  31579. return Layer;
  31580. }(Eventful));
  31581. var HOVER_LAYER_ZLEVEL = 1e5;
  31582. var CANVAS_ZLEVEL = 314159;
  31583. var EL_AFTER_INCREMENTAL_INC = 0.01;
  31584. var INCREMENTAL_INC = 0.001;
  31585. function parseInt10(val) {
  31586. return parseInt(val, 10);
  31587. }
  31588. function isLayerValid(layer) {
  31589. if (!layer) {
  31590. return false;
  31591. }
  31592. if (layer.__builtin__) {
  31593. return true;
  31594. }
  31595. if (typeof (layer.resize) !== 'function'
  31596. || typeof (layer.refresh) !== 'function') {
  31597. return false;
  31598. }
  31599. return true;
  31600. }
  31601. function createRoot(width, height) {
  31602. var domRoot = document.createElement('div');
  31603. domRoot.style.cssText = [
  31604. 'position:relative',
  31605. 'width:' + width + 'px',
  31606. 'height:' + height + 'px',
  31607. 'padding:0',
  31608. 'margin:0',
  31609. 'border-width:0'
  31610. ].join(';') + ';';
  31611. return domRoot;
  31612. }
  31613. var CanvasPainter = (function () {
  31614. function CanvasPainter(root, storage, opts, id) {
  31615. this.type = 'canvas';
  31616. this._zlevelList = [];
  31617. this._prevDisplayList = [];
  31618. this._layers = {};
  31619. this._layerConfig = {};
  31620. this._needsManuallyCompositing = false;
  31621. this.type = 'canvas';
  31622. var singleCanvas = !root.nodeName
  31623. || root.nodeName.toUpperCase() === 'CANVAS';
  31624. this._opts = opts = extend({}, opts || {});
  31625. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  31626. this._singleCanvas = singleCanvas;
  31627. this.root = root;
  31628. var rootStyle = root.style;
  31629. if (rootStyle) {
  31630. rootStyle.webkitTapHighlightColor = 'transparent';
  31631. rootStyle.webkitUserSelect = 'none';
  31632. rootStyle.userSelect = 'none';
  31633. rootStyle['-webkit-touch-callout'] = 'none';
  31634. root.innerHTML = '';
  31635. }
  31636. this.storage = storage;
  31637. var zlevelList = this._zlevelList;
  31638. this._prevDisplayList = [];
  31639. var layers = this._layers;
  31640. if (!singleCanvas) {
  31641. this._width = this._getSize(0);
  31642. this._height = this._getSize(1);
  31643. var domRoot = this._domRoot = createRoot(this._width, this._height);
  31644. root.appendChild(domRoot);
  31645. }
  31646. else {
  31647. var rootCanvas = root;
  31648. var width = rootCanvas.width;
  31649. var height = rootCanvas.height;
  31650. if (opts.width != null) {
  31651. width = opts.width;
  31652. }
  31653. if (opts.height != null) {
  31654. height = opts.height;
  31655. }
  31656. this.dpr = opts.devicePixelRatio || 1;
  31657. rootCanvas.width = width * this.dpr;
  31658. rootCanvas.height = height * this.dpr;
  31659. this._width = width;
  31660. this._height = height;
  31661. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  31662. mainLayer.__builtin__ = true;
  31663. mainLayer.initContext();
  31664. layers[CANVAS_ZLEVEL] = mainLayer;
  31665. mainLayer.zlevel = CANVAS_ZLEVEL;
  31666. zlevelList.push(CANVAS_ZLEVEL);
  31667. this._domRoot = root;
  31668. }
  31669. }
  31670. CanvasPainter.prototype.getType = function () {
  31671. return 'canvas';
  31672. };
  31673. CanvasPainter.prototype.isSingleCanvas = function () {
  31674. return this._singleCanvas;
  31675. };
  31676. CanvasPainter.prototype.getViewportRoot = function () {
  31677. return this._domRoot;
  31678. };
  31679. CanvasPainter.prototype.getViewportRootOffset = function () {
  31680. var viewportRoot = this.getViewportRoot();
  31681. if (viewportRoot) {
  31682. return {
  31683. offsetLeft: viewportRoot.offsetLeft || 0,
  31684. offsetTop: viewportRoot.offsetTop || 0
  31685. };
  31686. }
  31687. };
  31688. CanvasPainter.prototype.refresh = function (paintAll) {
  31689. var list = this.storage.getDisplayList(true);
  31690. var prevList = this._prevDisplayList;
  31691. var zlevelList = this._zlevelList;
  31692. this._redrawId = Math.random();
  31693. this._paintList(list, prevList, paintAll, this._redrawId);
  31694. for (var i = 0; i < zlevelList.length; i++) {
  31695. var z = zlevelList[i];
  31696. var layer = this._layers[z];
  31697. if (!layer.__builtin__ && layer.refresh) {
  31698. var clearColor = i === 0 ? this._backgroundColor : null;
  31699. layer.refresh(clearColor);
  31700. }
  31701. }
  31702. if (this._opts.useDirtyRect) {
  31703. this._prevDisplayList = list.slice();
  31704. }
  31705. return this;
  31706. };
  31707. CanvasPainter.prototype.refreshHover = function () {
  31708. this._paintHoverList(this.storage.getDisplayList(false));
  31709. };
  31710. CanvasPainter.prototype._paintHoverList = function (list) {
  31711. var len = list.length;
  31712. var hoverLayer = this._hoverlayer;
  31713. hoverLayer && hoverLayer.clear();
  31714. if (!len) {
  31715. return;
  31716. }
  31717. var scope = {
  31718. inHover: true,
  31719. viewWidth: this._width,
  31720. viewHeight: this._height
  31721. };
  31722. var ctx;
  31723. for (var i = 0; i < len; i++) {
  31724. var el = list[i];
  31725. if (el.__inHover) {
  31726. if (!hoverLayer) {
  31727. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  31728. }
  31729. if (!ctx) {
  31730. ctx = hoverLayer.ctx;
  31731. ctx.save();
  31732. }
  31733. brush(ctx, el, scope, i === len - 1);
  31734. }
  31735. }
  31736. if (ctx) {
  31737. ctx.restore();
  31738. }
  31739. };
  31740. CanvasPainter.prototype.getHoverLayer = function () {
  31741. return this.getLayer(HOVER_LAYER_ZLEVEL);
  31742. };
  31743. CanvasPainter.prototype.paintOne = function (ctx, el) {
  31744. brushSingle(ctx, el);
  31745. };
  31746. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  31747. if (this._redrawId !== redrawId) {
  31748. return;
  31749. }
  31750. paintAll = paintAll || false;
  31751. this._updateLayerStatus(list);
  31752. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  31753. if (this._needsManuallyCompositing) {
  31754. this._compositeManually();
  31755. }
  31756. if (needsRefreshHover) {
  31757. this._paintHoverList(list);
  31758. }
  31759. if (!finished) {
  31760. var self_1 = this;
  31761. requestAnimationFrame$1(function () {
  31762. self_1._paintList(list, prevList, paintAll, redrawId);
  31763. });
  31764. }
  31765. else {
  31766. this.eachLayer(function (layer) {
  31767. layer.afterBrush && layer.afterBrush();
  31768. });
  31769. }
  31770. };
  31771. CanvasPainter.prototype._compositeManually = function () {
  31772. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  31773. var width = this._domRoot.width;
  31774. var height = this._domRoot.height;
  31775. ctx.clearRect(0, 0, width, height);
  31776. this.eachBuiltinLayer(function (layer) {
  31777. if (layer.virtual) {
  31778. ctx.drawImage(layer.dom, 0, 0, width, height);
  31779. }
  31780. });
  31781. };
  31782. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  31783. var _this = this;
  31784. var layerList = [];
  31785. var useDirtyRect = this._opts.useDirtyRect;
  31786. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  31787. var zlevel = this._zlevelList[zi];
  31788. var layer = this._layers[zlevel];
  31789. if (layer.__builtin__
  31790. && layer !== this._hoverlayer
  31791. && (layer.__dirty || paintAll)) {
  31792. layerList.push(layer);
  31793. }
  31794. }
  31795. var finished = true;
  31796. var needsRefreshHover = false;
  31797. var _loop_1 = function (k) {
  31798. var layer = layerList[k];
  31799. var ctx = layer.ctx;
  31800. var repaintRects = useDirtyRect
  31801. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  31802. ctx.save();
  31803. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  31804. var useTimer = !paintAll && layer.incremental && Date.now;
  31805. var startTime = useTimer && Date.now();
  31806. var clearColor = layer.zlevel === this_1._zlevelList[0]
  31807. ? this_1._backgroundColor : null;
  31808. if (layer.__startIndex === layer.__endIndex) {
  31809. layer.clear(false, clearColor, repaintRects);
  31810. }
  31811. else if (start === layer.__startIndex) {
  31812. var firstEl = list[start];
  31813. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  31814. layer.clear(false, clearColor, repaintRects);
  31815. }
  31816. }
  31817. if (start === -1) {
  31818. console.error('For some unknown reason. drawIndex is -1');
  31819. start = layer.__startIndex;
  31820. }
  31821. var i;
  31822. var repaint = function (repaintRect) {
  31823. var scope = {
  31824. inHover: false,
  31825. allClipped: false,
  31826. prevEl: null,
  31827. viewWidth: _this._width,
  31828. viewHeight: _this._height
  31829. };
  31830. for (i = start; i < layer.__endIndex; i++) {
  31831. var el = list[i];
  31832. if (el.__inHover) {
  31833. needsRefreshHover = true;
  31834. }
  31835. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  31836. if (useTimer) {
  31837. var dTime = Date.now() - startTime;
  31838. if (dTime > 15) {
  31839. break;
  31840. }
  31841. }
  31842. }
  31843. if (scope.prevElClipPaths) {
  31844. ctx.restore();
  31845. }
  31846. };
  31847. if (repaintRects) {
  31848. if (repaintRects.length === 0) {
  31849. i = layer.__endIndex;
  31850. }
  31851. else {
  31852. var dpr = this_1.dpr;
  31853. for (var r = 0; r < repaintRects.length; ++r) {
  31854. var rect = repaintRects[r];
  31855. ctx.save();
  31856. ctx.beginPath();
  31857. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  31858. ctx.clip();
  31859. repaint(rect);
  31860. ctx.restore();
  31861. }
  31862. }
  31863. }
  31864. else {
  31865. ctx.save();
  31866. repaint();
  31867. ctx.restore();
  31868. }
  31869. layer.__drawIndex = i;
  31870. if (layer.__drawIndex < layer.__endIndex) {
  31871. finished = false;
  31872. }
  31873. };
  31874. var this_1 = this;
  31875. for (var k = 0; k < layerList.length; k++) {
  31876. _loop_1(k);
  31877. }
  31878. if (env.wxa) {
  31879. each(this._layers, function (layer) {
  31880. if (layer && layer.ctx && layer.ctx.draw) {
  31881. layer.ctx.draw();
  31882. }
  31883. });
  31884. }
  31885. return {
  31886. finished: finished,
  31887. needsRefreshHover: needsRefreshHover
  31888. };
  31889. };
  31890. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  31891. var ctx = currentLayer.ctx;
  31892. if (useDirtyRect) {
  31893. var paintRect = el.getPaintRect();
  31894. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  31895. brush(ctx, el, scope, isLast);
  31896. el.setPrevPaintRect(paintRect);
  31897. }
  31898. }
  31899. else {
  31900. brush(ctx, el, scope, isLast);
  31901. }
  31902. };
  31903. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  31904. if (this._singleCanvas && !this._needsManuallyCompositing) {
  31905. zlevel = CANVAS_ZLEVEL;
  31906. }
  31907. var layer = this._layers[zlevel];
  31908. if (!layer) {
  31909. layer = new Layer('zr_' + zlevel, this, this.dpr);
  31910. layer.zlevel = zlevel;
  31911. layer.__builtin__ = true;
  31912. if (this._layerConfig[zlevel]) {
  31913. merge(layer, this._layerConfig[zlevel], true);
  31914. }
  31915. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  31916. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  31917. }
  31918. if (virtual) {
  31919. layer.virtual = virtual;
  31920. }
  31921. this.insertLayer(zlevel, layer);
  31922. layer.initContext();
  31923. }
  31924. return layer;
  31925. };
  31926. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  31927. var layersMap = this._layers;
  31928. var zlevelList = this._zlevelList;
  31929. var len = zlevelList.length;
  31930. var domRoot = this._domRoot;
  31931. var prevLayer = null;
  31932. var i = -1;
  31933. if (layersMap[zlevel]) {
  31934. logError('ZLevel ' + zlevel + ' has been used already');
  31935. return;
  31936. }
  31937. if (!isLayerValid(layer)) {
  31938. logError('Layer of zlevel ' + zlevel + ' is not valid');
  31939. return;
  31940. }
  31941. if (len > 0 && zlevel > zlevelList[0]) {
  31942. for (i = 0; i < len - 1; i++) {
  31943. if (zlevelList[i] < zlevel
  31944. && zlevelList[i + 1] > zlevel) {
  31945. break;
  31946. }
  31947. }
  31948. prevLayer = layersMap[zlevelList[i]];
  31949. }
  31950. zlevelList.splice(i + 1, 0, zlevel);
  31951. layersMap[zlevel] = layer;
  31952. if (!layer.virtual) {
  31953. if (prevLayer) {
  31954. var prevDom = prevLayer.dom;
  31955. if (prevDom.nextSibling) {
  31956. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  31957. }
  31958. else {
  31959. domRoot.appendChild(layer.dom);
  31960. }
  31961. }
  31962. else {
  31963. if (domRoot.firstChild) {
  31964. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  31965. }
  31966. else {
  31967. domRoot.appendChild(layer.dom);
  31968. }
  31969. }
  31970. }
  31971. layer.__painter = this;
  31972. };
  31973. CanvasPainter.prototype.eachLayer = function (cb, context) {
  31974. var zlevelList = this._zlevelList;
  31975. for (var i = 0; i < zlevelList.length; i++) {
  31976. var z = zlevelList[i];
  31977. cb.call(context, this._layers[z], z);
  31978. }
  31979. };
  31980. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  31981. var zlevelList = this._zlevelList;
  31982. for (var i = 0; i < zlevelList.length; i++) {
  31983. var z = zlevelList[i];
  31984. var layer = this._layers[z];
  31985. if (layer.__builtin__) {
  31986. cb.call(context, layer, z);
  31987. }
  31988. }
  31989. };
  31990. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  31991. var zlevelList = this._zlevelList;
  31992. for (var i = 0; i < zlevelList.length; i++) {
  31993. var z = zlevelList[i];
  31994. var layer = this._layers[z];
  31995. if (!layer.__builtin__) {
  31996. cb.call(context, layer, z);
  31997. }
  31998. }
  31999. };
  32000. CanvasPainter.prototype.getLayers = function () {
  32001. return this._layers;
  32002. };
  32003. CanvasPainter.prototype._updateLayerStatus = function (list) {
  32004. this.eachBuiltinLayer(function (layer, z) {
  32005. layer.__dirty = layer.__used = false;
  32006. });
  32007. function updatePrevLayer(idx) {
  32008. if (prevLayer) {
  32009. if (prevLayer.__endIndex !== idx) {
  32010. prevLayer.__dirty = true;
  32011. }
  32012. prevLayer.__endIndex = idx;
  32013. }
  32014. }
  32015. if (this._singleCanvas) {
  32016. for (var i_1 = 1; i_1 < list.length; i_1++) {
  32017. var el = list[i_1];
  32018. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  32019. this._needsManuallyCompositing = true;
  32020. break;
  32021. }
  32022. }
  32023. }
  32024. var prevLayer = null;
  32025. var incrementalLayerCount = 0;
  32026. var prevZlevel;
  32027. var i;
  32028. for (i = 0; i < list.length; i++) {
  32029. var el = list[i];
  32030. var zlevel = el.zlevel;
  32031. var layer = void 0;
  32032. if (prevZlevel !== zlevel) {
  32033. prevZlevel = zlevel;
  32034. incrementalLayerCount = 0;
  32035. }
  32036. if (el.incremental) {
  32037. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  32038. layer.incremental = true;
  32039. incrementalLayerCount = 1;
  32040. }
  32041. else {
  32042. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  32043. }
  32044. if (!layer.__builtin__) {
  32045. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  32046. }
  32047. if (layer !== prevLayer) {
  32048. layer.__used = true;
  32049. if (layer.__startIndex !== i) {
  32050. layer.__dirty = true;
  32051. }
  32052. layer.__startIndex = i;
  32053. if (!layer.incremental) {
  32054. layer.__drawIndex = i;
  32055. }
  32056. else {
  32057. layer.__drawIndex = -1;
  32058. }
  32059. updatePrevLayer(i);
  32060. prevLayer = layer;
  32061. }
  32062. if ((el.__dirty & Element.REDARAW_BIT) && !el.__inHover) {
  32063. layer.__dirty = true;
  32064. if (layer.incremental && layer.__drawIndex < 0) {
  32065. layer.__drawIndex = i;
  32066. }
  32067. }
  32068. }
  32069. updatePrevLayer(i);
  32070. this.eachBuiltinLayer(function (layer, z) {
  32071. if (!layer.__used && layer.getElementCount() > 0) {
  32072. layer.__dirty = true;
  32073. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  32074. }
  32075. if (layer.__dirty && layer.__drawIndex < 0) {
  32076. layer.__drawIndex = layer.__startIndex;
  32077. }
  32078. });
  32079. };
  32080. CanvasPainter.prototype.clear = function () {
  32081. this.eachBuiltinLayer(this._clearLayer);
  32082. return this;
  32083. };
  32084. CanvasPainter.prototype._clearLayer = function (layer) {
  32085. layer.clear();
  32086. };
  32087. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  32088. this._backgroundColor = backgroundColor;
  32089. each(this._layers, function (layer) {
  32090. layer.setUnpainted();
  32091. });
  32092. };
  32093. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  32094. if (config) {
  32095. var layerConfig = this._layerConfig;
  32096. if (!layerConfig[zlevel]) {
  32097. layerConfig[zlevel] = config;
  32098. }
  32099. else {
  32100. merge(layerConfig[zlevel], config, true);
  32101. }
  32102. for (var i = 0; i < this._zlevelList.length; i++) {
  32103. var _zlevel = this._zlevelList[i];
  32104. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  32105. var layer = this._layers[_zlevel];
  32106. merge(layer, layerConfig[zlevel], true);
  32107. }
  32108. }
  32109. }
  32110. };
  32111. CanvasPainter.prototype.delLayer = function (zlevel) {
  32112. var layers = this._layers;
  32113. var zlevelList = this._zlevelList;
  32114. var layer = layers[zlevel];
  32115. if (!layer) {
  32116. return;
  32117. }
  32118. layer.dom.parentNode.removeChild(layer.dom);
  32119. delete layers[zlevel];
  32120. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  32121. };
  32122. CanvasPainter.prototype.resize = function (width, height) {
  32123. if (!this._domRoot.style) {
  32124. if (width == null || height == null) {
  32125. return;
  32126. }
  32127. this._width = width;
  32128. this._height = height;
  32129. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  32130. }
  32131. else {
  32132. var domRoot = this._domRoot;
  32133. domRoot.style.display = 'none';
  32134. var opts = this._opts;
  32135. width != null && (opts.width = width);
  32136. height != null && (opts.height = height);
  32137. width = this._getSize(0);
  32138. height = this._getSize(1);
  32139. domRoot.style.display = '';
  32140. if (this._width !== width || height !== this._height) {
  32141. domRoot.style.width = width + 'px';
  32142. domRoot.style.height = height + 'px';
  32143. for (var id in this._layers) {
  32144. if (this._layers.hasOwnProperty(id)) {
  32145. this._layers[id].resize(width, height);
  32146. }
  32147. }
  32148. this.refresh(true);
  32149. }
  32150. this._width = width;
  32151. this._height = height;
  32152. }
  32153. return this;
  32154. };
  32155. CanvasPainter.prototype.clearLayer = function (zlevel) {
  32156. var layer = this._layers[zlevel];
  32157. if (layer) {
  32158. layer.clear();
  32159. }
  32160. };
  32161. CanvasPainter.prototype.dispose = function () {
  32162. this.root.innerHTML = '';
  32163. this.root =
  32164. this.storage =
  32165. this._domRoot =
  32166. this._layers = null;
  32167. };
  32168. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  32169. opts = opts || {};
  32170. if (this._singleCanvas && !this._compositeManually) {
  32171. return this._layers[CANVAS_ZLEVEL].dom;
  32172. }
  32173. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  32174. imageLayer.initContext();
  32175. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  32176. var ctx = imageLayer.ctx;
  32177. if (opts.pixelRatio <= this.dpr) {
  32178. this.refresh();
  32179. var width_1 = imageLayer.dom.width;
  32180. var height_1 = imageLayer.dom.height;
  32181. this.eachLayer(function (layer) {
  32182. if (layer.__builtin__) {
  32183. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  32184. }
  32185. else if (layer.renderToCanvas) {
  32186. ctx.save();
  32187. layer.renderToCanvas(ctx);
  32188. ctx.restore();
  32189. }
  32190. });
  32191. }
  32192. else {
  32193. var scope = {
  32194. inHover: false,
  32195. viewWidth: this._width,
  32196. viewHeight: this._height
  32197. };
  32198. var displayList = this.storage.getDisplayList(true);
  32199. for (var i = 0, len = displayList.length; i < len; i++) {
  32200. var el = displayList[i];
  32201. brush(ctx, el, scope, i === len - 1);
  32202. }
  32203. }
  32204. return imageLayer.dom;
  32205. };
  32206. CanvasPainter.prototype.getWidth = function () {
  32207. return this._width;
  32208. };
  32209. CanvasPainter.prototype.getHeight = function () {
  32210. return this._height;
  32211. };
  32212. CanvasPainter.prototype._getSize = function (whIdx) {
  32213. var opts = this._opts;
  32214. var wh = ['width', 'height'][whIdx];
  32215. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  32216. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  32217. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  32218. if (opts[wh] != null && opts[wh] !== 'auto') {
  32219. return parseFloat(opts[wh]);
  32220. }
  32221. var root = this.root;
  32222. var stl = document.defaultView.getComputedStyle(root);
  32223. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  32224. - (parseInt10(stl[plt]) || 0)
  32225. - (parseInt10(stl[prb]) || 0)) | 0;
  32226. };
  32227. CanvasPainter.prototype.pathToImage = function (path, dpr) {
  32228. dpr = dpr || this.dpr;
  32229. var canvas = document.createElement('canvas');
  32230. var ctx = canvas.getContext('2d');
  32231. var rect = path.getBoundingRect();
  32232. var style = path.style;
  32233. var shadowBlurSize = style.shadowBlur * dpr;
  32234. var shadowOffsetX = style.shadowOffsetX * dpr;
  32235. var shadowOffsetY = style.shadowOffsetY * dpr;
  32236. var lineWidth = path.hasStroke() ? style.lineWidth : 0;
  32237. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  32238. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  32239. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  32240. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  32241. var width = rect.width + leftMargin + rightMargin;
  32242. var height = rect.height + topMargin + bottomMargin;
  32243. canvas.width = width * dpr;
  32244. canvas.height = height * dpr;
  32245. ctx.scale(dpr, dpr);
  32246. ctx.clearRect(0, 0, width, height);
  32247. ctx.dpr = dpr;
  32248. var pathTransform = {
  32249. x: path.x,
  32250. y: path.y,
  32251. scaleX: path.scaleX,
  32252. scaleY: path.scaleY,
  32253. rotation: path.rotation,
  32254. originX: path.originX,
  32255. originY: path.originY
  32256. };
  32257. path.x = leftMargin - rect.x;
  32258. path.y = topMargin - rect.y;
  32259. path.rotation = 0;
  32260. path.scaleX = 1;
  32261. path.scaleY = 1;
  32262. path.updateTransform();
  32263. if (path) {
  32264. brush(ctx, path, {
  32265. inHover: false,
  32266. viewWidth: this._width,
  32267. viewHeight: this._height
  32268. }, true);
  32269. }
  32270. var imgShape = new ZRImage({
  32271. style: {
  32272. x: 0,
  32273. y: 0,
  32274. image: canvas
  32275. }
  32276. });
  32277. extend(path, pathTransform);
  32278. return imgShape;
  32279. };
  32280. return CanvasPainter;
  32281. }());
  32282. function install(registers) {
  32283. registers.registerPainter('canvas', CanvasPainter);
  32284. }
  32285. var LineSeriesModel =
  32286. /** @class */
  32287. function (_super) {
  32288. __extends(LineSeriesModel, _super);
  32289. function LineSeriesModel() {
  32290. var _this = _super !== null && _super.apply(this, arguments) || this;
  32291. _this.type = LineSeriesModel.type;
  32292. _this.hasSymbolVisual = true;
  32293. _this.legendSymbol = 'line';
  32294. return _this;
  32295. }
  32296. LineSeriesModel.prototype.getInitialData = function (option) {
  32297. if ("development" !== 'production') {
  32298. var coordSys = option.coordinateSystem;
  32299. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32300. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32301. }
  32302. }
  32303. return createListFromArray(this.getSource(), this, {
  32304. useEncodeDefaulter: true
  32305. });
  32306. };
  32307. LineSeriesModel.type = 'series.line';
  32308. LineSeriesModel.dependencies = ['grid', 'polar'];
  32309. LineSeriesModel.defaultOption = {
  32310. zlevel: 0,
  32311. z: 3,
  32312. coordinateSystem: 'cartesian2d',
  32313. legendHoverLink: true,
  32314. clip: true,
  32315. label: {
  32316. position: 'top'
  32317. },
  32318. endLabel: {
  32319. show: false,
  32320. valueAnimation: true,
  32321. distance: 8
  32322. },
  32323. lineStyle: {
  32324. width: 2,
  32325. type: 'solid'
  32326. },
  32327. emphasis: {
  32328. scale: true,
  32329. lineStyle: {
  32330. width: 'bolder'
  32331. }
  32332. },
  32333. // areaStyle: {
  32334. // origin of areaStyle. Valid values:
  32335. // `'auto'/null/undefined`: from axisLine to data
  32336. // `'start'`: from min to data
  32337. // `'end'`: from data to max
  32338. // origin: 'auto'
  32339. // },
  32340. // false, 'start', 'end', 'middle'
  32341. step: false,
  32342. // Disabled if step is true
  32343. smooth: false,
  32344. smoothMonotone: null,
  32345. symbol: 'emptyCircle',
  32346. symbolSize: 4,
  32347. symbolRotate: null,
  32348. showSymbol: true,
  32349. // `false`: follow the label interval strategy.
  32350. // `true`: show all symbols.
  32351. // `'auto'`: If possible, show all symbols, otherwise
  32352. // follow the label interval strategy.
  32353. showAllSymbol: 'auto',
  32354. // Whether to connect break point.
  32355. connectNulls: false,
  32356. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  32357. sampling: 'none',
  32358. animationEasing: 'linear',
  32359. // Disable progressive
  32360. progressive: 0,
  32361. hoverLayerThreshold: Infinity
  32362. };
  32363. return LineSeriesModel;
  32364. }(SeriesModel);
  32365. /**
  32366. * @return label string. Not null/undefined
  32367. */
  32368. function getDefaultLabel(data, dataIndex) {
  32369. var labelDims = data.mapDimensionsAll('defaultedLabel');
  32370. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  32371. if (len === 1) {
  32372. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  32373. return rawVal != null ? rawVal + '' : null;
  32374. } else if (len) {
  32375. var vals = [];
  32376. for (var i = 0; i < labelDims.length; i++) {
  32377. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  32378. }
  32379. return vals.join(' ');
  32380. }
  32381. }
  32382. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  32383. var labelDims = data.mapDimensionsAll('defaultedLabel');
  32384. if (!isArray(interpolatedValue)) {
  32385. return interpolatedValue + '';
  32386. }
  32387. var vals = [];
  32388. for (var i = 0; i < labelDims.length; i++) {
  32389. var dimInfo = data.getDimensionInfo(labelDims[i]);
  32390. if (dimInfo) {
  32391. vals.push(interpolatedValue[dimInfo.index]);
  32392. }
  32393. }
  32394. return vals.join(' ');
  32395. }
  32396. var Symbol =
  32397. /** @class */
  32398. function (_super) {
  32399. __extends(Symbol, _super);
  32400. function Symbol(data, idx, seriesScope, opts) {
  32401. var _this = _super.call(this) || this;
  32402. _this.updateData(data, idx, seriesScope, opts);
  32403. return _this;
  32404. }
  32405. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  32406. // Remove paths created before
  32407. this.removeAll(); // let symbolPath = createSymbol(
  32408. // symbolType, -0.5, -0.5, 1, 1, color
  32409. // );
  32410. // If width/height are set too small (e.g., set to 1) on ios10
  32411. // and macOS Sierra, a circle stroke become a rect, no matter what
  32412. // the scale is set. So we set width/height as 2. See #4150.
  32413. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  32414. symbolPath.attr({
  32415. z2: 100,
  32416. culling: true,
  32417. scaleX: symbolSize[0] / 2,
  32418. scaleY: symbolSize[1] / 2
  32419. }); // Rewrite drift method
  32420. symbolPath.drift = driftSymbol;
  32421. this._symbolType = symbolType;
  32422. this.add(symbolPath);
  32423. };
  32424. /**
  32425. * Stop animation
  32426. * @param {boolean} toLastFrame
  32427. */
  32428. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  32429. this.childAt(0).stopAnimation(null, toLastFrame);
  32430. };
  32431. /**
  32432. * FIXME:
  32433. * Caution: This method breaks the encapsulation of this module,
  32434. * but it indeed brings convenience. So do not use the method
  32435. * unless you detailedly know all the implements of `Symbol`,
  32436. * especially animation.
  32437. *
  32438. * Get symbol path element.
  32439. */
  32440. Symbol.prototype.getSymbolPath = function () {
  32441. return this.childAt(0);
  32442. };
  32443. /**
  32444. * Highlight symbol
  32445. */
  32446. Symbol.prototype.highlight = function () {
  32447. enterEmphasis(this.childAt(0));
  32448. };
  32449. /**
  32450. * Downplay symbol
  32451. */
  32452. Symbol.prototype.downplay = function () {
  32453. leaveEmphasis(this.childAt(0));
  32454. };
  32455. /**
  32456. * @param {number} zlevel
  32457. * @param {number} z
  32458. */
  32459. Symbol.prototype.setZ = function (zlevel, z) {
  32460. var symbolPath = this.childAt(0);
  32461. symbolPath.zlevel = zlevel;
  32462. symbolPath.z = z;
  32463. };
  32464. Symbol.prototype.setDraggable = function (draggable) {
  32465. var symbolPath = this.childAt(0);
  32466. symbolPath.draggable = draggable;
  32467. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32468. };
  32469. /**
  32470. * Update symbol properties
  32471. */
  32472. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  32473. this.silent = false;
  32474. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32475. var seriesModel = data.hostModel;
  32476. var symbolSize = Symbol.getSymbolSize(data, idx);
  32477. var isInit = symbolType !== this._symbolType;
  32478. var disableAnimation = opts && opts.disableAnimation;
  32479. if (isInit) {
  32480. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32481. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32482. } else {
  32483. var symbolPath = this.childAt(0);
  32484. symbolPath.silent = false;
  32485. var target = {
  32486. scaleX: symbolSize[0] / 2,
  32487. scaleY: symbolSize[1] / 2
  32488. };
  32489. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  32490. }
  32491. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  32492. if (isInit) {
  32493. var symbolPath = this.childAt(0);
  32494. if (!disableAnimation) {
  32495. var target = {
  32496. scaleX: this._sizeX,
  32497. scaleY: this._sizeY,
  32498. style: {
  32499. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  32500. opacity: symbolPath.style.opacity
  32501. }
  32502. };
  32503. symbolPath.scaleX = symbolPath.scaleY = 0;
  32504. symbolPath.style.opacity = 0;
  32505. initProps(symbolPath, target, seriesModel, idx);
  32506. }
  32507. }
  32508. if (disableAnimation) {
  32509. // Must stop remove animation manually if don't call initProps or updateProps.
  32510. this.childAt(0).stopAnimation('remove');
  32511. }
  32512. this._seriesModel = seriesModel;
  32513. };
  32514. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  32515. var symbolPath = this.childAt(0);
  32516. var seriesModel = data.hostModel;
  32517. var emphasisItemStyle;
  32518. var blurItemStyle;
  32519. var selectItemStyle;
  32520. var focus;
  32521. var blurScope;
  32522. var symbolOffset;
  32523. var labelStatesModels;
  32524. var hoverScale;
  32525. var cursorStyle;
  32526. if (seriesScope) {
  32527. emphasisItemStyle = seriesScope.emphasisItemStyle;
  32528. blurItemStyle = seriesScope.blurItemStyle;
  32529. selectItemStyle = seriesScope.selectItemStyle;
  32530. focus = seriesScope.focus;
  32531. blurScope = seriesScope.blurScope;
  32532. symbolOffset = seriesScope.symbolOffset;
  32533. labelStatesModels = seriesScope.labelStatesModels;
  32534. hoverScale = seriesScope.hoverScale;
  32535. cursorStyle = seriesScope.cursorStyle;
  32536. }
  32537. if (!seriesScope || data.hasItemOption) {
  32538. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  32539. var emphasisModel = itemModel.getModel('emphasis');
  32540. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  32541. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  32542. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  32543. focus = emphasisModel.get('focus');
  32544. blurScope = emphasisModel.get('blurScope');
  32545. symbolOffset = itemModel.getShallow('symbolOffset');
  32546. labelStatesModels = getLabelStatesModels(itemModel);
  32547. hoverScale = emphasisModel.getShallow('scale');
  32548. cursorStyle = itemModel.getShallow('cursor');
  32549. }
  32550. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  32551. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32552. if (symbolOffset) {
  32553. symbolPath.x = parsePercent$1(symbolOffset[0], symbolSize[0]);
  32554. symbolPath.y = parsePercent$1(symbolOffset[1], symbolSize[1]);
  32555. }
  32556. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  32557. var symbolStyle = data.getItemVisual(idx, 'style');
  32558. var visualColor = symbolStyle.fill;
  32559. if (symbolPath instanceof ZRImage) {
  32560. var pathStyle = symbolPath.style;
  32561. symbolPath.useStyle(extend({
  32562. // TODO other properties like x, y ?
  32563. image: pathStyle.image,
  32564. x: pathStyle.x,
  32565. y: pathStyle.y,
  32566. width: pathStyle.width,
  32567. height: pathStyle.height
  32568. }, symbolStyle));
  32569. } else {
  32570. if (symbolPath.__isEmptyBrush) {
  32571. // fill and stroke will be swapped if it's empty.
  32572. // So we cloned a new style to avoid it affecting the original style in visual storage.
  32573. // TODO Better implementation. No empty logic!
  32574. symbolPath.useStyle(extend({}, symbolStyle));
  32575. } else {
  32576. symbolPath.useStyle(symbolStyle);
  32577. } // Disable decal because symbol scale will been applied on the decal.
  32578. symbolPath.style.decal = null;
  32579. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  32580. symbolPath.style.strokeNoScale = true;
  32581. }
  32582. var liftZ = data.getItemVisual(idx, 'liftZ');
  32583. var z2Origin = this._z2;
  32584. if (liftZ != null) {
  32585. if (z2Origin == null) {
  32586. this._z2 = symbolPath.z2;
  32587. symbolPath.z2 += liftZ;
  32588. }
  32589. } else if (z2Origin != null) {
  32590. symbolPath.z2 = z2Origin;
  32591. this._z2 = null;
  32592. }
  32593. var useNameLabel = opts && opts.useNameLabel;
  32594. setLabelStyle(symbolPath, labelStatesModels, {
  32595. labelFetcher: seriesModel,
  32596. labelDataIndex: idx,
  32597. defaultText: getLabelDefaultText,
  32598. inheritColor: visualColor,
  32599. defaultOpacity: symbolStyle.opacity
  32600. }); // Do not execute util needed.
  32601. function getLabelDefaultText(idx) {
  32602. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  32603. }
  32604. this._sizeX = symbolSize[0] / 2;
  32605. this._sizeY = symbolSize[1] / 2;
  32606. var emphasisState = symbolPath.ensureState('emphasis');
  32607. emphasisState.style = emphasisItemStyle;
  32608. symbolPath.ensureState('select').style = selectItemStyle;
  32609. symbolPath.ensureState('blur').style = blurItemStyle;
  32610. if (hoverScale) {
  32611. var scaleRatio = Math.max(1.1, 3 / this._sizeY);
  32612. emphasisState.scaleX = this._sizeX * scaleRatio;
  32613. emphasisState.scaleY = this._sizeY * scaleRatio;
  32614. }
  32615. this.setSymbolScale(1);
  32616. enableHoverEmphasis(this, focus, blurScope);
  32617. };
  32618. Symbol.prototype.setSymbolScale = function (scale) {
  32619. this.scaleX = this.scaleY = scale;
  32620. };
  32621. Symbol.prototype.fadeOut = function (cb, opt) {
  32622. var symbolPath = this.childAt(0);
  32623. var seriesModel = this._seriesModel;
  32624. var dataIndex = getECData(this).dataIndex;
  32625. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  32626. this.silent = symbolPath.silent = true; // Not show text when animating
  32627. if (opt && opt.fadeLabel) {
  32628. var textContent = symbolPath.getTextContent();
  32629. if (textContent) {
  32630. removeElement(textContent, {
  32631. style: {
  32632. opacity: 0
  32633. }
  32634. }, seriesModel, {
  32635. dataIndex: dataIndex,
  32636. removeOpt: animationOpt,
  32637. cb: function () {
  32638. symbolPath.removeTextContent();
  32639. }
  32640. });
  32641. }
  32642. } else {
  32643. symbolPath.removeTextContent();
  32644. }
  32645. removeElement(symbolPath, {
  32646. style: {
  32647. opacity: 0
  32648. },
  32649. scaleX: 0,
  32650. scaleY: 0
  32651. }, seriesModel, {
  32652. dataIndex: dataIndex,
  32653. cb: cb,
  32654. removeOpt: animationOpt
  32655. });
  32656. };
  32657. Symbol.getSymbolSize = function (data, idx) {
  32658. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32659. return symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize];
  32660. };
  32661. return Symbol;
  32662. }(Group);
  32663. function driftSymbol(dx, dy) {
  32664. this.parent.drift(dx, dy);
  32665. }
  32666. function symbolNeedsDraw(data, point, idx, opt) {
  32667. 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
  32668. // the symbol element shape. We use the same clip shape here as
  32669. // the line clip.
  32670. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  32671. }
  32672. function normalizeUpdateOpt(opt) {
  32673. if (opt != null && !isObject(opt)) {
  32674. opt = {
  32675. isIgnore: opt
  32676. };
  32677. }
  32678. return opt || {};
  32679. }
  32680. function makeSeriesScope(data) {
  32681. var seriesModel = data.hostModel;
  32682. var emphasisModel = seriesModel.getModel('emphasis');
  32683. return {
  32684. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  32685. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  32686. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  32687. focus: emphasisModel.get('focus'),
  32688. blurScope: emphasisModel.get('blurScope'),
  32689. symbolRotate: seriesModel.get('symbolRotate'),
  32690. symbolOffset: seriesModel.get('symbolOffset'),
  32691. hoverScale: emphasisModel.get('scale'),
  32692. labelStatesModels: getLabelStatesModels(seriesModel),
  32693. cursorStyle: seriesModel.get('cursor')
  32694. };
  32695. }
  32696. var SymbolDraw =
  32697. /** @class */
  32698. function () {
  32699. function SymbolDraw(SymbolCtor) {
  32700. this.group = new Group();
  32701. this._SymbolCtor = SymbolCtor || Symbol;
  32702. }
  32703. /**
  32704. * Update symbols draw by new data
  32705. */
  32706. SymbolDraw.prototype.updateData = function (data, opt) {
  32707. opt = normalizeUpdateOpt(opt);
  32708. var group = this.group;
  32709. var seriesModel = data.hostModel;
  32710. var oldData = this._data;
  32711. var SymbolCtor = this._SymbolCtor;
  32712. var disableAnimation = opt.disableAnimation;
  32713. var seriesScope = makeSeriesScope(data);
  32714. var symbolUpdateOpt = {
  32715. disableAnimation: disableAnimation
  32716. };
  32717. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  32718. return data.getItemLayout(idx);
  32719. }; // There is no oldLineData only when first rendering or switching from
  32720. // stream mode to normal mode, where previous elements should be removed.
  32721. if (!oldData) {
  32722. group.removeAll();
  32723. }
  32724. data.diff(oldData).add(function (newIdx) {
  32725. var point = getSymbolPoint(newIdx);
  32726. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  32727. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  32728. symbolEl.setPosition(point);
  32729. data.setItemGraphicEl(newIdx, symbolEl);
  32730. group.add(symbolEl);
  32731. }
  32732. }).update(function (newIdx, oldIdx) {
  32733. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32734. var point = getSymbolPoint(newIdx);
  32735. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  32736. group.remove(symbolEl);
  32737. return;
  32738. }
  32739. if (!symbolEl) {
  32740. symbolEl = new SymbolCtor(data, newIdx);
  32741. symbolEl.setPosition(point);
  32742. } else {
  32743. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  32744. var target = {
  32745. x: point[0],
  32746. y: point[1]
  32747. };
  32748. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  32749. } // Add back
  32750. group.add(symbolEl);
  32751. data.setItemGraphicEl(newIdx, symbolEl);
  32752. }).remove(function (oldIdx) {
  32753. var el = oldData.getItemGraphicEl(oldIdx);
  32754. el && el.fadeOut(function () {
  32755. group.remove(el);
  32756. });
  32757. }).execute();
  32758. this._getSymbolPoint = getSymbolPoint;
  32759. this._data = data;
  32760. };
  32761. SymbolDraw.prototype.isPersistent = function () {
  32762. return true;
  32763. };
  32764. SymbolDraw.prototype.updateLayout = function () {
  32765. var _this = this;
  32766. var data = this._data;
  32767. if (data) {
  32768. // Not use animation
  32769. data.eachItemGraphicEl(function (el, idx) {
  32770. var point = _this._getSymbolPoint(idx);
  32771. el.setPosition(point);
  32772. el.markRedraw();
  32773. });
  32774. }
  32775. };
  32776. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  32777. this._seriesScope = makeSeriesScope(data);
  32778. this._data = null;
  32779. this.group.removeAll();
  32780. };
  32781. /**
  32782. * Update symbols draw by new data
  32783. */
  32784. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  32785. opt = normalizeUpdateOpt(opt);
  32786. function updateIncrementalAndHover(el) {
  32787. if (!el.isGroup) {
  32788. el.incremental = true;
  32789. el.ensureState('emphasis').hoverLayer = true;
  32790. }
  32791. }
  32792. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  32793. var point = data.getItemLayout(idx);
  32794. if (symbolNeedsDraw(data, point, idx, opt)) {
  32795. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  32796. el.traverse(updateIncrementalAndHover);
  32797. el.setPosition(point);
  32798. this.group.add(el);
  32799. data.setItemGraphicEl(idx, el);
  32800. }
  32801. }
  32802. };
  32803. SymbolDraw.prototype.remove = function (enableAnimation) {
  32804. var group = this.group;
  32805. var data = this._data; // Incremental model do not have this._data.
  32806. if (data && enableAnimation) {
  32807. data.eachItemGraphicEl(function (el) {
  32808. el.fadeOut(function () {
  32809. group.remove(el);
  32810. });
  32811. });
  32812. } else {
  32813. group.removeAll();
  32814. }
  32815. };
  32816. return SymbolDraw;
  32817. }();
  32818. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  32819. var baseAxis = coordSys.getBaseAxis();
  32820. var valueAxis = coordSys.getOtherAxis(baseAxis);
  32821. var valueStart = getValueStart(valueAxis, valueOrigin);
  32822. var baseAxisDim = baseAxis.dim;
  32823. var valueAxisDim = valueAxis.dim;
  32824. var valueDim = data.mapDimension(valueAxisDim);
  32825. var baseDim = data.mapDimension(baseAxisDim);
  32826. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  32827. var dims = map(coordSys.dimensions, function (coordDim) {
  32828. return data.mapDimension(coordDim);
  32829. });
  32830. var stacked = false;
  32831. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  32832. if (isDimensionStacked(data, dims[0]
  32833. /*, dims[1]*/
  32834. )) {
  32835. // jshint ignore:line
  32836. stacked = true;
  32837. dims[0] = stackResultDim;
  32838. }
  32839. if (isDimensionStacked(data, dims[1]
  32840. /*, dims[0]*/
  32841. )) {
  32842. // jshint ignore:line
  32843. stacked = true;
  32844. dims[1] = stackResultDim;
  32845. }
  32846. return {
  32847. dataDimsForPoint: dims,
  32848. valueStart: valueStart,
  32849. valueAxisDim: valueAxisDim,
  32850. baseAxisDim: baseAxisDim,
  32851. stacked: !!stacked,
  32852. valueDim: valueDim,
  32853. baseDim: baseDim,
  32854. baseDataOffset: baseDataOffset,
  32855. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  32856. };
  32857. }
  32858. function getValueStart(valueAxis, valueOrigin) {
  32859. var valueStart = 0;
  32860. var extent = valueAxis.scale.getExtent();
  32861. if (valueOrigin === 'start') {
  32862. valueStart = extent[0];
  32863. } else if (valueOrigin === 'end') {
  32864. valueStart = extent[1];
  32865. } // auto
  32866. else {
  32867. // Both positive
  32868. if (extent[0] > 0) {
  32869. valueStart = extent[0];
  32870. } // Both negative
  32871. else if (extent[1] < 0) {
  32872. valueStart = extent[1];
  32873. } // If is one positive, and one negative, onZero shall be true
  32874. }
  32875. return valueStart;
  32876. }
  32877. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  32878. var value = NaN;
  32879. if (dataCoordInfo.stacked) {
  32880. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  32881. }
  32882. if (isNaN(value)) {
  32883. value = dataCoordInfo.valueStart;
  32884. }
  32885. var baseDataOffset = dataCoordInfo.baseDataOffset;
  32886. var stackedData = [];
  32887. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  32888. stackedData[1 - baseDataOffset] = value;
  32889. return coordSys.dataToPoint(stackedData);
  32890. }
  32891. /* global Float32Array */
  32892. var supportFloat32Array = typeof Float32Array !== 'undefined';
  32893. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  32894. function createFloat32Array(arg) {
  32895. if (isArray(arg)) {
  32896. // Return self directly if don't support TypedArray.
  32897. return supportFloat32Array ? new Float32Array(arg) : arg;
  32898. } // Else is number
  32899. return new Float32ArrayCtor(arg);
  32900. }
  32901. function diffData(oldData, newData) {
  32902. var diffResult = [];
  32903. newData.diff(oldData).add(function (idx) {
  32904. diffResult.push({
  32905. cmd: '+',
  32906. idx: idx
  32907. });
  32908. }).update(function (newIdx, oldIdx) {
  32909. diffResult.push({
  32910. cmd: '=',
  32911. idx: oldIdx,
  32912. idx1: newIdx
  32913. });
  32914. }).remove(function (idx) {
  32915. diffResult.push({
  32916. cmd: '-',
  32917. idx: idx
  32918. });
  32919. }).execute();
  32920. return diffResult;
  32921. }
  32922. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  32923. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  32924. // let oldIdList = oldData.mapArray(oldData.getId);
  32925. // convertToIntId(newIdList, oldIdList);
  32926. // // FIXME One data ?
  32927. // diff = arrayDiff(oldIdList, newIdList);
  32928. var currPoints = [];
  32929. var nextPoints = []; // Points for stacking base line
  32930. var currStackedPoints = [];
  32931. var nextStackedPoints = [];
  32932. var status = [];
  32933. var sortedIndices = [];
  32934. var rawIndices = [];
  32935. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  32936. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  32937. var oldPoints = oldData.getLayout('points') || [];
  32938. var newPoints = newData.getLayout('points') || [];
  32939. for (var i = 0; i < diff.length; i++) {
  32940. var diffItem = diff[i];
  32941. var pointAdded = true;
  32942. var oldIdx2 = void 0;
  32943. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  32944. // Which is in case remvoing or add more than one data in the tail or head
  32945. switch (diffItem.cmd) {
  32946. case '=':
  32947. oldIdx2 = diffItem.idx * 2;
  32948. newIdx2 = diffItem.idx1 * 2;
  32949. var currentX = oldPoints[oldIdx2];
  32950. var currentY = oldPoints[oldIdx2 + 1];
  32951. var nextX = newPoints[newIdx2];
  32952. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  32953. if (isNaN(currentX) || isNaN(currentY)) {
  32954. currentX = nextX;
  32955. currentY = nextY;
  32956. }
  32957. currPoints.push(currentX, currentY);
  32958. nextPoints.push(nextX, nextY);
  32959. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  32960. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  32961. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  32962. break;
  32963. case '+':
  32964. var newIdx = diffItem.idx;
  32965. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  32966. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  32967. newIdx2 = newIdx * 2;
  32968. currPoints.push(oldPt[0], oldPt[1]);
  32969. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  32970. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  32971. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  32972. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  32973. rawIndices.push(newData.getRawIndex(newIdx));
  32974. break;
  32975. case '-':
  32976. var oldIdx = diffItem.idx;
  32977. var rawIndex = oldData.getRawIndex(oldIdx);
  32978. var oldDataDimsForPoint = oldDataNewCoordInfo.dataDimsForPoint;
  32979. oldIdx2 = oldIdx * 2; // Data is replaced. In the case of dynamic data queue
  32980. // FIXME FIXME FIXME
  32981. if (rawIndex !== oldIdx) {
  32982. var newPt = newCoordSys.dataToPoint([oldData.get(oldDataDimsForPoint[0], oldIdx), oldData.get(oldDataDimsForPoint[1], oldIdx)]);
  32983. var newStackedOnPt = getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, oldIdx);
  32984. currPoints.push(oldPoints[oldIdx2], oldPoints[oldIdx2 + 1]);
  32985. nextPoints.push(newPt[0], newPt[1]);
  32986. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  32987. nextStackedPoints.push(newStackedOnPt[0], newStackedOnPt[1]);
  32988. rawIndices.push(rawIndex);
  32989. } else {
  32990. pointAdded = false;
  32991. }
  32992. } // Original indices
  32993. if (pointAdded) {
  32994. status.push(diffItem);
  32995. sortedIndices.push(sortedIndices.length);
  32996. }
  32997. } // Diff result may be crossed if all items are changed
  32998. // Sort by data index
  32999. sortedIndices.sort(function (a, b) {
  33000. return rawIndices[a] - rawIndices[b];
  33001. });
  33002. var len = currPoints.length;
  33003. var sortedCurrPoints = createFloat32Array(len);
  33004. var sortedNextPoints = createFloat32Array(len);
  33005. var sortedCurrStackedPoints = createFloat32Array(len);
  33006. var sortedNextStackedPoints = createFloat32Array(len);
  33007. var sortedStatus = [];
  33008. for (var i = 0; i < sortedIndices.length; i++) {
  33009. var idx = sortedIndices[i];
  33010. var i2 = i * 2;
  33011. var idx2 = idx * 2;
  33012. sortedCurrPoints[i2] = currPoints[idx2];
  33013. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  33014. sortedNextPoints[i2] = nextPoints[idx2];
  33015. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  33016. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  33017. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  33018. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  33019. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  33020. sortedStatus[i] = status[idx];
  33021. }
  33022. return {
  33023. current: sortedCurrPoints,
  33024. next: sortedNextPoints,
  33025. stackedOnCurrent: sortedCurrStackedPoints,
  33026. stackedOnNext: sortedNextStackedPoints,
  33027. status: sortedStatus
  33028. };
  33029. }
  33030. var mathMin$5 = Math.min;
  33031. var mathMax$5 = Math.max;
  33032. function isPointNull(x, y) {
  33033. return isNaN(x) || isNaN(y);
  33034. }
  33035. /**
  33036. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33037. * situations. This should be used when points are non-monotone neither in x or
  33038. * y dimension.
  33039. */
  33040. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  33041. var prevX;
  33042. var prevY;
  33043. var cpx0;
  33044. var cpy0;
  33045. var cpx1;
  33046. var cpy1;
  33047. var idx = start;
  33048. var k = 0;
  33049. for (; k < segLen; k++) {
  33050. var x = points[idx * 2];
  33051. var y = points[idx * 2 + 1];
  33052. if (idx >= allLen || idx < 0) {
  33053. break;
  33054. }
  33055. if (isPointNull(x, y)) {
  33056. if (connectNulls) {
  33057. idx += dir;
  33058. continue;
  33059. }
  33060. break;
  33061. }
  33062. if (idx === start) {
  33063. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  33064. cpx0 = x;
  33065. cpy0 = y;
  33066. } else {
  33067. var dx = x - prevX;
  33068. var dy = y - prevY; // Ignore tiny segment.
  33069. if (dx * dx + dy * dy < 0.5) {
  33070. idx += dir;
  33071. continue;
  33072. }
  33073. if (smooth > 0) {
  33074. var nextIdx = idx + dir;
  33075. var nextX = points[nextIdx * 2];
  33076. var nextY = points[nextIdx * 2 + 1];
  33077. var tmpK = k + 1;
  33078. if (connectNulls) {
  33079. // Find next point not null
  33080. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  33081. tmpK++;
  33082. nextIdx += dir;
  33083. nextX = points[nextIdx * 2];
  33084. nextY = points[nextIdx * 2 + 1];
  33085. }
  33086. }
  33087. var ratioNextSeg = 0.5;
  33088. var vx = 0;
  33089. var vy = 0;
  33090. var nextCpx0 = void 0;
  33091. var nextCpy0 = void 0; // Is last point
  33092. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  33093. cpx1 = x;
  33094. cpy1 = y;
  33095. } else {
  33096. vx = nextX - prevX;
  33097. vy = nextY - prevY;
  33098. var dx0 = x - prevX;
  33099. var dx1 = nextX - x;
  33100. var dy0 = y - prevY;
  33101. var dy1 = nextY - y;
  33102. var lenPrevSeg = void 0;
  33103. var lenNextSeg = void 0;
  33104. if (smoothMonotone === 'x') {
  33105. lenPrevSeg = Math.abs(dx0);
  33106. lenNextSeg = Math.abs(dx1);
  33107. cpx1 = x - lenPrevSeg * smooth;
  33108. cpy1 = y;
  33109. nextCpx0 = x + lenPrevSeg * smooth;
  33110. nextCpy0 = y;
  33111. } else if (smoothMonotone === 'y') {
  33112. lenPrevSeg = Math.abs(dy0);
  33113. lenNextSeg = Math.abs(dy1);
  33114. cpx1 = x;
  33115. cpy1 = y - lenPrevSeg * smooth;
  33116. nextCpx0 = x;
  33117. nextCpy0 = y + lenPrevSeg * smooth;
  33118. } else {
  33119. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  33120. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  33121. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33122. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  33123. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  33124. nextCpx0 = x + vx * smooth * ratioNextSeg;
  33125. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  33126. // Avoid exceeding extreme after smoothing.
  33127. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  33128. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  33129. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  33130. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  33131. vx = nextCpx0 - x;
  33132. vy = nextCpy0 - y;
  33133. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  33134. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  33135. // Avoid exceeding extreme after smoothing.
  33136. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  33137. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  33138. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  33139. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  33140. vx = x - cpx1;
  33141. vy = y - cpy1;
  33142. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  33143. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  33144. }
  33145. }
  33146. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  33147. cpx0 = nextCpx0;
  33148. cpy0 = nextCpy0;
  33149. } else {
  33150. ctx.lineTo(x, y);
  33151. }
  33152. }
  33153. prevX = x;
  33154. prevY = y;
  33155. idx += dir;
  33156. }
  33157. return k;
  33158. }
  33159. var ECPolylineShape =
  33160. /** @class */
  33161. function () {
  33162. function ECPolylineShape() {
  33163. this.smooth = 0;
  33164. this.smoothConstraint = true;
  33165. }
  33166. return ECPolylineShape;
  33167. }();
  33168. var ECPolyline =
  33169. /** @class */
  33170. function (_super) {
  33171. __extends(ECPolyline, _super);
  33172. function ECPolyline(opts) {
  33173. var _this = _super.call(this, opts) || this;
  33174. _this.type = 'ec-polyline';
  33175. return _this;
  33176. }
  33177. ECPolyline.prototype.getDefaultStyle = function () {
  33178. return {
  33179. stroke: '#000',
  33180. fill: null
  33181. };
  33182. };
  33183. ECPolyline.prototype.getDefaultShape = function () {
  33184. return new ECPolylineShape();
  33185. };
  33186. ECPolyline.prototype.buildPath = function (ctx, shape) {
  33187. var points = shape.points;
  33188. var i = 0;
  33189. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  33190. if (shape.connectNulls) {
  33191. // Must remove first and last null values avoid draw error in polygon
  33192. for (; len > 0; len--) {
  33193. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  33194. break;
  33195. }
  33196. }
  33197. for (; i < len; i++) {
  33198. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  33199. break;
  33200. }
  33201. }
  33202. }
  33203. while (i < len) {
  33204. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  33205. }
  33206. };
  33207. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  33208. if (!this.path) {
  33209. this.createPathProxy();
  33210. this.buildPath(this.path, this.shape);
  33211. }
  33212. var path = this.path;
  33213. var data = path.data;
  33214. var CMD = PathProxy.CMD;
  33215. var x0;
  33216. var y0;
  33217. var isDimX = dim === 'x';
  33218. var roots = [];
  33219. for (var i = 0; i < data.length;) {
  33220. var cmd = data[i++];
  33221. var x = void 0;
  33222. var y = void 0;
  33223. var x2 = void 0;
  33224. var y2 = void 0;
  33225. var x3 = void 0;
  33226. var y3 = void 0;
  33227. var t = void 0;
  33228. switch (cmd) {
  33229. case CMD.M:
  33230. x0 = data[i++];
  33231. y0 = data[i++];
  33232. break;
  33233. case CMD.L:
  33234. x = data[i++];
  33235. y = data[i++];
  33236. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  33237. if (t <= 1 && t >= 0) {
  33238. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  33239. return isDimX ? [xOrY, val] : [val, xOrY];
  33240. }
  33241. x0 = x;
  33242. y0 = y;
  33243. break;
  33244. case CMD.C:
  33245. x = data[i++];
  33246. y = data[i++];
  33247. x2 = data[i++];
  33248. y2 = data[i++];
  33249. x3 = data[i++];
  33250. y3 = data[i++];
  33251. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  33252. if (nRoot > 0) {
  33253. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  33254. var t_1 = roots[i_1];
  33255. if (t_1 <= 1 && t_1 >= 0) {
  33256. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  33257. return isDimX ? [xOrY, val] : [val, xOrY];
  33258. }
  33259. }
  33260. }
  33261. x0 = x3;
  33262. y0 = y3;
  33263. break;
  33264. }
  33265. }
  33266. };
  33267. return ECPolyline;
  33268. }(Path);
  33269. var ECPolygonShape =
  33270. /** @class */
  33271. function (_super) {
  33272. __extends(ECPolygonShape, _super);
  33273. function ECPolygonShape() {
  33274. return _super !== null && _super.apply(this, arguments) || this;
  33275. }
  33276. return ECPolygonShape;
  33277. }(ECPolylineShape);
  33278. var ECPolygon =
  33279. /** @class */
  33280. function (_super) {
  33281. __extends(ECPolygon, _super);
  33282. function ECPolygon(opts) {
  33283. var _this = _super.call(this, opts) || this;
  33284. _this.type = 'ec-polygon';
  33285. return _this;
  33286. }
  33287. ECPolygon.prototype.getDefaultShape = function () {
  33288. return new ECPolygonShape();
  33289. };
  33290. ECPolygon.prototype.buildPath = function (ctx, shape) {
  33291. var points = shape.points;
  33292. var stackedOnPoints = shape.stackedOnPoints;
  33293. var i = 0;
  33294. var len = points.length / 2;
  33295. var smoothMonotone = shape.smoothMonotone;
  33296. if (shape.connectNulls) {
  33297. // Must remove first and last null values avoid draw error in polygon
  33298. for (; len > 0; len--) {
  33299. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  33300. break;
  33301. }
  33302. }
  33303. for (; i < len; i++) {
  33304. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  33305. break;
  33306. }
  33307. }
  33308. }
  33309. while (i < len) {
  33310. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  33311. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  33312. i += k + 1;
  33313. ctx.closePath();
  33314. }
  33315. };
  33316. return ECPolygon;
  33317. }(Path);
  33318. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  33319. var rect = cartesian.getArea();
  33320. var x = rect.x;
  33321. var y = rect.y;
  33322. var width = rect.width;
  33323. var height = rect.height;
  33324. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33325. x -= lineWidth / 2;
  33326. y -= lineWidth / 2;
  33327. width += lineWidth;
  33328. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  33329. x = Math.floor(x);
  33330. width = Math.round(width);
  33331. var clipPath = new Rect({
  33332. shape: {
  33333. x: x,
  33334. y: y,
  33335. width: width,
  33336. height: height
  33337. }
  33338. });
  33339. if (hasAnimation) {
  33340. var baseAxis = cartesian.getBaseAxis();
  33341. var isHorizontal = baseAxis.isHorizontal();
  33342. var isAxisInversed = baseAxis.inverse;
  33343. if (isHorizontal) {
  33344. if (isAxisInversed) {
  33345. clipPath.shape.x += width;
  33346. }
  33347. clipPath.shape.width = 0;
  33348. } else {
  33349. if (!isAxisInversed) {
  33350. clipPath.shape.y += height;
  33351. }
  33352. clipPath.shape.height = 0;
  33353. }
  33354. var duringCb = typeof during === 'function' ? function (percent) {
  33355. during(percent, clipPath);
  33356. } : null;
  33357. initProps(clipPath, {
  33358. shape: {
  33359. width: width,
  33360. height: height,
  33361. x: x,
  33362. y: y
  33363. }
  33364. }, seriesModel, null, done, duringCb);
  33365. }
  33366. return clipPath;
  33367. }
  33368. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33369. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  33370. var r0 = round(sectorArea.r0, 1);
  33371. var r = round(sectorArea.r, 1);
  33372. var clipPath = new Sector({
  33373. shape: {
  33374. cx: round(polar.cx, 1),
  33375. cy: round(polar.cy, 1),
  33376. r0: r0,
  33377. r: r,
  33378. startAngle: sectorArea.startAngle,
  33379. endAngle: sectorArea.endAngle,
  33380. clockwise: sectorArea.clockwise
  33381. }
  33382. });
  33383. if (hasAnimation) {
  33384. var isRadial = polar.getBaseAxis().dim === 'angle';
  33385. if (isRadial) {
  33386. clipPath.shape.endAngle = sectorArea.startAngle;
  33387. } else {
  33388. clipPath.shape.r = r0;
  33389. }
  33390. initProps(clipPath, {
  33391. shape: {
  33392. endAngle: sectorArea.endAngle,
  33393. r: r
  33394. }
  33395. }, seriesModel);
  33396. }
  33397. return clipPath;
  33398. }
  33399. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  33400. if (!coordSys) {
  33401. return null;
  33402. } else if (coordSys.type === 'polar') {
  33403. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33404. } else if (coordSys.type === 'cartesian2d') {
  33405. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  33406. }
  33407. return null;
  33408. }
  33409. /*
  33410. * Licensed to the Apache Software Foundation (ASF) under one
  33411. * or more contributor license agreements. See the NOTICE file
  33412. * distributed with this work for additional information
  33413. * regarding copyright ownership. The ASF licenses this file
  33414. * to you under the Apache License, Version 2.0 (the
  33415. * "License"); you may not use this file except in compliance
  33416. * with the License. You may obtain a copy of the License at
  33417. *
  33418. * http://www.apache.org/licenses/LICENSE-2.0
  33419. *
  33420. * Unless required by applicable law or agreed to in writing,
  33421. * software distributed under the License is distributed on an
  33422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33423. * KIND, either express or implied. See the License for the
  33424. * specific language governing permissions and limitations
  33425. * under the License.
  33426. */
  33427. /**
  33428. * AUTO-GENERATED FILE. DO NOT MODIFY.
  33429. */
  33430. /*
  33431. * Licensed to the Apache Software Foundation (ASF) under one
  33432. * or more contributor license agreements. See the NOTICE file
  33433. * distributed with this work for additional information
  33434. * regarding copyright ownership. The ASF licenses this file
  33435. * to you under the Apache License, Version 2.0 (the
  33436. * "License"); you may not use this file except in compliance
  33437. * with the License. You may obtain a copy of the License at
  33438. *
  33439. * http://www.apache.org/licenses/LICENSE-2.0
  33440. *
  33441. * Unless required by applicable law or agreed to in writing,
  33442. * software distributed under the License is distributed on an
  33443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33444. * KIND, either express or implied. See the License for the
  33445. * specific language governing permissions and limitations
  33446. * under the License.
  33447. */
  33448. function isCoordinateSystemType(coordSys, type) {
  33449. return coordSys.type === type;
  33450. }
  33451. function isPointsSame(points1, points2) {
  33452. if (points1.length !== points2.length) {
  33453. return;
  33454. }
  33455. for (var i = 0; i < points1.length; i++) {
  33456. if (points1[i] !== points2[i]) {
  33457. return;
  33458. }
  33459. }
  33460. return true;
  33461. }
  33462. function bboxFromPoints(points) {
  33463. var minX = Infinity;
  33464. var minY = Infinity;
  33465. var maxX = -Infinity;
  33466. var maxY = -Infinity;
  33467. for (var i = 0; i < points.length;) {
  33468. var x = points[i++];
  33469. var y = points[i++];
  33470. if (!isNaN(x)) {
  33471. minX = Math.min(x, minX);
  33472. maxX = Math.max(x, maxX);
  33473. }
  33474. if (!isNaN(y)) {
  33475. minY = Math.min(y, minY);
  33476. maxY = Math.max(y, maxY);
  33477. }
  33478. }
  33479. return [[minX, minY], [maxX, maxY]];
  33480. }
  33481. function getBoundingDiff(points1, points2) {
  33482. var _a = bboxFromPoints(points1),
  33483. min1 = _a[0],
  33484. max1 = _a[1];
  33485. var _b = bboxFromPoints(points2),
  33486. min2 = _b[0],
  33487. max2 = _b[1]; // Get a max value from each corner of two boundings.
  33488. 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]));
  33489. }
  33490. function getSmooth(smooth) {
  33491. return typeof smooth === 'number' ? smooth : smooth ? 0.5 : 0;
  33492. }
  33493. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  33494. if (!dataCoordInfo.valueDim) {
  33495. return [];
  33496. }
  33497. var len = data.count();
  33498. var points = createFloat32Array(len * 2);
  33499. for (var idx = 0; idx < len; idx++) {
  33500. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  33501. points[idx * 2] = pt[0];
  33502. points[idx * 2 + 1] = pt[1];
  33503. }
  33504. return points;
  33505. }
  33506. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  33507. var baseAxis = coordSys.getBaseAxis();
  33508. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  33509. var stepPoints = [];
  33510. var i = 0;
  33511. var stepPt = [];
  33512. var pt = [];
  33513. var nextPt = [];
  33514. for (; i < points.length - 2; i += 2) {
  33515. nextPt[0] = points[i + 2];
  33516. nextPt[1] = points[i + 3];
  33517. pt[0] = points[i];
  33518. pt[1] = points[i + 1];
  33519. stepPoints.push(pt[0], pt[1]);
  33520. switch (stepTurnAt) {
  33521. case 'end':
  33522. stepPt[baseIndex] = nextPt[baseIndex];
  33523. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33524. stepPoints.push(stepPt[0], stepPt[1]);
  33525. break;
  33526. case 'middle':
  33527. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  33528. var stepPt2 = [];
  33529. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  33530. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33531. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  33532. stepPoints.push(stepPt[0], stepPt[1]);
  33533. stepPoints.push(stepPt2[0], stepPt2[1]);
  33534. break;
  33535. default:
  33536. // default is start
  33537. stepPt[baseIndex] = pt[baseIndex];
  33538. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  33539. stepPoints.push(stepPt[0], stepPt[1]);
  33540. }
  33541. } // Last points
  33542. stepPoints.push(points[i++], points[i++]);
  33543. return stepPoints;
  33544. }
  33545. function getVisualGradient(data, coordSys) {
  33546. var visualMetaList = data.getVisual('visualMeta');
  33547. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  33548. // When data.count() is 0, gradient range can not be calculated.
  33549. return;
  33550. }
  33551. if (coordSys.type !== 'cartesian2d') {
  33552. if ("development" !== 'production') {
  33553. console.warn('Visual map on line style is only supported on cartesian2d.');
  33554. }
  33555. return;
  33556. }
  33557. var coordDim;
  33558. var visualMeta;
  33559. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  33560. var dimIndex = visualMetaList[i].dimension;
  33561. var dimName = data.dimensions[dimIndex];
  33562. var dimInfo = data.getDimensionInfo(dimName);
  33563. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  33564. if (coordDim === 'x' || coordDim === 'y') {
  33565. visualMeta = visualMetaList[i];
  33566. break;
  33567. }
  33568. }
  33569. if (!visualMeta) {
  33570. if ("development" !== 'production') {
  33571. console.warn('Visual map on line style only support x or y dimension.');
  33572. }
  33573. return;
  33574. } // If the area to be rendered is bigger than area defined by LinearGradient,
  33575. // the canvas spec prescribes that the color of the first stop and the last
  33576. // stop should be used. But if two stops are added at offset 0, in effect
  33577. // browsers use the color of the second stop to render area outside
  33578. // LinearGradient. So we can only infinitesimally extend area defined in
  33579. // LinearGradient to render `outerColors`.
  33580. var axis = coordSys.getAxis(coordDim); // dataToCoor mapping may not be linear, but must be monotonic.
  33581. var colorStops = map(visualMeta.stops, function (stop) {
  33582. return {
  33583. offset: 0,
  33584. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  33585. color: stop.color
  33586. };
  33587. });
  33588. var stopLen = colorStops.length;
  33589. var outerColors = visualMeta.outerColors.slice();
  33590. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  33591. colorStops.reverse();
  33592. outerColors.reverse();
  33593. }
  33594. var tinyExtent = 10; // Arbitrary value: 10px
  33595. var minCoord = colorStops[0].coord - tinyExtent;
  33596. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  33597. var coordSpan = maxCoord - minCoord;
  33598. if (coordSpan < 1e-3) {
  33599. return 'transparent';
  33600. }
  33601. each(colorStops, function (stop) {
  33602. stop.offset = (stop.coord - minCoord) / coordSpan;
  33603. });
  33604. colorStops.push({
  33605. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  33606. color: outerColors[1] || 'transparent'
  33607. });
  33608. colorStops.unshift({
  33609. offset: stopLen ? colorStops[0].offset : 0.5,
  33610. color: outerColors[0] || 'transparent'
  33611. }); // zrUtil.each(colorStops, function (colorStop) {
  33612. // // Make sure each offset has rounded px to avoid not sharp edge
  33613. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  33614. // });
  33615. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  33616. gradient[coordDim] = minCoord;
  33617. gradient[coordDim + '2'] = maxCoord;
  33618. return gradient;
  33619. }
  33620. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  33621. var showAllSymbol = seriesModel.get('showAllSymbol');
  33622. var isAuto = showAllSymbol === 'auto';
  33623. if (showAllSymbol && !isAuto) {
  33624. return;
  33625. }
  33626. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  33627. if (!categoryAxis) {
  33628. return;
  33629. } // Note that category label interval strategy might bring some weird effect
  33630. // in some scenario: users may wonder why some of the symbols are not
  33631. // displayed. So we show all symbols as possible as we can.
  33632. if (isAuto // Simplify the logic, do not determine label overlap here.
  33633. && canShowAllSymbolForCategory(categoryAxis, data)) {
  33634. return;
  33635. } // Otherwise follow the label interval strategy on category axis.
  33636. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  33637. var labelMap = {};
  33638. each(categoryAxis.getViewLabels(), function (labelItem) {
  33639. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  33640. labelMap[ordinalNumber] = 1;
  33641. });
  33642. return function (dataIndex) {
  33643. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  33644. };
  33645. }
  33646. function canShowAllSymbolForCategory(categoryAxis, data) {
  33647. // In mose cases, line is monotonous on category axis, and the label size
  33648. // is close with each other. So we check the symbol size and some of the
  33649. // label size alone with the category axis to estimate whether all symbol
  33650. // can be shown without overlap.
  33651. var axisExtent = categoryAxis.getExtent();
  33652. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  33653. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  33654. // Sampling some points, max 5.
  33655. var dataLen = data.count();
  33656. var step = Math.max(1, Math.round(dataLen / 5));
  33657. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  33658. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  33659. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  33660. * 1.5 > availSize) {
  33661. return false;
  33662. }
  33663. }
  33664. return true;
  33665. }
  33666. function isPointNull$1(x, y) {
  33667. return isNaN(x) || isNaN(y);
  33668. }
  33669. function getLastIndexNotNull(points) {
  33670. var len = points.length / 2;
  33671. for (; len > 0; len--) {
  33672. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  33673. break;
  33674. }
  33675. }
  33676. return len - 1;
  33677. }
  33678. function getPointAtIndex(points, idx) {
  33679. return [points[idx * 2], points[idx * 2 + 1]];
  33680. }
  33681. function getIndexRange(points, xOrY, dim) {
  33682. var len = points.length / 2;
  33683. var dimIdx = dim === 'x' ? 0 : 1;
  33684. var a;
  33685. var b;
  33686. var prevIndex = 0;
  33687. var nextIndex = -1;
  33688. for (var i = 0; i < len; i++) {
  33689. b = points[i * 2 + dimIdx];
  33690. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  33691. continue;
  33692. }
  33693. if (i === 0) {
  33694. a = b;
  33695. continue;
  33696. }
  33697. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  33698. nextIndex = i;
  33699. break;
  33700. }
  33701. prevIndex = i;
  33702. a = b;
  33703. }
  33704. return {
  33705. range: [prevIndex, nextIndex],
  33706. t: (xOrY - a) / (b - a)
  33707. };
  33708. }
  33709. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  33710. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  33711. var endLabelModel_1 = seriesModel.getModel('endLabel');
  33712. var showEndLabel = endLabelModel_1.get('show');
  33713. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  33714. var data_1 = seriesModel.getData();
  33715. var labelAnimationRecord_1 = {
  33716. lastFrameIndex: 0
  33717. };
  33718. var during = showEndLabel ? function (percent, clipRect) {
  33719. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  33720. } : null;
  33721. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  33722. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  33723. var endLabel = lineView._endLabel;
  33724. if (endLabel && hasAnimation) {
  33725. if (labelAnimationRecord_1.originalX != null) {
  33726. endLabel.attr({
  33727. x: labelAnimationRecord_1.originalX,
  33728. y: labelAnimationRecord_1.originalY
  33729. });
  33730. }
  33731. }
  33732. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  33733. if (!seriesModel.get('clip', true)) {
  33734. var rectShape = clipPath.shape;
  33735. var expandSize = Math.max(rectShape.width, rectShape.height);
  33736. if (isHorizontal) {
  33737. rectShape.y -= expandSize;
  33738. rectShape.height += expandSize * 2;
  33739. } else {
  33740. rectShape.x -= expandSize;
  33741. rectShape.width += expandSize * 2;
  33742. }
  33743. } // Set to the final frame. To make sure label layout is right.
  33744. if (during) {
  33745. during(1, clipPath);
  33746. }
  33747. return clipPath;
  33748. } else {
  33749. if ("development" !== 'production') {
  33750. if (seriesModel.get(['endLabel', 'show'])) {
  33751. console.warn('endLabel is not supported for lines in polar systems.');
  33752. }
  33753. }
  33754. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33755. }
  33756. }
  33757. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  33758. var baseAxis = coordSys.getBaseAxis();
  33759. var isHorizontal = baseAxis.isHorizontal();
  33760. var isBaseInversed = baseAxis.inverse;
  33761. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  33762. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  33763. return {
  33764. normal: {
  33765. align: endLabelModel.get('align') || align,
  33766. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  33767. }
  33768. };
  33769. }
  33770. var LineView =
  33771. /** @class */
  33772. function (_super) {
  33773. __extends(LineView, _super);
  33774. function LineView() {
  33775. return _super !== null && _super.apply(this, arguments) || this;
  33776. }
  33777. LineView.prototype.init = function () {
  33778. var lineGroup = new Group();
  33779. var symbolDraw = new SymbolDraw();
  33780. this.group.add(symbolDraw.group);
  33781. this._symbolDraw = symbolDraw;
  33782. this._lineGroup = lineGroup;
  33783. };
  33784. LineView.prototype.render = function (seriesModel, ecModel, api) {
  33785. var _this = this;
  33786. var coordSys = seriesModel.coordinateSystem;
  33787. var group = this.group;
  33788. var data = seriesModel.getData();
  33789. var lineStyleModel = seriesModel.getModel('lineStyle');
  33790. var areaStyleModel = seriesModel.getModel('areaStyle');
  33791. var points = data.getLayout('points') || [];
  33792. var isCoordSysPolar = coordSys.type === 'polar';
  33793. var prevCoordSys = this._coordSys;
  33794. var symbolDraw = this._symbolDraw;
  33795. var polyline = this._polyline;
  33796. var polygon = this._polygon;
  33797. var lineGroup = this._lineGroup;
  33798. var hasAnimation = seriesModel.get('animation');
  33799. var isAreaChart = !areaStyleModel.isEmpty();
  33800. var valueOrigin = areaStyleModel.get('origin');
  33801. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  33802. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  33803. var showSymbol = seriesModel.get('showSymbol');
  33804. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  33805. var oldData = this._data;
  33806. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  33807. if (el.__temp) {
  33808. group.remove(el);
  33809. oldData.setItemGraphicEl(idx, null);
  33810. }
  33811. }); // Remove previous created symbols if showSymbol changed to false
  33812. if (!showSymbol) {
  33813. symbolDraw.remove();
  33814. }
  33815. group.add(lineGroup); // FIXME step not support polar
  33816. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  33817. var clipShapeForSymbol;
  33818. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  33819. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  33820. // See #7913 and `test/dataZoom-clip.html`.
  33821. if (clipShapeForSymbol.width != null) {
  33822. clipShapeForSymbol.x -= 0.1;
  33823. clipShapeForSymbol.y -= 0.1;
  33824. clipShapeForSymbol.width += 0.2;
  33825. clipShapeForSymbol.height += 0.2;
  33826. } else if (clipShapeForSymbol.r0) {
  33827. clipShapeForSymbol.r0 -= 0.5;
  33828. clipShapeForSymbol.r += 0.5;
  33829. }
  33830. }
  33831. this._clipShapeForSymbol = clipShapeForSymbol;
  33832. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  33833. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  33834. showSymbol && symbolDraw.updateData(data, {
  33835. isIgnore: isIgnoreFunc,
  33836. clipShape: clipShapeForSymbol,
  33837. disableAnimation: true,
  33838. getSymbolPoint: function (idx) {
  33839. return [points[idx * 2], points[idx * 2 + 1]];
  33840. }
  33841. });
  33842. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  33843. if (step) {
  33844. // TODO If stacked series is not step
  33845. points = turnPointsIntoStep(points, coordSys, step);
  33846. if (stackedOnPoints) {
  33847. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  33848. }
  33849. }
  33850. polyline = this._newPolyline(points);
  33851. if (isAreaChart) {
  33852. polygon = this._newPolygon(points, stackedOnPoints);
  33853. } // NOTE: Must update _endLabel before setClipPath.
  33854. if (!isCoordSysPolar) {
  33855. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  33856. }
  33857. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  33858. } else {
  33859. if (isAreaChart && !polygon) {
  33860. // If areaStyle is added
  33861. polygon = this._newPolygon(points, stackedOnPoints);
  33862. } else if (polygon && !isAreaChart) {
  33863. // If areaStyle is removed
  33864. lineGroup.remove(polygon);
  33865. polygon = this._polygon = null;
  33866. } // NOTE: Must update _endLabel before setClipPath.
  33867. if (!isCoordSysPolar) {
  33868. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  33869. } // Update clipPath
  33870. lineGroup.setClipPath(createLineClipPath(this, coordSys, false, seriesModel)); // Always update, or it is wrong in the case turning on legend
  33871. // because points are not changed
  33872. showSymbol && symbolDraw.updateData(data, {
  33873. isIgnore: isIgnoreFunc,
  33874. clipShape: clipShapeForSymbol,
  33875. disableAnimation: true,
  33876. getSymbolPoint: function (idx) {
  33877. return [points[idx * 2], points[idx * 2 + 1]];
  33878. }
  33879. }); // In the case data zoom triggerred refreshing frequently
  33880. // Data may not change if line has a category axis. So it should animate nothing
  33881. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  33882. if (hasAnimation) {
  33883. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin);
  33884. } else {
  33885. // Not do it in update with animation
  33886. if (step) {
  33887. // TODO If stacked series is not step
  33888. points = turnPointsIntoStep(points, coordSys, step);
  33889. if (stackedOnPoints) {
  33890. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  33891. }
  33892. }
  33893. polyline.setShape({
  33894. points: points
  33895. });
  33896. polygon && polygon.setShape({
  33897. points: points,
  33898. stackedOnPoints: stackedOnPoints
  33899. });
  33900. }
  33901. }
  33902. }
  33903. var focus = seriesModel.get(['emphasis', 'focus']);
  33904. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  33905. polyline.useStyle(defaults( // Use color in lineStyle first
  33906. lineStyleModel.getLineStyle(), {
  33907. fill: 'none',
  33908. stroke: visualColor,
  33909. lineJoin: 'bevel'
  33910. }));
  33911. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  33912. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  33913. var emphasisLineStyle = polyline.getState('emphasis').style;
  33914. emphasisLineStyle.lineWidth = polyline.style.lineWidth + 1;
  33915. } // Needs seriesIndex for focus
  33916. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  33917. enableHoverEmphasis(polyline, focus, blurScope);
  33918. var smooth = getSmooth(seriesModel.get('smooth'));
  33919. var smoothMonotone = seriesModel.get('smoothMonotone');
  33920. var connectNulls = seriesModel.get('connectNulls');
  33921. polyline.setShape({
  33922. smooth: smooth,
  33923. smoothMonotone: smoothMonotone,
  33924. connectNulls: connectNulls
  33925. });
  33926. if (polygon) {
  33927. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  33928. var stackedOnSmooth = 0;
  33929. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  33930. fill: visualColor,
  33931. opacity: 0.7,
  33932. lineJoin: 'bevel',
  33933. decal: data.getVisual('style').decal
  33934. }));
  33935. if (stackedOnSeries) {
  33936. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  33937. }
  33938. polygon.setShape({
  33939. smooth: smooth,
  33940. stackedOnSmooth: stackedOnSmooth,
  33941. smoothMonotone: smoothMonotone,
  33942. connectNulls: connectNulls
  33943. });
  33944. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  33945. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  33946. enableHoverEmphasis(polygon, focus, blurScope);
  33947. }
  33948. var changePolyState = function (toState) {
  33949. _this._changePolyState(toState);
  33950. };
  33951. data.eachItemGraphicEl(function (el) {
  33952. // Switch polyline / polygon state if element changed its state.
  33953. el && (el.onHoverStateChange = changePolyState);
  33954. });
  33955. this._polyline.onHoverStateChange = changePolyState;
  33956. this._data = data; // Save the coordinate system for transition animation when data changed
  33957. this._coordSys = coordSys;
  33958. this._stackedOnPoints = stackedOnPoints;
  33959. this._points = points;
  33960. this._step = step;
  33961. this._valueOrigin = valueOrigin;
  33962. };
  33963. LineView.prototype.dispose = function () {};
  33964. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  33965. var data = seriesModel.getData();
  33966. var dataIndex = queryDataIndex(data, payload);
  33967. this._changePolyState('emphasis');
  33968. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  33969. var points = data.getLayout('points');
  33970. var symbol = data.getItemGraphicEl(dataIndex);
  33971. if (!symbol) {
  33972. // Create a temporary symbol if it is not exists
  33973. var x = points[dataIndex * 2];
  33974. var y = points[dataIndex * 2 + 1];
  33975. if (isNaN(x) || isNaN(y)) {
  33976. // Null data
  33977. return;
  33978. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  33979. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  33980. return;
  33981. }
  33982. symbol = new Symbol(data, dataIndex);
  33983. symbol.x = x;
  33984. symbol.y = y;
  33985. symbol.setZ(seriesModel.get('zlevel'), seriesModel.get('z'));
  33986. symbol.__temp = true;
  33987. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  33988. symbol.stopSymbolAnimation(true);
  33989. this.group.add(symbol);
  33990. }
  33991. symbol.highlight();
  33992. } else {
  33993. // Highlight whole series
  33994. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  33995. }
  33996. };
  33997. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  33998. var data = seriesModel.getData();
  33999. var dataIndex = queryDataIndex(data, payload);
  34000. this._changePolyState('normal');
  34001. if (dataIndex != null && dataIndex >= 0) {
  34002. var symbol = data.getItemGraphicEl(dataIndex);
  34003. if (symbol) {
  34004. if (symbol.__temp) {
  34005. data.setItemGraphicEl(dataIndex, null);
  34006. this.group.remove(symbol);
  34007. } else {
  34008. symbol.downplay();
  34009. }
  34010. }
  34011. } else {
  34012. // FIXME
  34013. // can not downplay completely.
  34014. // Downplay whole series
  34015. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  34016. }
  34017. };
  34018. LineView.prototype._changePolyState = function (toState) {
  34019. var polygon = this._polygon;
  34020. setStatesFlag(this._polyline, toState);
  34021. polygon && setStatesFlag(polygon, toState);
  34022. };
  34023. LineView.prototype._newPolyline = function (points) {
  34024. var polyline = this._polyline; // Remove previous created polyline
  34025. if (polyline) {
  34026. this._lineGroup.remove(polyline);
  34027. }
  34028. polyline = new ECPolyline({
  34029. shape: {
  34030. points: points
  34031. },
  34032. segmentIgnoreThreshold: 2,
  34033. z2: 10
  34034. });
  34035. this._lineGroup.add(polyline);
  34036. this._polyline = polyline;
  34037. return polyline;
  34038. };
  34039. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  34040. var polygon = this._polygon; // Remove previous created polygon
  34041. if (polygon) {
  34042. this._lineGroup.remove(polygon);
  34043. }
  34044. polygon = new ECPolygon({
  34045. shape: {
  34046. points: points,
  34047. stackedOnPoints: stackedOnPoints
  34048. },
  34049. segmentIgnoreThreshold: 2
  34050. });
  34051. this._lineGroup.add(polygon);
  34052. this._polygon = polygon;
  34053. return polygon;
  34054. };
  34055. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  34056. var isHorizontalOrRadial;
  34057. var isCoordSysPolar;
  34058. var baseAxis = coordSys.getBaseAxis();
  34059. var isAxisInverse = baseAxis.inverse;
  34060. if (coordSys.type === 'cartesian2d') {
  34061. isHorizontalOrRadial = baseAxis.isHorizontal();
  34062. isCoordSysPolar = false;
  34063. } else if (coordSys.type === 'polar') {
  34064. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34065. isCoordSysPolar = true;
  34066. }
  34067. var seriesModel = data.hostModel;
  34068. var seriesDuration = seriesModel.get('animationDuration');
  34069. if (typeof seriesDuration === 'function') {
  34070. seriesDuration = seriesDuration(null);
  34071. }
  34072. var seriesDalay = seriesModel.get('animationDelay') || 0;
  34073. var seriesDalayValue = typeof seriesDalay === 'function' ? seriesDalay(null) : seriesDalay;
  34074. data.eachItemGraphicEl(function (symbol, idx) {
  34075. var el = symbol;
  34076. if (el) {
  34077. var point = [symbol.x, symbol.y];
  34078. var start = void 0;
  34079. var end = void 0;
  34080. var current = void 0;
  34081. if (isCoordSysPolar) {
  34082. var polarClip = clipShape;
  34083. var coord = coordSys.pointToCoord(point);
  34084. if (isHorizontalOrRadial) {
  34085. start = polarClip.startAngle;
  34086. end = polarClip.endAngle;
  34087. current = -coord[1] / 180 * Math.PI;
  34088. } else {
  34089. start = polarClip.r0;
  34090. end = polarClip.r;
  34091. current = coord[0];
  34092. }
  34093. } else {
  34094. var gridClip = clipShape;
  34095. if (isHorizontalOrRadial) {
  34096. start = gridClip.x;
  34097. end = gridClip.x + gridClip.width;
  34098. current = symbol.x;
  34099. } else {
  34100. start = gridClip.y + gridClip.height;
  34101. end = gridClip.y;
  34102. current = symbol.y;
  34103. }
  34104. }
  34105. var ratio = end === start ? 0 : (current - start) / (end - start);
  34106. if (isAxisInverse) {
  34107. ratio = 1 - ratio;
  34108. }
  34109. var delay = typeof seriesDalay === 'function' ? seriesDalay(idx) : seriesDuration * ratio + seriesDalayValue;
  34110. var symbolPath = el.getSymbolPath();
  34111. var text = symbolPath.getTextContent();
  34112. el.attr({
  34113. scaleX: 0,
  34114. scaleY: 0
  34115. });
  34116. el.animateTo({
  34117. scaleX: 1,
  34118. scaleY: 1
  34119. }, {
  34120. duration: 200,
  34121. delay: delay
  34122. });
  34123. if (text) {
  34124. text.animateFrom({
  34125. style: {
  34126. opacity: 0
  34127. }
  34128. }, {
  34129. duration: 300,
  34130. delay: delay
  34131. });
  34132. }
  34133. symbolPath.disableLabelAnimation = true;
  34134. }
  34135. });
  34136. };
  34137. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  34138. var endLabelModel = seriesModel.getModel('endLabel');
  34139. if (endLabelModel.get('show')) {
  34140. var data_2 = seriesModel.getData();
  34141. var polyline = this._polyline;
  34142. var endLabel = this._endLabel;
  34143. if (!endLabel) {
  34144. endLabel = this._endLabel = new ZRText({
  34145. z2: 200 // should be higher than item symbol
  34146. });
  34147. endLabel.ignoreClip = true;
  34148. polyline.setTextContent(this._endLabel);
  34149. polyline.disableLabelAnimation = true;
  34150. } // Find last non-NaN data to display data
  34151. var dataIndex = getLastIndexNotNull(data_2.getLayout('points'));
  34152. if (dataIndex >= 0) {
  34153. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  34154. inheritColor: inheritColor,
  34155. labelFetcher: seriesModel,
  34156. labelDataIndex: dataIndex,
  34157. defaultText: function (dataIndex, opt, interpolatedValue) {
  34158. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  34159. },
  34160. enableTextSetter: true
  34161. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  34162. polyline.textConfig.position = null;
  34163. }
  34164. } else if (this._endLabel) {
  34165. this._polyline.removeTextContent();
  34166. this._endLabel = null;
  34167. }
  34168. };
  34169. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  34170. var endLabel = this._endLabel;
  34171. var polyline = this._polyline;
  34172. if (endLabel) {
  34173. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  34174. // The label is not prepared at this time.
  34175. if (percent < 1 && animationRecord.originalX == null) {
  34176. animationRecord.originalX = endLabel.x;
  34177. animationRecord.originalY = endLabel.y;
  34178. }
  34179. var points = data.getLayout('points');
  34180. var seriesModel = data.hostModel;
  34181. var connectNulls = seriesModel.get('connectNulls');
  34182. var precision = endLabelModel.get('precision');
  34183. var distance = endLabelModel.get('distance') || 0;
  34184. var baseAxis = coordSys.getBaseAxis();
  34185. var isHorizontal = baseAxis.isHorizontal();
  34186. var isBaseInversed = baseAxis.inverse;
  34187. var clipShape = clipRect.shape;
  34188. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  34189. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  34190. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  34191. var dim = isHorizontal ? 'x' : 'y';
  34192. var dataIndexRange = getIndexRange(points, xOrY, dim);
  34193. var indices = dataIndexRange.range;
  34194. var diff = indices[1] - indices[0];
  34195. var value = void 0;
  34196. if (diff >= 1) {
  34197. // diff > 1 && connectNulls, which is on the null data.
  34198. if (diff > 1 && !connectNulls) {
  34199. var pt = getPointAtIndex(points, indices[0]);
  34200. endLabel.attr({
  34201. x: pt[0] + distanceX,
  34202. y: pt[1] + distanceY
  34203. });
  34204. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  34205. } else {
  34206. var pt = polyline.getPointOn(xOrY, dim);
  34207. pt && endLabel.attr({
  34208. x: pt[0] + distanceX,
  34209. y: pt[1] + distanceY
  34210. });
  34211. var startValue = seriesModel.getRawValue(indices[0]);
  34212. var endValue = seriesModel.getRawValue(indices[1]);
  34213. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  34214. }
  34215. animationRecord.lastFrameIndex = indices[0];
  34216. } else {
  34217. // If diff <= 0, which is the range is not found(Include NaN)
  34218. // Choose the first point or last point.
  34219. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  34220. var pt = getPointAtIndex(points, idx);
  34221. valueAnimation && (value = seriesModel.getRawValue(idx));
  34222. endLabel.attr({
  34223. x: pt[0] + distanceX,
  34224. y: pt[1] + distanceY
  34225. });
  34226. }
  34227. if (valueAnimation) {
  34228. labelInner(endLabel).setLabelText(value);
  34229. }
  34230. }
  34231. };
  34232. /**
  34233. * @private
  34234. */
  34235. // FIXME Two value axis
  34236. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34237. var polyline = this._polyline;
  34238. var polygon = this._polygon;
  34239. var seriesModel = data.hostModel;
  34240. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin, valueOrigin);
  34241. var current = diff.current;
  34242. var stackedOnCurrent = diff.stackedOnCurrent;
  34243. var next = diff.next;
  34244. var stackedOnNext = diff.stackedOnNext;
  34245. if (step) {
  34246. // TODO If stacked series is not step
  34247. current = turnPointsIntoStep(diff.current, coordSys, step);
  34248. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34249. next = turnPointsIntoStep(diff.next, coordSys, step);
  34250. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34251. } // Don't apply animation if diff is large.
  34252. // For better result and avoid memory explosion problems like
  34253. // https://github.com/apache/incubator-echarts/issues/12229
  34254. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  34255. polyline.setShape({
  34256. points: next
  34257. });
  34258. if (polygon) {
  34259. polygon.setShape({
  34260. points: next,
  34261. stackedOnPoints: stackedOnNext
  34262. });
  34263. }
  34264. return;
  34265. }
  34266. polyline.shape.__points = diff.current;
  34267. polyline.shape.points = current;
  34268. var target = {
  34269. shape: {
  34270. points: next
  34271. }
  34272. }; // Also animate the original points.
  34273. // If points reference is changed when turning into step line.
  34274. if (diff.current !== current) {
  34275. target.shape.__points = diff.next;
  34276. } // Stop previous animation.
  34277. polyline.stopAnimation();
  34278. updateProps(polyline, target, seriesModel);
  34279. if (polygon) {
  34280. polygon.setShape({
  34281. // Reuse the points with polyline.
  34282. points: current,
  34283. stackedOnPoints: stackedOnCurrent
  34284. });
  34285. polygon.stopAnimation();
  34286. updateProps(polygon, {
  34287. shape: {
  34288. stackedOnPoints: stackedOnNext
  34289. }
  34290. }, seriesModel); // If use attr directly in updateProps.
  34291. if (polyline.shape.points !== polygon.shape.points) {
  34292. polygon.shape.points = polyline.shape.points;
  34293. }
  34294. }
  34295. var updatedDataInfo = [];
  34296. var diffStatus = diff.status;
  34297. for (var i = 0; i < diffStatus.length; i++) {
  34298. var cmd = diffStatus[i].cmd;
  34299. if (cmd === '=') {
  34300. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34301. if (el) {
  34302. updatedDataInfo.push({
  34303. el: el,
  34304. ptIdx: i // Index of points
  34305. });
  34306. }
  34307. }
  34308. }
  34309. if (polyline.animators && polyline.animators.length) {
  34310. polyline.animators[0].during(function () {
  34311. polygon && polygon.dirtyShape();
  34312. var points = polyline.shape.__points;
  34313. for (var i = 0; i < updatedDataInfo.length; i++) {
  34314. var el = updatedDataInfo[i].el;
  34315. var offset = updatedDataInfo[i].ptIdx * 2;
  34316. el.x = points[offset];
  34317. el.y = points[offset + 1];
  34318. el.markRedraw();
  34319. }
  34320. });
  34321. }
  34322. };
  34323. LineView.prototype.remove = function (ecModel) {
  34324. var group = this.group;
  34325. var oldData = this._data;
  34326. this._lineGroup.removeAll();
  34327. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  34328. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34329. if (el.__temp) {
  34330. group.remove(el);
  34331. oldData.setItemGraphicEl(idx, null);
  34332. }
  34333. });
  34334. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  34335. };
  34336. LineView.type = 'line';
  34337. return LineView;
  34338. }(ChartView);
  34339. function pointsLayout(seriesType, forceStoreInTypedArray) {
  34340. return {
  34341. seriesType: seriesType,
  34342. plan: createRenderPlanner(),
  34343. reset: function (seriesModel) {
  34344. var data = seriesModel.getData();
  34345. var coordSys = seriesModel.coordinateSystem;
  34346. var pipelineContext = seriesModel.pipelineContext;
  34347. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  34348. if (!coordSys) {
  34349. return;
  34350. }
  34351. var dims = map(coordSys.dimensions, function (dim) {
  34352. return data.mapDimension(dim);
  34353. }).slice(0, 2);
  34354. var dimLen = dims.length;
  34355. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34356. if (isDimensionStacked(data, dims[0]
  34357. /*, dims[1]*/
  34358. )) {
  34359. dims[0] = stackResultDim;
  34360. }
  34361. if (isDimensionStacked(data, dims[1]
  34362. /*, dims[0]*/
  34363. )) {
  34364. dims[1] = stackResultDim;
  34365. }
  34366. var dimInfo0 = data.getDimensionInfo(dims[0]);
  34367. var dimInfo1 = data.getDimensionInfo(dims[1]);
  34368. var dimIdx0 = dimInfo0 && dimInfo0.index;
  34369. var dimIdx1 = dimInfo1 && dimInfo1.index;
  34370. return dimLen && {
  34371. progress: function (params, data) {
  34372. var segCount = params.end - params.start;
  34373. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  34374. var tmpIn = [];
  34375. var tmpOut = [];
  34376. for (var i = params.start, offset = 0; i < params.end; i++) {
  34377. var point = void 0;
  34378. if (dimLen === 1) {
  34379. var x = data.getByDimIdx(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  34380. point = coordSys.dataToPoint(x, null, tmpOut);
  34381. } else {
  34382. tmpIn[0] = data.getByDimIdx(dimIdx0, i);
  34383. tmpIn[1] = data.getByDimIdx(dimIdx1, i); // Let coordinate system to handle the NaN data.
  34384. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  34385. }
  34386. if (useTypedArray) {
  34387. points[offset++] = point[0];
  34388. points[offset++] = point[1];
  34389. } else {
  34390. data.setItemLayout(i, point.slice());
  34391. }
  34392. }
  34393. useTypedArray && data.setLayout('points', points);
  34394. }
  34395. };
  34396. }
  34397. };
  34398. }
  34399. /*
  34400. * Licensed to the Apache Software Foundation (ASF) under one
  34401. * or more contributor license agreements. See the NOTICE file
  34402. * distributed with this work for additional information
  34403. * regarding copyright ownership. The ASF licenses this file
  34404. * to you under the Apache License, Version 2.0 (the
  34405. * "License"); you may not use this file except in compliance
  34406. * with the License. You may obtain a copy of the License at
  34407. *
  34408. * http://www.apache.org/licenses/LICENSE-2.0
  34409. *
  34410. * Unless required by applicable law or agreed to in writing,
  34411. * software distributed under the License is distributed on an
  34412. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34413. * KIND, either express or implied. See the License for the
  34414. * specific language governing permissions and limitations
  34415. * under the License.
  34416. */
  34417. /**
  34418. * AUTO-GENERATED FILE. DO NOT MODIFY.
  34419. */
  34420. /*
  34421. * Licensed to the Apache Software Foundation (ASF) under one
  34422. * or more contributor license agreements. See the NOTICE file
  34423. * distributed with this work for additional information
  34424. * regarding copyright ownership. The ASF licenses this file
  34425. * to you under the Apache License, Version 2.0 (the
  34426. * "License"); you may not use this file except in compliance
  34427. * with the License. You may obtain a copy of the License at
  34428. *
  34429. * http://www.apache.org/licenses/LICENSE-2.0
  34430. *
  34431. * Unless required by applicable law or agreed to in writing,
  34432. * software distributed under the License is distributed on an
  34433. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34434. * KIND, either express or implied. See the License for the
  34435. * specific language governing permissions and limitations
  34436. * under the License.
  34437. */
  34438. var samplers = {
  34439. average: function (frame) {
  34440. var sum = 0;
  34441. var count = 0;
  34442. for (var i = 0; i < frame.length; i++) {
  34443. if (!isNaN(frame[i])) {
  34444. sum += frame[i];
  34445. count++;
  34446. }
  34447. } // Return NaN if count is 0
  34448. return count === 0 ? NaN : sum / count;
  34449. },
  34450. sum: function (frame) {
  34451. var sum = 0;
  34452. for (var i = 0; i < frame.length; i++) {
  34453. // Ignore NaN
  34454. sum += frame[i] || 0;
  34455. }
  34456. return sum;
  34457. },
  34458. max: function (frame) {
  34459. var max = -Infinity;
  34460. for (var i = 0; i < frame.length; i++) {
  34461. frame[i] > max && (max = frame[i]);
  34462. } // NaN will cause illegal axis extent.
  34463. return isFinite(max) ? max : NaN;
  34464. },
  34465. min: function (frame) {
  34466. var min = Infinity;
  34467. for (var i = 0; i < frame.length; i++) {
  34468. frame[i] < min && (min = frame[i]);
  34469. } // NaN will cause illegal axis extent.
  34470. return isFinite(min) ? min : NaN;
  34471. },
  34472. // TODO
  34473. // Median
  34474. nearest: function (frame) {
  34475. return frame[0];
  34476. }
  34477. };
  34478. var indexSampler = function (frame) {
  34479. return Math.round(frame.length / 2);
  34480. };
  34481. function dataSample(seriesType) {
  34482. return {
  34483. seriesType: seriesType,
  34484. // FIXME:TS never used, so comment it
  34485. // modifyOutputEnd: true,
  34486. reset: function (seriesModel, ecModel, api) {
  34487. var data = seriesModel.getData();
  34488. var sampling = seriesModel.get('sampling');
  34489. var coordSys = seriesModel.coordinateSystem;
  34490. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  34491. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  34492. var baseAxis = coordSys.getBaseAxis();
  34493. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34494. var extent = baseAxis.getExtent();
  34495. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  34496. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  34497. var rate = Math.round(count / size);
  34498. if (rate > 1) {
  34499. if (sampling === 'lttb') {
  34500. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  34501. }
  34502. var sampler = void 0;
  34503. if (typeof sampling === 'string') {
  34504. sampler = samplers[sampling];
  34505. } else if (typeof sampling === 'function') {
  34506. sampler = sampling;
  34507. }
  34508. if (sampler) {
  34509. // Only support sample the first dim mapped from value axis.
  34510. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  34511. }
  34512. }
  34513. }
  34514. }
  34515. };
  34516. }
  34517. function install$1(registers) {
  34518. registers.registerChartView(LineView);
  34519. registers.registerSeriesModel(LineSeriesModel);
  34520. registers.registerLayout(pointsLayout('line', true)); // Down sample after filter
  34521. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  34522. }
  34523. var BaseBarSeriesModel =
  34524. /** @class */
  34525. function (_super) {
  34526. __extends(BaseBarSeriesModel, _super);
  34527. function BaseBarSeriesModel() {
  34528. var _this = _super !== null && _super.apply(this, arguments) || this;
  34529. _this.type = BaseBarSeriesModel.type;
  34530. return _this;
  34531. }
  34532. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  34533. return createListFromArray(this.getSource(), this, {
  34534. useEncodeDefaulter: true
  34535. });
  34536. };
  34537. BaseBarSeriesModel.prototype.getMarkerPosition = function (value) {
  34538. var coordSys = this.coordinateSystem;
  34539. if (coordSys) {
  34540. // PENDING if clamp ?
  34541. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  34542. var data = this.getData();
  34543. var offset = data.getLayout('offset');
  34544. var size = data.getLayout('size');
  34545. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  34546. pt[offsetIndex] += offset + size / 2;
  34547. return pt;
  34548. }
  34549. return [NaN, NaN];
  34550. };
  34551. BaseBarSeriesModel.type = 'series.__base_bar__';
  34552. BaseBarSeriesModel.defaultOption = {
  34553. zlevel: 0,
  34554. z: 2,
  34555. coordinateSystem: 'cartesian2d',
  34556. legendHoverLink: true,
  34557. // stack: null
  34558. // Cartesian coordinate system
  34559. // xAxisIndex: 0,
  34560. // yAxisIndex: 0,
  34561. barMinHeight: 0,
  34562. barMinAngle: 0,
  34563. // cursor: null,
  34564. large: false,
  34565. largeThreshold: 400,
  34566. progressive: 3e3,
  34567. progressiveChunkMode: 'mod'
  34568. };
  34569. return BaseBarSeriesModel;
  34570. }(SeriesModel);
  34571. SeriesModel.registerClass(BaseBarSeriesModel);
  34572. var BarSeriesModel =
  34573. /** @class */
  34574. function (_super) {
  34575. __extends(BarSeriesModel, _super);
  34576. function BarSeriesModel() {
  34577. var _this = _super !== null && _super.apply(this, arguments) || this;
  34578. _this.type = BarSeriesModel.type;
  34579. return _this;
  34580. }
  34581. BarSeriesModel.prototype.getInitialData = function () {
  34582. return createListFromArray(this.getSource(), this, {
  34583. useEncodeDefaulter: true,
  34584. createInvertedIndices: !!this.get('realtimeSort', true) || null
  34585. });
  34586. };
  34587. /**
  34588. * @override
  34589. */
  34590. BarSeriesModel.prototype.getProgressive = function () {
  34591. // Do not support progressive in normal mode.
  34592. return this.get('large') ? this.get('progressive') : false;
  34593. };
  34594. /**
  34595. * @override
  34596. */
  34597. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  34598. // Do not support progressive in normal mode.
  34599. var progressiveThreshold = this.get('progressiveThreshold');
  34600. var largeThreshold = this.get('largeThreshold');
  34601. if (largeThreshold > progressiveThreshold) {
  34602. progressiveThreshold = largeThreshold;
  34603. }
  34604. return progressiveThreshold;
  34605. };
  34606. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  34607. return selectors.rect(data.getItemLayout(dataIndex));
  34608. };
  34609. BarSeriesModel.type = 'series.bar';
  34610. BarSeriesModel.dependencies = ['grid', 'polar'];
  34611. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  34612. // If clipped
  34613. // Only available on cartesian2d
  34614. clip: true,
  34615. roundCap: false,
  34616. showBackground: false,
  34617. backgroundStyle: {
  34618. color: 'rgba(180, 180, 180, 0.2)',
  34619. borderColor: null,
  34620. borderWidth: 0,
  34621. borderType: 'solid',
  34622. borderRadius: 0,
  34623. shadowBlur: 0,
  34624. shadowColor: null,
  34625. shadowOffsetX: 0,
  34626. shadowOffsetY: 0,
  34627. opacity: 1
  34628. },
  34629. select: {
  34630. itemStyle: {
  34631. borderColor: '#212121'
  34632. }
  34633. },
  34634. realtimeSort: false
  34635. });
  34636. return BarSeriesModel;
  34637. }(BaseBarSeriesModel);
  34638. /**
  34639. * Sausage: similar to sector, but have half circle on both sides
  34640. */
  34641. var SausageShape =
  34642. /** @class */
  34643. function () {
  34644. function SausageShape() {
  34645. this.cx = 0;
  34646. this.cy = 0;
  34647. this.r0 = 0;
  34648. this.r = 0;
  34649. this.startAngle = 0;
  34650. this.endAngle = Math.PI * 2;
  34651. this.clockwise = true;
  34652. }
  34653. return SausageShape;
  34654. }();
  34655. var SausagePath =
  34656. /** @class */
  34657. function (_super) {
  34658. __extends(SausagePath, _super);
  34659. function SausagePath(opts) {
  34660. var _this = _super.call(this, opts) || this;
  34661. _this.type = 'sausage';
  34662. return _this;
  34663. }
  34664. SausagePath.prototype.getDefaultShape = function () {
  34665. return new SausageShape();
  34666. };
  34667. SausagePath.prototype.buildPath = function (ctx, shape) {
  34668. var x = shape.cx;
  34669. var y = shape.cy;
  34670. var r0 = Math.max(shape.r0 || 0, 0);
  34671. var r = Math.max(shape.r, 0);
  34672. var dr = (r - r0) * 0.5;
  34673. var rCenter = r0 + dr;
  34674. var startAngle = shape.startAngle;
  34675. var endAngle = shape.endAngle;
  34676. var clockwise = shape.clockwise;
  34677. var unitStartX = Math.cos(startAngle);
  34678. var unitStartY = Math.sin(startAngle);
  34679. var unitEndX = Math.cos(endAngle);
  34680. var unitEndY = Math.sin(endAngle);
  34681. var lessThanCircle = clockwise ? endAngle - startAngle < Math.PI * 2 : startAngle - endAngle < Math.PI * 2;
  34682. if (lessThanCircle) {
  34683. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  34684. ctx.arc(unitStartX * rCenter + x, unitStartY * rCenter + y, dr, -Math.PI + startAngle, startAngle, !clockwise);
  34685. }
  34686. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  34687. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  34688. ctx.arc(unitEndX * rCenter + x, unitEndY * rCenter + y, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  34689. if (r0 !== 0) {
  34690. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  34691. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  34692. }
  34693. ctx.closePath();
  34694. };
  34695. return SausagePath;
  34696. }(Path);
  34697. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth'];
  34698. var BAR_BORDER_RADIUS_QUERY = ['itemStyle', 'borderRadius'];
  34699. var _eventPos = [0, 0];
  34700. var mathMax$6 = Math.max;
  34701. var mathMin$6 = Math.min;
  34702. function getClipArea(coord, data) {
  34703. var coordSysClipArea = coord.getArea && coord.getArea();
  34704. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  34705. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  34706. // We should not clip this part.
  34707. // See test/bar2.html
  34708. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  34709. var expandWidth = data.getLayout('bandWidth');
  34710. if (baseAxis.isHorizontal()) {
  34711. coordSysClipArea.x -= expandWidth;
  34712. coordSysClipArea.width += expandWidth * 2;
  34713. } else {
  34714. coordSysClipArea.y -= expandWidth;
  34715. coordSysClipArea.height += expandWidth * 2;
  34716. }
  34717. }
  34718. }
  34719. return coordSysClipArea;
  34720. }
  34721. var BarView =
  34722. /** @class */
  34723. function (_super) {
  34724. __extends(BarView, _super);
  34725. function BarView() {
  34726. var _this = _super.call(this) || this;
  34727. _this.type = BarView.type;
  34728. _this._isFirstFrame = true;
  34729. return _this;
  34730. }
  34731. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  34732. this._model = seriesModel;
  34733. this._removeOnRenderedListener(api);
  34734. this._updateDrawMode(seriesModel);
  34735. var coordinateSystemType = seriesModel.get('coordinateSystem');
  34736. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  34737. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  34738. } else if ("development" !== 'production') {
  34739. warn('Only cartesian2d and polar supported for bar.');
  34740. }
  34741. };
  34742. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  34743. this._clear();
  34744. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  34745. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  34746. this._updateLargeClip(seriesModel);
  34747. };
  34748. BarView.prototype.incrementalRender = function (params, seriesModel) {
  34749. // Do not support progressive in normal mode.
  34750. this._incrementalRenderLarge(params, seriesModel);
  34751. };
  34752. BarView.prototype._updateDrawMode = function (seriesModel) {
  34753. var isLargeDraw = seriesModel.pipelineContext.large;
  34754. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  34755. this._isLargeDraw = isLargeDraw;
  34756. this._clear();
  34757. }
  34758. };
  34759. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  34760. var group = this.group;
  34761. var data = seriesModel.getData();
  34762. var oldData = this._data;
  34763. var coord = seriesModel.coordinateSystem;
  34764. var baseAxis = coord.getBaseAxis();
  34765. var isHorizontalOrRadial;
  34766. if (coord.type === 'cartesian2d') {
  34767. isHorizontalOrRadial = baseAxis.isHorizontal();
  34768. } else if (coord.type === 'polar') {
  34769. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34770. }
  34771. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  34772. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  34773. if (realtimeSortCfg) {
  34774. this._enableRealtimeSort(realtimeSortCfg, data, api);
  34775. }
  34776. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  34777. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  34778. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  34779. // And don't want the label are clipped.
  34780. var roundCap = seriesModel.get('roundCap', true);
  34781. var drawBackground = seriesModel.get('showBackground', true);
  34782. var backgroundModel = seriesModel.getModel('backgroundStyle');
  34783. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  34784. var bgEls = [];
  34785. var oldBgEls = this._backgroundEls;
  34786. var isInitSort = payload && payload.isInitSort;
  34787. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  34788. function createBackground(dataIndex) {
  34789. var bgLayout = getLayout[coord.type](data, dataIndex);
  34790. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  34791. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  34792. if (coord.type === 'cartesian2d') {
  34793. bgEl.setShape('r', barBorderRadius);
  34794. }
  34795. bgEls[dataIndex] = bgEl;
  34796. return bgEl;
  34797. }
  34798. data.diff(oldData).add(function (dataIndex) {
  34799. var itemModel = data.getItemModel(dataIndex);
  34800. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  34801. if (drawBackground) {
  34802. createBackground(dataIndex);
  34803. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  34804. if (!data.hasValue(dataIndex)) {
  34805. return;
  34806. }
  34807. var isClipped = false;
  34808. if (needsClip) {
  34809. // Clip will modify the layout params.
  34810. // And return a boolean to determine if the shape are fully clipped.
  34811. isClipped = clip[coord.type](coordSysClipArea, layout);
  34812. }
  34813. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  34814. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  34815. if (isInitSort) {
  34816. el.attr({
  34817. shape: layout
  34818. });
  34819. } else if (realtimeSortCfg) {
  34820. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  34821. } else {
  34822. initProps(el, {
  34823. shape: layout
  34824. }, seriesModel, dataIndex);
  34825. }
  34826. data.setItemGraphicEl(dataIndex, el);
  34827. group.add(el);
  34828. el.ignore = isClipped;
  34829. }).update(function (newIndex, oldIndex) {
  34830. var itemModel = data.getItemModel(newIndex);
  34831. var layout = getLayout[coord.type](data, newIndex, itemModel);
  34832. if (drawBackground) {
  34833. var bgEl = void 0;
  34834. if (oldBgEls.length === 0) {
  34835. bgEl = createBackground(oldIndex);
  34836. } else {
  34837. bgEl = oldBgEls[oldIndex];
  34838. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  34839. if (coord.type === 'cartesian2d') {
  34840. bgEl.setShape('r', barBorderRadius);
  34841. }
  34842. bgEls[newIndex] = bgEl;
  34843. }
  34844. var bgLayout = getLayout[coord.type](data, newIndex);
  34845. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  34846. updateProps(bgEl, {
  34847. shape: shape
  34848. }, animationModel, newIndex);
  34849. }
  34850. var el = oldData.getItemGraphicEl(oldIndex);
  34851. if (!data.hasValue(newIndex)) {
  34852. group.remove(el);
  34853. el = null;
  34854. return;
  34855. }
  34856. var isClipped = false;
  34857. if (needsClip) {
  34858. isClipped = clip[coord.type](coordSysClipArea, layout);
  34859. if (isClipped) {
  34860. group.remove(el);
  34861. }
  34862. }
  34863. if (!el) {
  34864. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  34865. } // Not change anything if only order changed.
  34866. // Especially not change label.
  34867. if (!isChangeOrder) {
  34868. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  34869. }
  34870. if (isInitSort) {
  34871. el.attr({
  34872. shape: layout
  34873. });
  34874. } else if (realtimeSortCfg) {
  34875. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  34876. } else {
  34877. updateProps(el, {
  34878. shape: layout
  34879. }, seriesModel, newIndex, null);
  34880. }
  34881. data.setItemGraphicEl(newIndex, el);
  34882. el.ignore = isClipped;
  34883. group.add(el);
  34884. }).remove(function (dataIndex) {
  34885. var el = oldData.getItemGraphicEl(dataIndex);
  34886. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  34887. }).execute();
  34888. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  34889. bgGroup.removeAll();
  34890. for (var i = 0; i < bgEls.length; ++i) {
  34891. bgGroup.add(bgEls[i]);
  34892. }
  34893. group.add(bgGroup);
  34894. this._backgroundEls = bgEls;
  34895. this._data = data;
  34896. };
  34897. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  34898. this._clear();
  34899. createLarge(seriesModel, this.group);
  34900. this._updateLargeClip(seriesModel);
  34901. };
  34902. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  34903. this._removeBackground();
  34904. createLarge(seriesModel, this.group, true);
  34905. };
  34906. BarView.prototype._updateLargeClip = function (seriesModel) {
  34907. // Use clipPath in large mode.
  34908. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  34909. if (clipPath) {
  34910. this.group.setClipPath(clipPath);
  34911. } else {
  34912. this.group.removeClipPath();
  34913. }
  34914. };
  34915. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  34916. var _this = this; // If no data in the first frame, wait for data to initSort
  34917. if (!data.count()) {
  34918. return;
  34919. }
  34920. var baseAxis = realtimeSortCfg.baseAxis;
  34921. if (this._isFirstFrame) {
  34922. this._dispatchInitSort(data, realtimeSortCfg, api);
  34923. this._isFirstFrame = false;
  34924. } else {
  34925. var orderMapping_1 = function (idx) {
  34926. var el = data.getItemGraphicEl(idx);
  34927. if (el) {
  34928. var shape = el.shape; // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  34929. return (baseAxis.isHorizontal() // The result should be consistent with the initial sort by data value.
  34930. // Do not support the case that both positive and negative exist.
  34931. ? Math.abs(shape.height) : Math.abs(shape.width)) || 0;
  34932. } else {
  34933. return 0;
  34934. }
  34935. };
  34936. this._onRendered = function () {
  34937. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  34938. };
  34939. api.getZr().on('rendered', this._onRendered);
  34940. }
  34941. };
  34942. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  34943. var info = [];
  34944. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  34945. var mappedValue = orderMapping(dataIdx);
  34946. mappedValue = mappedValue == null ? NaN : mappedValue;
  34947. info.push({
  34948. dataIndex: dataIdx,
  34949. mappedValue: mappedValue,
  34950. ordinalNumber: ordinalNumber
  34951. });
  34952. });
  34953. info.sort(function (a, b) {
  34954. // If NaN, it will be treated as min val.
  34955. return b.mappedValue - a.mappedValue;
  34956. });
  34957. return {
  34958. ordinalNumbers: map(info, function (item) {
  34959. return item.ordinalNumber;
  34960. })
  34961. };
  34962. };
  34963. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  34964. var scale = baseAxis.scale;
  34965. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  34966. var lastValue = Number.MAX_VALUE;
  34967. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  34968. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  34969. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  34970. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  34971. : orderMapping(data.indexOfRawIndex(rawIdx));
  34972. if (value > lastValue) {
  34973. return true;
  34974. }
  34975. lastValue = value;
  34976. }
  34977. return false;
  34978. };
  34979. /*
  34980. * Consider the case when A and B changed order, whose representing
  34981. * bars are both out of sight, we don't wish to trigger reorder action
  34982. * as long as the order in the view doesn't change.
  34983. */
  34984. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  34985. var scale = baseAxis.scale;
  34986. var extent = scale.getExtent();
  34987. var tickNum = Math.max(0, extent[0]);
  34988. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  34989. for (; tickNum <= tickMax; ++tickNum) {
  34990. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  34991. return true;
  34992. }
  34993. }
  34994. };
  34995. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  34996. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  34997. return;
  34998. }
  34999. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  35000. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  35001. this._removeOnRenderedListener(api);
  35002. api.dispatchAction({
  35003. type: 'changeAxisOrder',
  35004. componentType: baseAxis.dim + 'Axis',
  35005. axisId: baseAxis.index,
  35006. sortInfo: sortInfo
  35007. });
  35008. }
  35009. };
  35010. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  35011. var baseAxis = realtimeSortCfg.baseAxis;
  35012. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  35013. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  35014. });
  35015. api.dispatchAction({
  35016. type: 'changeAxisOrder',
  35017. componentType: baseAxis.dim + 'Axis',
  35018. isInitSort: true,
  35019. axisId: baseAxis.index,
  35020. sortInfo: sortResult,
  35021. animation: {
  35022. // Update the axis label from the natural initial layout to
  35023. // sorted layout should has no animation.
  35024. duration: 0
  35025. }
  35026. });
  35027. };
  35028. BarView.prototype.remove = function (ecModel, api) {
  35029. this._clear(this._model);
  35030. this._removeOnRenderedListener(api);
  35031. };
  35032. BarView.prototype.dispose = function (ecModel, api) {
  35033. this._removeOnRenderedListener(api);
  35034. };
  35035. BarView.prototype._removeOnRenderedListener = function (api) {
  35036. if (this._onRendered) {
  35037. api.getZr().off('rendered', this._onRendered);
  35038. this._onRendered = null;
  35039. }
  35040. };
  35041. BarView.prototype._clear = function (model) {
  35042. var group = this.group;
  35043. var data = this._data;
  35044. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  35045. this._removeBackground();
  35046. this._backgroundEls = [];
  35047. data.eachItemGraphicEl(function (el) {
  35048. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  35049. });
  35050. } else {
  35051. group.removeAll();
  35052. }
  35053. this._data = null;
  35054. this._isFirstFrame = true;
  35055. };
  35056. BarView.prototype._removeBackground = function () {
  35057. this.group.remove(this._backgroundGroup);
  35058. this._backgroundGroup = null;
  35059. };
  35060. BarView.type = 'bar';
  35061. return BarView;
  35062. }(ChartView);
  35063. var clip = {
  35064. cartesian2d: function (coordSysBoundingRect, layout) {
  35065. var signWidth = layout.width < 0 ? -1 : 1;
  35066. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  35067. if (signWidth < 0) {
  35068. layout.x += layout.width;
  35069. layout.width = -layout.width;
  35070. }
  35071. if (signHeight < 0) {
  35072. layout.y += layout.height;
  35073. layout.height = -layout.height;
  35074. }
  35075. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  35076. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  35077. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  35078. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  35079. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  35080. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  35081. var xClipped = x2 < x;
  35082. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  35083. // But we should also place the element at the edge of the coord sys bounding rect.
  35084. // Beause if data changed and the bar show again, its transition animaiton
  35085. // will begin at this place.
  35086. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  35087. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  35088. layout.width = xClipped ? 0 : x2 - x;
  35089. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  35090. if (signWidth < 0) {
  35091. layout.x += layout.width;
  35092. layout.width = -layout.width;
  35093. }
  35094. if (signHeight < 0) {
  35095. layout.y += layout.height;
  35096. layout.height = -layout.height;
  35097. }
  35098. return xClipped || yClipped;
  35099. },
  35100. polar: function (coordSysClipArea, layout) {
  35101. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  35102. if (signR < 0) {
  35103. var tmp = layout.r;
  35104. layout.r = layout.r0;
  35105. layout.r0 = tmp;
  35106. }
  35107. var r = mathMin$6(layout.r, coordSysClipArea.r);
  35108. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  35109. layout.r = r;
  35110. layout.r0 = r0;
  35111. var clipped = r - r0 < 0; // Reverse back
  35112. if (signR < 0) {
  35113. var tmp = layout.r;
  35114. layout.r = layout.r0;
  35115. layout.r0 = tmp;
  35116. }
  35117. return clipped;
  35118. }
  35119. };
  35120. var elementCreator = {
  35121. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  35122. var rect = new Rect({
  35123. shape: extend({}, layout),
  35124. z2: 1
  35125. });
  35126. rect.__dataIndex = newIndex;
  35127. rect.name = 'item';
  35128. if (animationModel) {
  35129. var rectShape = rect.shape;
  35130. var animateProperty = isHorizontal ? 'height' : 'width';
  35131. rectShape[animateProperty] = 0;
  35132. }
  35133. return rect;
  35134. },
  35135. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  35136. // Keep the same logic with bar in catesion: use end value to control
  35137. // direction. Notice that if clockwise is true (by default), the sector
  35138. // will always draw clockwisely, no matter whether endAngle is greater
  35139. // or less than startAngle.
  35140. var clockwise = layout.startAngle < layout.endAngle;
  35141. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  35142. var sector = new ShapeClass({
  35143. shape: defaults({
  35144. clockwise: clockwise
  35145. }, layout),
  35146. z2: 1
  35147. });
  35148. sector.name = 'item'; // Animation
  35149. if (animationModel) {
  35150. var sectorShape = sector.shape;
  35151. var animateProperty = isRadial ? 'r' : 'endAngle';
  35152. var animateTarget = {};
  35153. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  35154. animateTarget[animateProperty] = layout[animateProperty];
  35155. (isUpdate ? updateProps : initProps)(sector, {
  35156. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  35157. }, animationModel);
  35158. }
  35159. return sector;
  35160. }
  35161. };
  35162. function shouldRealtimeSort(seriesModel, coordSys) {
  35163. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  35164. var baseAxis = coordSys.getBaseAxis();
  35165. if ("development" !== 'production') {
  35166. if (realtimeSortOption) {
  35167. if (baseAxis.type !== 'category') {
  35168. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  35169. }
  35170. if (coordSys.type !== 'cartesian2d') {
  35171. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  35172. }
  35173. }
  35174. }
  35175. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  35176. return {
  35177. baseAxis: baseAxis,
  35178. otherAxis: coordSys.getOtherAxis(baseAxis)
  35179. };
  35180. }
  35181. }
  35182. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  35183. var seriesTarget;
  35184. var axisTarget;
  35185. if (isHorizontal) {
  35186. axisTarget = {
  35187. x: layout.x,
  35188. width: layout.width
  35189. };
  35190. seriesTarget = {
  35191. y: layout.y,
  35192. height: layout.height
  35193. };
  35194. } else {
  35195. axisTarget = {
  35196. y: layout.y,
  35197. height: layout.height
  35198. };
  35199. seriesTarget = {
  35200. x: layout.x,
  35201. width: layout.width
  35202. };
  35203. }
  35204. if (!isChangeOrder) {
  35205. // Keep the original growth animation if only axis order changed.
  35206. // Not start a new animation.
  35207. (isUpdate ? updateProps : initProps)(el, {
  35208. shape: seriesTarget
  35209. }, seriesAnimationModel, newIndex, null);
  35210. }
  35211. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  35212. (isUpdate ? updateProps : initProps)(el, {
  35213. shape: axisTarget
  35214. }, axisAnimationModel, newIndex);
  35215. }
  35216. var getLayout = {
  35217. // itemModel is only used to get borderWidth, which is not needed
  35218. // when calculating bar background layout.
  35219. cartesian2d: function (data, dataIndex, itemModel) {
  35220. var layout = data.getItemLayout(dataIndex);
  35221. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  35222. var signX = layout.width > 0 ? 1 : -1;
  35223. var signY = layout.height > 0 ? 1 : -1;
  35224. return {
  35225. x: layout.x + signX * fixedLineWidth / 2,
  35226. y: layout.y + signY * fixedLineWidth / 2,
  35227. width: layout.width - signX * fixedLineWidth,
  35228. height: layout.height - signY * fixedLineWidth
  35229. };
  35230. },
  35231. polar: function (data, dataIndex, itemModel) {
  35232. var layout = data.getItemLayout(dataIndex);
  35233. return {
  35234. cx: layout.cx,
  35235. cy: layout.cy,
  35236. r0: layout.r0,
  35237. r: layout.r,
  35238. startAngle: layout.startAngle,
  35239. endAngle: layout.endAngle
  35240. };
  35241. }
  35242. };
  35243. function isZeroOnPolar(layout) {
  35244. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  35245. }
  35246. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar) {
  35247. var style = data.getItemVisual(dataIndex, 'style');
  35248. if (!isPolar) {
  35249. el.setShape('r', itemModel.get(BAR_BORDER_RADIUS_QUERY) || 0);
  35250. }
  35251. el.useStyle(style);
  35252. var cursorStyle = itemModel.getShallow('cursor');
  35253. cursorStyle && el.attr('cursor', cursorStyle);
  35254. if (!isPolar) {
  35255. var labelPositionOutside = isHorizontal ? layout.height > 0 ? 'bottom' : 'top' : layout.width > 0 ? 'left' : 'right';
  35256. var labelStatesModels = getLabelStatesModels(itemModel);
  35257. setLabelStyle(el, labelStatesModels, {
  35258. labelFetcher: seriesModel,
  35259. labelDataIndex: dataIndex,
  35260. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  35261. inheritColor: style.fill,
  35262. defaultOpacity: style.opacity,
  35263. defaultOutsidePosition: labelPositionOutside
  35264. });
  35265. var label = el.getTextContent();
  35266. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  35267. return getDefaultInterpolatedLabel(data, value);
  35268. });
  35269. }
  35270. var emphasisModel = itemModel.getModel(['emphasis']);
  35271. enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  35272. setStatesStylesFromModel(el, itemModel);
  35273. if (isZeroOnPolar(layout)) {
  35274. el.style.fill = 'none';
  35275. el.style.stroke = 'none';
  35276. each(el.states, function (state) {
  35277. if (state.style) {
  35278. state.style.fill = state.style.stroke = 'none';
  35279. }
  35280. });
  35281. }
  35282. } // In case width or height are too small.
  35283. function getLineWidth(itemModel, rawLayout) {
  35284. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0; // width or height may be NaN for empty data
  35285. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  35286. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  35287. return Math.min(lineWidth, width, height);
  35288. }
  35289. var LagePathShape =
  35290. /** @class */
  35291. function () {
  35292. function LagePathShape() {}
  35293. return LagePathShape;
  35294. }();
  35295. var LargePath =
  35296. /** @class */
  35297. function (_super) {
  35298. __extends(LargePath, _super);
  35299. function LargePath(opts) {
  35300. var _this = _super.call(this, opts) || this;
  35301. _this.type = 'largeBar';
  35302. return _this;
  35303. }
  35304. LargePath.prototype.getDefaultShape = function () {
  35305. return new LagePathShape();
  35306. };
  35307. LargePath.prototype.buildPath = function (ctx, shape) {
  35308. // Drawing lines is more efficient than drawing
  35309. // a whole line or drawing rects.
  35310. var points = shape.points;
  35311. var startPoint = this.__startPoint;
  35312. var baseDimIdx = this.__baseDimIdx;
  35313. for (var i = 0; i < points.length; i += 2) {
  35314. startPoint[baseDimIdx] = points[i + baseDimIdx];
  35315. ctx.moveTo(startPoint[0], startPoint[1]);
  35316. ctx.lineTo(points[i], points[i + 1]);
  35317. }
  35318. };
  35319. return LargePath;
  35320. }(Path);
  35321. function createLarge(seriesModel, group, incremental) {
  35322. // TODO support polar
  35323. var data = seriesModel.getData();
  35324. var startPoint = [];
  35325. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  35326. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  35327. var largeDataIndices = data.getLayout('largeDataIndices');
  35328. var barWidth = data.getLayout('barWidth');
  35329. var backgroundModel = seriesModel.getModel('backgroundStyle');
  35330. var drawBackground = seriesModel.get('showBackground', true);
  35331. if (drawBackground) {
  35332. var points = data.getLayout('largeBackgroundPoints');
  35333. var backgroundStartPoint = [];
  35334. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  35335. var bgEl = new LargePath({
  35336. shape: {
  35337. points: points
  35338. },
  35339. incremental: !!incremental,
  35340. silent: true,
  35341. z2: 0
  35342. });
  35343. bgEl.__startPoint = backgroundStartPoint;
  35344. bgEl.__baseDimIdx = baseDimIdx;
  35345. bgEl.__largeDataIndices = largeDataIndices;
  35346. bgEl.__barWidth = barWidth;
  35347. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  35348. group.add(bgEl);
  35349. }
  35350. var el = new LargePath({
  35351. shape: {
  35352. points: data.getLayout('largePoints')
  35353. },
  35354. incremental: !!incremental
  35355. });
  35356. el.__startPoint = startPoint;
  35357. el.__baseDimIdx = baseDimIdx;
  35358. el.__largeDataIndices = largeDataIndices;
  35359. el.__barWidth = barWidth;
  35360. group.add(el);
  35361. setLargeStyle(el, seriesModel, data); // Enable tooltip and user mouse/touch event handlers.
  35362. getECData(el).seriesIndex = seriesModel.seriesIndex;
  35363. if (!seriesModel.get('silent')) {
  35364. el.on('mousedown', largePathUpdateDataIndex);
  35365. el.on('mousemove', largePathUpdateDataIndex);
  35366. }
  35367. } // Use throttle to avoid frequently traverse to find dataIndex.
  35368. var largePathUpdateDataIndex = throttle(function (event) {
  35369. var largePath = this;
  35370. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  35371. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  35372. }, 30, false);
  35373. function largePathFindDataIndex(largePath, x, y) {
  35374. var baseDimIdx = largePath.__baseDimIdx;
  35375. var valueDimIdx = 1 - baseDimIdx;
  35376. var points = largePath.shape.points;
  35377. var largeDataIndices = largePath.__largeDataIndices;
  35378. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  35379. var startValueVal = largePath.__startPoint[valueDimIdx];
  35380. _eventPos[0] = x;
  35381. _eventPos[1] = y;
  35382. var pointerBaseVal = _eventPos[baseDimIdx];
  35383. var pointerValueVal = _eventPos[1 - baseDimIdx];
  35384. var baseLowerBound = pointerBaseVal - barWidthHalf;
  35385. var baseUpperBound = pointerBaseVal + barWidthHalf;
  35386. for (var i = 0, len = points.length / 2; i < len; i++) {
  35387. var ii = i * 2;
  35388. var barBaseVal = points[ii + baseDimIdx];
  35389. var barValueVal = points[ii + valueDimIdx];
  35390. if (barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound && (startValueVal <= barValueVal ? pointerValueVal >= startValueVal && pointerValueVal <= barValueVal : pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)) {
  35391. return largeDataIndices[i];
  35392. }
  35393. }
  35394. return -1;
  35395. }
  35396. function setLargeStyle(el, seriesModel, data) {
  35397. var globalStyle = data.getVisual('style');
  35398. el.useStyle(extend({}, globalStyle)); // Use stroke instead of fill.
  35399. el.style.fill = null;
  35400. el.style.stroke = globalStyle.fill;
  35401. el.style.lineWidth = data.getLayout('barWidth');
  35402. }
  35403. function setLargeBackgroundStyle(el, backgroundModel, data) {
  35404. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  35405. var itemStyle = backgroundModel.getItemStyle();
  35406. el.useStyle(itemStyle);
  35407. el.style.fill = null;
  35408. el.style.stroke = borderColor;
  35409. el.style.lineWidth = data.getLayout('barWidth');
  35410. }
  35411. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  35412. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  35413. var rectShape = layout;
  35414. var coordLayout = coord.getArea();
  35415. return {
  35416. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  35417. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  35418. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  35419. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  35420. };
  35421. } else {
  35422. var coordLayout = coord.getArea();
  35423. var sectorShape = layout;
  35424. return {
  35425. cx: coordLayout.cx,
  35426. cy: coordLayout.cy,
  35427. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  35428. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  35429. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  35430. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  35431. };
  35432. }
  35433. }
  35434. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  35435. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  35436. return new ElementClz({
  35437. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  35438. silent: true,
  35439. z2: 0
  35440. });
  35441. }
  35442. function install$2(registers) {
  35443. registers.registerChartView(BarView);
  35444. registers.registerSeriesModel(BarSeriesModel);
  35445. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Use higher prority to avoid to be blocked by other overall layout, which do not
  35446. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  35447. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  35448. registers.registerVisual({
  35449. seriesType: 'bar',
  35450. reset: function (seriesModel) {
  35451. // Visual coding for legend
  35452. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  35453. }
  35454. }); // Down sample after filter
  35455. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  35456. /**
  35457. * @payload
  35458. * @property {string} [componentType=series]
  35459. * @property {number} [dx]
  35460. * @property {number} [dy]
  35461. * @property {number} [zoom]
  35462. * @property {number} [originX]
  35463. * @property {number} [originY]
  35464. */
  35465. registers.registerAction({
  35466. type: 'changeAxisOrder',
  35467. event: 'changeAxisOrder',
  35468. update: 'update'
  35469. }, function (payload, ecModel) {
  35470. var componentType = payload.componentType || 'series';
  35471. ecModel.eachComponent({
  35472. mainType: componentType,
  35473. query: payload
  35474. }, function (componentModel) {
  35475. if (payload.sortInfo) {
  35476. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  35477. }
  35478. });
  35479. });
  35480. }
  35481. var PI2$7 = Math.PI * 2;
  35482. var RADIAN = Math.PI / 180;
  35483. function getViewRect(seriesModel, api) {
  35484. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  35485. width: api.getWidth(),
  35486. height: api.getHeight()
  35487. });
  35488. }
  35489. function pieLayout(seriesType, ecModel, api) {
  35490. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35491. var data = seriesModel.getData();
  35492. var valueDim = data.mapDimension('value');
  35493. var viewRect = getViewRect(seriesModel, api);
  35494. var center = seriesModel.get('center');
  35495. var radius = seriesModel.get('radius');
  35496. if (!isArray(radius)) {
  35497. radius = [0, radius];
  35498. }
  35499. if (!isArray(center)) {
  35500. center = [center, center];
  35501. }
  35502. var width = parsePercent$1(viewRect.width, api.getWidth());
  35503. var height = parsePercent$1(viewRect.height, api.getHeight());
  35504. var size = Math.min(width, height);
  35505. var cx = parsePercent$1(center[0], width) + viewRect.x;
  35506. var cy = parsePercent$1(center[1], height) + viewRect.y;
  35507. var r0 = parsePercent$1(radius[0], size / 2);
  35508. var r = parsePercent$1(radius[1], size / 2);
  35509. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  35510. var minAngle = seriesModel.get('minAngle') * RADIAN;
  35511. var validDataCount = 0;
  35512. data.each(valueDim, function (value) {
  35513. !isNaN(value) && validDataCount++;
  35514. });
  35515. var sum = data.getSum(valueDim); // Sum may be 0
  35516. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  35517. var clockwise = seriesModel.get('clockwise');
  35518. var roseType = seriesModel.get('roseType');
  35519. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  35520. var extent = data.getDataExtent(valueDim);
  35521. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  35522. var restAngle = PI2$7;
  35523. var valueSumLargerThanMinAngle = 0;
  35524. var currentAngle = startAngle;
  35525. var dir = clockwise ? 1 : -1;
  35526. data.setLayout({
  35527. viewRect: viewRect,
  35528. r: r
  35529. });
  35530. data.each(valueDim, function (value, idx) {
  35531. var angle;
  35532. if (isNaN(value)) {
  35533. data.setItemLayout(idx, {
  35534. angle: NaN,
  35535. startAngle: NaN,
  35536. endAngle: NaN,
  35537. clockwise: clockwise,
  35538. cx: cx,
  35539. cy: cy,
  35540. r0: r0,
  35541. r: roseType ? NaN : r
  35542. });
  35543. return;
  35544. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  35545. if (roseType !== 'area') {
  35546. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  35547. } else {
  35548. angle = PI2$7 / validDataCount;
  35549. }
  35550. if (angle < minAngle) {
  35551. angle = minAngle;
  35552. restAngle -= minAngle;
  35553. } else {
  35554. valueSumLargerThanMinAngle += value;
  35555. }
  35556. var endAngle = currentAngle + dir * angle;
  35557. data.setItemLayout(idx, {
  35558. angle: angle,
  35559. startAngle: currentAngle,
  35560. endAngle: endAngle,
  35561. clockwise: clockwise,
  35562. cx: cx,
  35563. cy: cy,
  35564. r0: r0,
  35565. r: roseType ? linearMap(value, extent, [r0, r]) : r
  35566. });
  35567. currentAngle = endAngle;
  35568. }); // Some sector is constrained by minAngle
  35569. // Rest sectors needs recalculate angle
  35570. if (restAngle < PI2$7 && validDataCount) {
  35571. // Average the angle if rest angle is not enough after all angles is
  35572. // Constrained by minAngle
  35573. if (restAngle <= 1e-3) {
  35574. var angle_1 = PI2$7 / validDataCount;
  35575. data.each(valueDim, function (value, idx) {
  35576. if (!isNaN(value)) {
  35577. var layout_1 = data.getItemLayout(idx);
  35578. layout_1.angle = angle_1;
  35579. layout_1.startAngle = startAngle + dir * idx * angle_1;
  35580. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  35581. }
  35582. });
  35583. } else {
  35584. unitRadian = restAngle / valueSumLargerThanMinAngle;
  35585. currentAngle = startAngle;
  35586. data.each(valueDim, function (value, idx) {
  35587. if (!isNaN(value)) {
  35588. var layout_2 = data.getItemLayout(idx);
  35589. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  35590. layout_2.startAngle = currentAngle;
  35591. layout_2.endAngle = currentAngle + dir * angle;
  35592. currentAngle += dir * angle;
  35593. }
  35594. });
  35595. }
  35596. }
  35597. });
  35598. }
  35599. /*
  35600. * Licensed to the Apache Software Foundation (ASF) under one
  35601. * or more contributor license agreements. See the NOTICE file
  35602. * distributed with this work for additional information
  35603. * regarding copyright ownership. The ASF licenses this file
  35604. * to you under the Apache License, Version 2.0 (the
  35605. * "License"); you may not use this file except in compliance
  35606. * with the License. You may obtain a copy of the License at
  35607. *
  35608. * http://www.apache.org/licenses/LICENSE-2.0
  35609. *
  35610. * Unless required by applicable law or agreed to in writing,
  35611. * software distributed under the License is distributed on an
  35612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35613. * KIND, either express or implied. See the License for the
  35614. * specific language governing permissions and limitations
  35615. * under the License.
  35616. */
  35617. /**
  35618. * AUTO-GENERATED FILE. DO NOT MODIFY.
  35619. */
  35620. /*
  35621. * Licensed to the Apache Software Foundation (ASF) under one
  35622. * or more contributor license agreements. See the NOTICE file
  35623. * distributed with this work for additional information
  35624. * regarding copyright ownership. The ASF licenses this file
  35625. * to you under the Apache License, Version 2.0 (the
  35626. * "License"); you may not use this file except in compliance
  35627. * with the License. You may obtain a copy of the License at
  35628. *
  35629. * http://www.apache.org/licenses/LICENSE-2.0
  35630. *
  35631. * Unless required by applicable law or agreed to in writing,
  35632. * software distributed under the License is distributed on an
  35633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35634. * KIND, either express or implied. See the License for the
  35635. * specific language governing permissions and limitations
  35636. * under the License.
  35637. */
  35638. function dataFilter(seriesType) {
  35639. return {
  35640. seriesType: seriesType,
  35641. reset: function (seriesModel, ecModel) {
  35642. var legendModels = ecModel.findComponents({
  35643. mainType: 'legend'
  35644. });
  35645. if (!legendModels || !legendModels.length) {
  35646. return;
  35647. }
  35648. var data = seriesModel.getData();
  35649. data.filterSelf(function (idx) {
  35650. var name = data.getName(idx); // If in any legend component the status is not selected.
  35651. for (var i = 0; i < legendModels.length; i++) {
  35652. // @ts-ignore FIXME: LegendModel
  35653. if (!legendModels[i].isSelected(name)) {
  35654. return false;
  35655. }
  35656. }
  35657. return true;
  35658. });
  35659. }
  35660. };
  35661. }
  35662. var RADIAN$1 = Math.PI / 180;
  35663. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  35664. if (list.length < 2) {
  35665. return;
  35666. }
  35667. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  35668. var rB = semi.rB;
  35669. var rB2 = rB * rB;
  35670. for (var i = 0; i < semi.list.length; i++) {
  35671. var item = semi.list[i];
  35672. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  35673. var rA = r + item.len;
  35674. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  35675. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  35676. item.label.x = cx + (dx + item.len2) * dir;
  35677. }
  35678. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  35679. function recalculateX(items) {
  35680. // Extremes of
  35681. var topSemi = {
  35682. list: [],
  35683. maxY: 0
  35684. };
  35685. var bottomSemi = {
  35686. list: [],
  35687. maxY: 0
  35688. };
  35689. for (var i = 0; i < items.length; i++) {
  35690. if (items[i].labelAlignTo !== 'none') {
  35691. continue;
  35692. }
  35693. var item = items[i];
  35694. var semi = item.label.y > cy ? bottomSemi : topSemi;
  35695. var dy = Math.abs(item.label.y - cy);
  35696. if (dy > semi.maxY) {
  35697. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  35698. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  35699. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  35700. semi.rB = rB;
  35701. semi.maxY = dy;
  35702. }
  35703. semi.list.push(item);
  35704. }
  35705. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  35706. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  35707. }
  35708. var len = list.length;
  35709. for (var i = 0; i < len; i++) {
  35710. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  35711. var dx = list[i].label.x - farthestX;
  35712. list[i].linePoints[1][0] += dx;
  35713. list[i].label.x = farthestX;
  35714. }
  35715. }
  35716. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  35717. recalculateX(list);
  35718. }
  35719. }
  35720. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  35721. var leftList = [];
  35722. var rightList = [];
  35723. var leftmostX = Number.MAX_VALUE;
  35724. var rightmostX = -Number.MAX_VALUE;
  35725. for (var i = 0; i < labelLayoutList.length; i++) {
  35726. var label = labelLayoutList[i].label;
  35727. if (isPositionCenter(labelLayoutList[i])) {
  35728. continue;
  35729. }
  35730. if (label.x < cx) {
  35731. leftmostX = Math.min(leftmostX, label.x);
  35732. leftList.push(labelLayoutList[i]);
  35733. } else {
  35734. rightmostX = Math.max(rightmostX, label.x);
  35735. rightList.push(labelLayoutList[i]);
  35736. }
  35737. }
  35738. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  35739. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  35740. for (var i = 0; i < labelLayoutList.length; i++) {
  35741. var layout = labelLayoutList[i];
  35742. var label = layout.label;
  35743. if (isPositionCenter(layout)) {
  35744. continue;
  35745. }
  35746. var linePoints = layout.linePoints;
  35747. if (linePoints) {
  35748. var isAlignToEdge = layout.labelAlignTo === 'edge';
  35749. var realTextWidth = layout.rect.width;
  35750. var targetTextWidth = void 0;
  35751. if (isAlignToEdge) {
  35752. if (label.x < cx) {
  35753. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  35754. } else {
  35755. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  35756. }
  35757. } else {
  35758. if (label.x < cx) {
  35759. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  35760. } else {
  35761. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  35762. }
  35763. }
  35764. if (targetTextWidth < layout.rect.width) {
  35765. // TODOTODO
  35766. // layout.text = textContain.truncateText(layout.text, targetTextWidth, layout.font);
  35767. layout.label.style.width = targetTextWidth;
  35768. if (layout.labelAlignTo === 'edge') {
  35769. realTextWidth = targetTextWidth; // realTextWidth = textContain.getWidth(layout.text, layout.font);
  35770. }
  35771. }
  35772. var dist = linePoints[1][0] - linePoints[2][0];
  35773. if (isAlignToEdge) {
  35774. if (label.x < cx) {
  35775. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  35776. } else {
  35777. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  35778. }
  35779. } else {
  35780. if (label.x < cx) {
  35781. linePoints[2][0] = label.x + layout.labelDistance;
  35782. } else {
  35783. linePoints[2][0] = label.x - layout.labelDistance;
  35784. }
  35785. linePoints[1][0] = linePoints[2][0] + dist;
  35786. }
  35787. linePoints[1][1] = linePoints[2][1] = label.y;
  35788. }
  35789. }
  35790. }
  35791. function isPositionCenter(sectorShape) {
  35792. // Not change x for center label
  35793. return sectorShape.position === 'center';
  35794. }
  35795. function pieLabelLayout(seriesModel) {
  35796. var data = seriesModel.getData();
  35797. var labelLayoutList = [];
  35798. var cx;
  35799. var cy;
  35800. var hasLabelRotate = false;
  35801. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  35802. var viewRect = data.getLayout('viewRect');
  35803. var r = data.getLayout('r');
  35804. var viewWidth = viewRect.width;
  35805. var viewLeft = viewRect.x;
  35806. var viewTop = viewRect.y;
  35807. var viewHeight = viewRect.height;
  35808. function setNotShow(el) {
  35809. el.ignore = true;
  35810. }
  35811. function isLabelShown(label) {
  35812. if (!label.ignore) {
  35813. return true;
  35814. }
  35815. for (var key in label.states) {
  35816. if (label.states[key].ignore === false) {
  35817. return true;
  35818. }
  35819. }
  35820. return false;
  35821. }
  35822. data.each(function (idx) {
  35823. var sector = data.getItemGraphicEl(idx);
  35824. var sectorShape = sector.shape;
  35825. var label = sector.getTextContent();
  35826. var labelLine = sector.getTextGuideLine();
  35827. var itemModel = data.getItemModel(idx);
  35828. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  35829. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  35830. var labelDistance = labelModel.get('distanceToLabelLine');
  35831. var labelAlignTo = labelModel.get('alignTo');
  35832. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  35833. var bleedMargin = labelModel.get('bleedMargin');
  35834. var labelLineModel = itemModel.getModel('labelLine');
  35835. var labelLineLen = labelLineModel.get('length');
  35836. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  35837. var labelLineLen2 = labelLineModel.get('length2');
  35838. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  35839. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  35840. each(label.states, setNotShow);
  35841. label.ignore = true;
  35842. return;
  35843. }
  35844. if (!isLabelShown(label)) {
  35845. return;
  35846. }
  35847. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  35848. var nx = Math.cos(midAngle);
  35849. var ny = Math.sin(midAngle);
  35850. var textX;
  35851. var textY;
  35852. var linePoints;
  35853. var textAlign;
  35854. cx = sectorShape.cx;
  35855. cy = sectorShape.cy;
  35856. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  35857. if (labelPosition === 'center') {
  35858. textX = sectorShape.cx;
  35859. textY = sectorShape.cy;
  35860. textAlign = 'center';
  35861. } else {
  35862. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  35863. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  35864. textX = x1 + nx * 3;
  35865. textY = y1 + ny * 3;
  35866. if (!isLabelInside) {
  35867. // For roseType
  35868. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  35869. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  35870. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  35871. var y3 = y2;
  35872. if (labelAlignTo === 'edge') {
  35873. // Adjust textX because text align of edge is opposite
  35874. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  35875. } else {
  35876. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  35877. }
  35878. textY = y3;
  35879. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  35880. }
  35881. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  35882. }
  35883. var labelRotate;
  35884. var rotate = labelModel.get('rotate');
  35885. if (typeof rotate === 'number') {
  35886. labelRotate = rotate * (Math.PI / 180);
  35887. } else {
  35888. labelRotate = rotate ? nx < 0 ? -midAngle + Math.PI : -midAngle : 0;
  35889. }
  35890. hasLabelRotate = !!labelRotate;
  35891. label.x = textX;
  35892. label.y = textY;
  35893. label.rotation = labelRotate;
  35894. label.setStyle({
  35895. verticalAlign: 'middle'
  35896. }); // Not sectorShape the inside label
  35897. if (!isLabelInside) {
  35898. var textRect = label.getBoundingRect().clone();
  35899. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  35900. var margin = (label.style.margin || 0) + 2.1;
  35901. textRect.y -= margin / 2;
  35902. textRect.height += margin;
  35903. labelLayoutList.push({
  35904. label: label,
  35905. labelLine: labelLine,
  35906. position: labelPosition,
  35907. len: labelLineLen,
  35908. len2: labelLineLen2,
  35909. minTurnAngle: labelLineModel.get('minTurnAngle'),
  35910. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  35911. surfaceNormal: new Point(nx, ny),
  35912. linePoints: linePoints,
  35913. textAlign: textAlign,
  35914. labelDistance: labelDistance,
  35915. labelAlignTo: labelAlignTo,
  35916. edgeDistance: edgeDistance,
  35917. bleedMargin: bleedMargin,
  35918. rect: textRect
  35919. });
  35920. } else {
  35921. label.setStyle({
  35922. align: textAlign
  35923. });
  35924. var selectState = label.states.select;
  35925. if (selectState) {
  35926. selectState.x += label.x;
  35927. selectState.y += label.y;
  35928. }
  35929. }
  35930. sector.setTextConfig({
  35931. inside: isLabelInside
  35932. });
  35933. });
  35934. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  35935. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  35936. }
  35937. for (var i = 0; i < labelLayoutList.length; i++) {
  35938. var layout = labelLayoutList[i];
  35939. var label = layout.label;
  35940. var labelLine = layout.labelLine;
  35941. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  35942. if (label) {
  35943. label.setStyle({
  35944. align: layout.textAlign
  35945. });
  35946. if (notShowLabel) {
  35947. each(label.states, setNotShow);
  35948. label.ignore = true;
  35949. }
  35950. var selectState = label.states.select;
  35951. if (selectState) {
  35952. selectState.x += label.x;
  35953. selectState.y += label.y;
  35954. }
  35955. }
  35956. if (labelLine) {
  35957. var linePoints = layout.linePoints;
  35958. if (notShowLabel || !linePoints) {
  35959. each(labelLine.states, setNotShow);
  35960. labelLine.ignore = true;
  35961. } else {
  35962. limitTurnAngle(linePoints, layout.minTurnAngle);
  35963. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  35964. labelLine.setShape({
  35965. points: linePoints
  35966. }); // Set the anchor to the midpoint of sector
  35967. label.__hostTarget.textGuideLineConfig = {
  35968. anchor: new Point(linePoints[0][0], linePoints[0][1])
  35969. };
  35970. }
  35971. }
  35972. }
  35973. }
  35974. function getSectorCornerRadius(model, shape) {
  35975. var cornerRadius = model.get('borderRadius');
  35976. if (cornerRadius == null) {
  35977. return null;
  35978. }
  35979. if (!isArray(cornerRadius)) {
  35980. cornerRadius = [cornerRadius, cornerRadius];
  35981. }
  35982. return {
  35983. innerCornerRadius: parsePercent(cornerRadius[0], shape.r0),
  35984. cornerRadius: parsePercent(cornerRadius[1], shape.r)
  35985. };
  35986. }
  35987. /**
  35988. * Piece of pie including Sector, Label, LabelLine
  35989. */
  35990. var PiePiece =
  35991. /** @class */
  35992. function (_super) {
  35993. __extends(PiePiece, _super);
  35994. function PiePiece(data, idx, startAngle) {
  35995. var _this = _super.call(this) || this;
  35996. _this.z2 = 2;
  35997. var polyline = new Polyline();
  35998. var text = new ZRText();
  35999. _this.setTextGuideLine(polyline);
  36000. _this.setTextContent(text);
  36001. _this.updateData(data, idx, startAngle, true);
  36002. return _this;
  36003. }
  36004. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  36005. var sector = this;
  36006. var seriesModel = data.hostModel;
  36007. var itemModel = data.getItemModel(idx);
  36008. var emphasisModel = itemModel.getModel('emphasis');
  36009. var layout = data.getItemLayout(idx);
  36010. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout) || {}, layout);
  36011. if (firstCreate) {
  36012. sector.setShape(sectorShape);
  36013. var animationType = seriesModel.getShallow('animationType');
  36014. if (animationType === 'scale') {
  36015. sector.shape.r = layout.r0;
  36016. initProps(sector, {
  36017. shape: {
  36018. r: layout.r
  36019. }
  36020. }, seriesModel, idx);
  36021. } // Expansion
  36022. else {
  36023. if (startAngle != null) {
  36024. sector.setShape({
  36025. startAngle: startAngle,
  36026. endAngle: startAngle
  36027. });
  36028. initProps(sector, {
  36029. shape: {
  36030. startAngle: layout.startAngle,
  36031. endAngle: layout.endAngle
  36032. }
  36033. }, seriesModel, idx);
  36034. } else {
  36035. sector.shape.endAngle = layout.startAngle;
  36036. updateProps(sector, {
  36037. shape: {
  36038. endAngle: layout.endAngle
  36039. }
  36040. }, seriesModel, idx);
  36041. }
  36042. }
  36043. } else {
  36044. // Transition animation from the old shape
  36045. updateProps(sector, {
  36046. shape: sectorShape
  36047. }, seriesModel, idx);
  36048. }
  36049. sector.useStyle(data.getItemVisual(idx, 'style'));
  36050. setStatesStylesFromModel(sector, itemModel);
  36051. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36052. var offset = seriesModel.get('selectedOffset');
  36053. var dx = Math.cos(midAngle) * offset;
  36054. var dy = Math.sin(midAngle) * offset;
  36055. var cursorStyle = itemModel.getShallow('cursor');
  36056. cursorStyle && sector.attr('cursor', cursorStyle);
  36057. this._updateLabel(seriesModel, data, idx);
  36058. sector.ensureState('emphasis').shape = __assign({
  36059. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  36060. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  36061. extend(sector.ensureState('select'), {
  36062. x: dx,
  36063. y: dy,
  36064. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  36065. });
  36066. extend(sector.ensureState('blur'), {
  36067. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  36068. });
  36069. var labelLine = sector.getTextGuideLine();
  36070. var labelText = sector.getTextContent();
  36071. labelLine && extend(labelLine.ensureState('select'), {
  36072. x: dx,
  36073. y: dy
  36074. }); // TODO: needs dx, dy in zrender?
  36075. extend(labelText.ensureState('select'), {
  36076. x: dx,
  36077. y: dy
  36078. });
  36079. enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  36080. };
  36081. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  36082. var _a;
  36083. var sector = this;
  36084. var itemModel = data.getItemModel(idx);
  36085. var labelLineModel = itemModel.getModel('labelLine');
  36086. var style = data.getItemVisual(idx, 'style');
  36087. var visualColor = style && style.fill;
  36088. var visualOpacity = style && style.opacity;
  36089. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  36090. labelFetcher: data.hostModel,
  36091. labelDataIndex: idx,
  36092. inheritColor: visualColor,
  36093. defaultOpacity: visualOpacity,
  36094. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  36095. });
  36096. var labelText = sector.getTextContent(); // Set textConfig on sector.
  36097. sector.setTextConfig({
  36098. // reset position, rotation
  36099. position: null,
  36100. rotation: null
  36101. }); // Make sure update style on labelText after setLabelStyle.
  36102. // Because setLabelStyle will replace a new style on it.
  36103. labelText.attr({
  36104. z2: 10
  36105. });
  36106. var labelPosition = seriesModel.get(['label', 'position']);
  36107. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  36108. (_a = sector.getTextGuideLine()) === null || _a === void 0 ? void 0 : _a.hide();
  36109. return;
  36110. } // Default use item visual color
  36111. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  36112. stroke: visualColor,
  36113. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  36114. });
  36115. };
  36116. return PiePiece;
  36117. }(Sector); // Pie view
  36118. var PieView =
  36119. /** @class */
  36120. function (_super) {
  36121. __extends(PieView, _super);
  36122. function PieView() {
  36123. var _this = _super !== null && _super.apply(this, arguments) || this;
  36124. _this.ignoreLabelLineUpdate = true;
  36125. return _this;
  36126. }
  36127. PieView.prototype.init = function () {
  36128. var sectorGroup = new Group();
  36129. this._sectorGroup = sectorGroup;
  36130. };
  36131. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  36132. var data = seriesModel.getData();
  36133. var oldData = this._data;
  36134. var group = this.group;
  36135. var startAngle; // First render
  36136. if (!oldData && data.count() > 0) {
  36137. var shape = data.getItemLayout(0);
  36138. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  36139. shape = data.getItemLayout(s);
  36140. }
  36141. if (shape) {
  36142. startAngle = shape.startAngle;
  36143. }
  36144. }
  36145. data.diff(oldData).add(function (idx) {
  36146. var piePiece = new PiePiece(data, idx, startAngle);
  36147. data.setItemGraphicEl(idx, piePiece);
  36148. group.add(piePiece);
  36149. }).update(function (newIdx, oldIdx) {
  36150. var piePiece = oldData.getItemGraphicEl(oldIdx);
  36151. piePiece.updateData(data, newIdx, startAngle);
  36152. piePiece.off('click');
  36153. group.add(piePiece);
  36154. data.setItemGraphicEl(newIdx, piePiece);
  36155. }).remove(function (idx) {
  36156. var piePiece = oldData.getItemGraphicEl(idx);
  36157. removeElementWithFadeOut(piePiece, seriesModel, idx);
  36158. }).execute();
  36159. pieLabelLayout(seriesModel); // Always use initial animation.
  36160. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  36161. this._data = data;
  36162. }
  36163. };
  36164. PieView.prototype.dispose = function () {};
  36165. PieView.prototype.containPoint = function (point, seriesModel) {
  36166. var data = seriesModel.getData();
  36167. var itemLayout = data.getItemLayout(0);
  36168. if (itemLayout) {
  36169. var dx = point[0] - itemLayout.cx;
  36170. var dy = point[1] - itemLayout.cy;
  36171. var radius = Math.sqrt(dx * dx + dy * dy);
  36172. return radius <= itemLayout.r && radius >= itemLayout.r0;
  36173. }
  36174. };
  36175. PieView.type = 'pie';
  36176. return PieView;
  36177. }(ChartView);
  36178. /**
  36179. * [Usage]:
  36180. * (1)
  36181. * createListSimply(seriesModel, ['value']);
  36182. * (2)
  36183. * createListSimply(seriesModel, {
  36184. * coordDimensions: ['value'],
  36185. * dimensionsCount: 5
  36186. * });
  36187. */
  36188. function createListSimply(seriesModel, opt, nameList) {
  36189. opt = isArray(opt) && {
  36190. coordDimensions: opt
  36191. } || extend({}, opt);
  36192. var source = seriesModel.getSource();
  36193. var dimensionsInfo = createDimensions(source, opt);
  36194. var list = new List(dimensionsInfo, seriesModel);
  36195. list.initData(source, nameList);
  36196. return list;
  36197. }
  36198. /*
  36199. * Licensed to the Apache Software Foundation (ASF) under one
  36200. * or more contributor license agreements. See the NOTICE file
  36201. * distributed with this work for additional information
  36202. * regarding copyright ownership. The ASF licenses this file
  36203. * to you under the Apache License, Version 2.0 (the
  36204. * "License"); you may not use this file except in compliance
  36205. * with the License. You may obtain a copy of the License at
  36206. *
  36207. * http://www.apache.org/licenses/LICENSE-2.0
  36208. *
  36209. * Unless required by applicable law or agreed to in writing,
  36210. * software distributed under the License is distributed on an
  36211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36212. * KIND, either express or implied. See the License for the
  36213. * specific language governing permissions and limitations
  36214. * under the License.
  36215. */
  36216. /**
  36217. * AUTO-GENERATED FILE. DO NOT MODIFY.
  36218. */
  36219. /*
  36220. * Licensed to the Apache Software Foundation (ASF) under one
  36221. * or more contributor license agreements. See the NOTICE file
  36222. * distributed with this work for additional information
  36223. * regarding copyright ownership. The ASF licenses this file
  36224. * to you under the Apache License, Version 2.0 (the
  36225. * "License"); you may not use this file except in compliance
  36226. * with the License. You may obtain a copy of the License at
  36227. *
  36228. * http://www.apache.org/licenses/LICENSE-2.0
  36229. *
  36230. * Unless required by applicable law or agreed to in writing,
  36231. * software distributed under the License is distributed on an
  36232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36233. * KIND, either express or implied. See the License for the
  36234. * specific language governing permissions and limitations
  36235. * under the License.
  36236. */
  36237. /**
  36238. * LegendVisualProvider is an bridge that pick encoded color from data and
  36239. * provide to the legend component.
  36240. */
  36241. var LegendVisualProvider =
  36242. /** @class */
  36243. function () {
  36244. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  36245. getDataWithEncodedVisual, // Function to get raw data before filtered.
  36246. getRawData) {
  36247. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  36248. this._getRawData = getRawData;
  36249. }
  36250. LegendVisualProvider.prototype.getAllNames = function () {
  36251. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  36252. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  36253. return rawData.mapArray(rawData.getName);
  36254. };
  36255. LegendVisualProvider.prototype.containName = function (name) {
  36256. var rawData = this._getRawData();
  36257. return rawData.indexOfName(name) >= 0;
  36258. };
  36259. LegendVisualProvider.prototype.indexOfName = function (name) {
  36260. // Only get data when necessary.
  36261. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  36262. // Invoking Series#getData immediately will throw an error.
  36263. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  36264. return dataWithEncodedVisual.indexOfName(name);
  36265. };
  36266. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  36267. // Get encoded visual properties from final filtered data.
  36268. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  36269. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  36270. };
  36271. return LegendVisualProvider;
  36272. }();
  36273. var PieSeriesModel =
  36274. /** @class */
  36275. function (_super) {
  36276. __extends(PieSeriesModel, _super);
  36277. function PieSeriesModel() {
  36278. var _this = _super !== null && _super.apply(this, arguments) || this;
  36279. _this.useColorPaletteOnData = true;
  36280. return _this;
  36281. }
  36282. /**
  36283. * @overwrite
  36284. */
  36285. PieSeriesModel.prototype.init = function (option) {
  36286. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  36287. // Use a function instead of direct access because data reference may changed
  36288. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  36289. this._defaultLabelLine(option);
  36290. };
  36291. /**
  36292. * @overwrite
  36293. */
  36294. PieSeriesModel.prototype.mergeOption = function () {
  36295. _super.prototype.mergeOption.apply(this, arguments);
  36296. };
  36297. /**
  36298. * @overwrite
  36299. */
  36300. PieSeriesModel.prototype.getInitialData = function () {
  36301. return createListSimply(this, {
  36302. coordDimensions: ['value'],
  36303. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  36304. });
  36305. };
  36306. /**
  36307. * @overwrite
  36308. */
  36309. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  36310. var data = this.getData();
  36311. var params = _super.prototype.getDataParams.call(this, dataIndex); // FIXME toFixed?
  36312. var valueList = [];
  36313. data.each(data.mapDimension('value'), function (value) {
  36314. valueList.push(value);
  36315. });
  36316. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  36317. params.$vars.push('percent');
  36318. return params;
  36319. };
  36320. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  36321. // Extend labelLine emphasis
  36322. defaultEmphasis(option, 'labelLine', ['show']);
  36323. var labelLineNormalOpt = option.labelLine;
  36324. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  36325. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  36326. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  36327. };
  36328. PieSeriesModel.type = 'series.pie';
  36329. PieSeriesModel.defaultOption = {
  36330. zlevel: 0,
  36331. z: 2,
  36332. legendHoverLink: true,
  36333. // 默认全局居中
  36334. center: ['50%', '50%'],
  36335. radius: [0, '75%'],
  36336. // 默认顺时针
  36337. clockwise: true,
  36338. startAngle: 90,
  36339. // 最小角度改为0
  36340. minAngle: 0,
  36341. // If the angle of a sector less than `minShowLabelAngle`,
  36342. // the label will not be displayed.
  36343. minShowLabelAngle: 0,
  36344. // 选中时扇区偏移量
  36345. selectedOffset: 10,
  36346. // 选择模式,默认关闭,可选single,multiple
  36347. // selectedMode: false,
  36348. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  36349. // roseType: null,
  36350. percentPrecision: 2,
  36351. // If still show when all data zero.
  36352. stillShowZeroSum: true,
  36353. // cursor: null,
  36354. left: 0,
  36355. top: 0,
  36356. right: 0,
  36357. bottom: 0,
  36358. width: null,
  36359. height: null,
  36360. label: {
  36361. // color: 'inherit',
  36362. // If rotate around circle
  36363. rotate: 0,
  36364. show: true,
  36365. overflow: 'truncate',
  36366. // 'outer', 'inside', 'center'
  36367. position: 'outer',
  36368. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  36369. alignTo: 'none',
  36370. // Closest distance between label and chart edge.
  36371. // Works only position is 'outer' and alignTo is 'edge'.
  36372. edgeDistance: '25%',
  36373. // Works only position is 'outer' and alignTo is not 'edge'.
  36374. bleedMargin: 10,
  36375. // Distance between text and label line.
  36376. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  36377. // 默认使用全局文本样式,详见TEXTSTYLE
  36378. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  36379. },
  36380. // Enabled when label.normal.position is 'outer'
  36381. labelLine: {
  36382. show: true,
  36383. // 引导线两段中的第一段长度
  36384. length: 15,
  36385. // 引导线两段中的第二段长度
  36386. length2: 15,
  36387. smooth: false,
  36388. minTurnAngle: 90,
  36389. maxSurfaceAngle: 90,
  36390. lineStyle: {
  36391. // color: 各异,
  36392. width: 1,
  36393. type: 'solid'
  36394. }
  36395. },
  36396. itemStyle: {
  36397. borderWidth: 1
  36398. },
  36399. labelLayout: {
  36400. // Hide the overlapped label.
  36401. hideOverlap: true
  36402. },
  36403. emphasis: {
  36404. scale: true,
  36405. scaleSize: 5
  36406. },
  36407. // If use strategy to avoid label overlapping
  36408. avoidLabelOverlap: true,
  36409. // Animation type. Valid values: expansion, scale
  36410. animationType: 'expansion',
  36411. animationDuration: 1000,
  36412. // Animation type when update. Valid values: transition, expansion
  36413. animationTypeUpdate: 'transition',
  36414. animationEasingUpdate: 'cubicInOut',
  36415. animationDurationUpdate: 500,
  36416. animationEasing: 'cubicInOut'
  36417. };
  36418. return PieSeriesModel;
  36419. }(SeriesModel);
  36420. function install$3(registers) {
  36421. registers.registerChartView(PieView);
  36422. registers.registerSeriesModel(PieSeriesModel);
  36423. createLegacyDataSelectAction('pie', registers.registerAction);
  36424. registers.registerLayout(curry(pieLayout, 'pie'));
  36425. registers.registerProcessor(dataFilter('pie'));
  36426. }
  36427. var GridModel =
  36428. /** @class */
  36429. function (_super) {
  36430. __extends(GridModel, _super);
  36431. function GridModel() {
  36432. return _super !== null && _super.apply(this, arguments) || this;
  36433. }
  36434. GridModel.type = 'grid';
  36435. GridModel.dependencies = ['xAxis', 'yAxis'];
  36436. GridModel.layoutMode = 'box';
  36437. GridModel.defaultOption = {
  36438. show: false,
  36439. zlevel: 0,
  36440. z: 0,
  36441. left: '10%',
  36442. top: 60,
  36443. right: '10%',
  36444. bottom: 70,
  36445. // If grid size contain label
  36446. containLabel: false,
  36447. // width: {totalWidth} - left - right,
  36448. // height: {totalHeight} - top - bottom,
  36449. backgroundColor: 'rgba(0,0,0,0)',
  36450. borderWidth: 1,
  36451. borderColor: '#ccc'
  36452. };
  36453. return GridModel;
  36454. }(ComponentModel);
  36455. var CartesianAxisModel =
  36456. /** @class */
  36457. function (_super) {
  36458. __extends(CartesianAxisModel, _super);
  36459. function CartesianAxisModel() {
  36460. return _super !== null && _super.apply(this, arguments) || this;
  36461. }
  36462. CartesianAxisModel.prototype.getCoordSysModel = function () {
  36463. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  36464. };
  36465. CartesianAxisModel.type = 'cartesian2dAxis';
  36466. return CartesianAxisModel;
  36467. }(ComponentModel);
  36468. mixin(CartesianAxisModel, AxisModelCommonMixin);
  36469. var defaultOption = {
  36470. show: true,
  36471. zlevel: 0,
  36472. z: 0,
  36473. // Inverse the axis.
  36474. inverse: false,
  36475. // Axis name displayed.
  36476. name: '',
  36477. // 'start' | 'middle' | 'end'
  36478. nameLocation: 'end',
  36479. // By degree. By default auto rotate by nameLocation.
  36480. nameRotate: null,
  36481. nameTruncate: {
  36482. maxWidth: null,
  36483. ellipsis: '...',
  36484. placeholder: '.'
  36485. },
  36486. // Use global text style by default.
  36487. nameTextStyle: {},
  36488. // The gap between axisName and axisLine.
  36489. nameGap: 15,
  36490. // Default `false` to support tooltip.
  36491. silent: false,
  36492. // Default `false` to avoid legacy user event listener fail.
  36493. triggerEvent: false,
  36494. tooltip: {
  36495. show: false
  36496. },
  36497. axisPointer: {},
  36498. axisLine: {
  36499. show: true,
  36500. onZero: true,
  36501. onZeroAxisIndex: null,
  36502. lineStyle: {
  36503. color: '#6E7079',
  36504. width: 1,
  36505. type: 'solid'
  36506. },
  36507. // The arrow at both ends the the axis.
  36508. symbol: ['none', 'none'],
  36509. symbolSize: [10, 15]
  36510. },
  36511. axisTick: {
  36512. show: true,
  36513. // Whether axisTick is inside the grid or outside the grid.
  36514. inside: false,
  36515. // The length of axisTick.
  36516. length: 5,
  36517. lineStyle: {
  36518. width: 1
  36519. }
  36520. },
  36521. axisLabel: {
  36522. show: true,
  36523. // Whether axisLabel is inside the grid or outside the grid.
  36524. inside: false,
  36525. rotate: 0,
  36526. // true | false | null/undefined (auto)
  36527. showMinLabel: null,
  36528. // true | false | null/undefined (auto)
  36529. showMaxLabel: null,
  36530. margin: 8,
  36531. // formatter: null,
  36532. fontSize: 12
  36533. },
  36534. splitLine: {
  36535. show: true,
  36536. lineStyle: {
  36537. color: ['#E0E6F1'],
  36538. width: 1,
  36539. type: 'solid'
  36540. }
  36541. },
  36542. splitArea: {
  36543. show: false,
  36544. areaStyle: {
  36545. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  36546. }
  36547. }
  36548. };
  36549. var categoryAxis = merge({
  36550. // The gap at both ends of the axis. For categoryAxis, boolean.
  36551. boundaryGap: true,
  36552. // Set false to faster category collection.
  36553. deduplication: null,
  36554. // splitArea: {
  36555. // show: false
  36556. // },
  36557. splitLine: {
  36558. show: false
  36559. },
  36560. axisTick: {
  36561. // If tick is align with label when boundaryGap is true
  36562. alignWithLabel: false,
  36563. interval: 'auto'
  36564. },
  36565. axisLabel: {
  36566. interval: 'auto'
  36567. }
  36568. }, defaultOption);
  36569. var valueAxis = merge({
  36570. boundaryGap: [0, 0],
  36571. axisLine: {
  36572. // Not shown when other axis is categoryAxis in cartesian
  36573. show: 'auto'
  36574. },
  36575. axisTick: {
  36576. // Not shown when other axis is categoryAxis in cartesian
  36577. show: 'auto'
  36578. },
  36579. // TODO
  36580. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  36581. splitNumber: 5,
  36582. minorTick: {
  36583. // Minor tick, not available for cateogry axis.
  36584. show: false,
  36585. // Split number of minor ticks. The value should be in range of (0, 100)
  36586. splitNumber: 5,
  36587. // Lenght of minor tick
  36588. length: 3,
  36589. // Line style
  36590. lineStyle: {// Default to be same with axisTick
  36591. }
  36592. },
  36593. minorSplitLine: {
  36594. show: false,
  36595. lineStyle: {
  36596. color: '#F4F7FD',
  36597. width: 1
  36598. }
  36599. }
  36600. }, defaultOption);
  36601. var timeAxis = merge({
  36602. scale: true,
  36603. splitNumber: 6,
  36604. axisLabel: {
  36605. // To eliminate labels that are not nice
  36606. showMinLabel: false,
  36607. showMaxLabel: false,
  36608. rich: {
  36609. primary: {
  36610. fontWeight: 'bold'
  36611. }
  36612. }
  36613. },
  36614. splitLine: {
  36615. show: false
  36616. }
  36617. }, valueAxis);
  36618. var logAxis = defaults({
  36619. scale: true,
  36620. logBase: 10
  36621. }, valueAxis);
  36622. var axisDefault = {
  36623. category: categoryAxis,
  36624. value: valueAxis,
  36625. time: timeAxis,
  36626. log: logAxis
  36627. };
  36628. /*
  36629. * Licensed to the Apache Software Foundation (ASF) under one
  36630. * or more contributor license agreements. See the NOTICE file
  36631. * distributed with this work for additional information
  36632. * regarding copyright ownership. The ASF licenses this file
  36633. * to you under the Apache License, Version 2.0 (the
  36634. * "License"); you may not use this file except in compliance
  36635. * with the License. You may obtain a copy of the License at
  36636. *
  36637. * http://www.apache.org/licenses/LICENSE-2.0
  36638. *
  36639. * Unless required by applicable law or agreed to in writing,
  36640. * software distributed under the License is distributed on an
  36641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36642. * KIND, either express or implied. See the License for the
  36643. * specific language governing permissions and limitations
  36644. * under the License.
  36645. */
  36646. /**
  36647. * AUTO-GENERATED FILE. DO NOT MODIFY.
  36648. */
  36649. /*
  36650. * Licensed to the Apache Software Foundation (ASF) under one
  36651. * or more contributor license agreements. See the NOTICE file
  36652. * distributed with this work for additional information
  36653. * regarding copyright ownership. The ASF licenses this file
  36654. * to you under the Apache License, Version 2.0 (the
  36655. * "License"); you may not use this file except in compliance
  36656. * with the License. You may obtain a copy of the License at
  36657. *
  36658. * http://www.apache.org/licenses/LICENSE-2.0
  36659. *
  36660. * Unless required by applicable law or agreed to in writing,
  36661. * software distributed under the License is distributed on an
  36662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36663. * KIND, either express or implied. See the License for the
  36664. * specific language governing permissions and limitations
  36665. * under the License.
  36666. */
  36667. var AXIS_TYPES = {
  36668. value: 1,
  36669. category: 1,
  36670. time: 1,
  36671. log: 1
  36672. };
  36673. /**
  36674. * Generate sub axis model class
  36675. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  36676. */
  36677. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  36678. each(AXIS_TYPES, function (v, axisType) {
  36679. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  36680. var AxisModel =
  36681. /** @class */
  36682. function (_super) {
  36683. __extends(AxisModel, _super);
  36684. function AxisModel() {
  36685. var args = [];
  36686. for (var _i = 0; _i < arguments.length; _i++) {
  36687. args[_i] = arguments[_i];
  36688. }
  36689. var _this = _super.apply(this, args) || this;
  36690. _this.type = axisName + 'Axis.' + axisType;
  36691. return _this;
  36692. }
  36693. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  36694. var layoutMode = fetchLayoutMode(this);
  36695. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  36696. var themeModel = ecModel.getTheme();
  36697. merge(option, themeModel.get(axisType + 'Axis'));
  36698. merge(option, this.getDefaultOption());
  36699. option.type = getAxisType(option);
  36700. if (layoutMode) {
  36701. mergeLayoutParam(option, inputPositionParams, layoutMode);
  36702. }
  36703. };
  36704. AxisModel.prototype.optionUpdated = function () {
  36705. var thisOption = this.option;
  36706. if (thisOption.type === 'category') {
  36707. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  36708. }
  36709. };
  36710. /**
  36711. * Should not be called before all of 'getInitailData' finished.
  36712. * Because categories are collected during initializing data.
  36713. */
  36714. AxisModel.prototype.getCategories = function (rawData) {
  36715. var option = this.option; // FIXME
  36716. // warning if called before all of 'getInitailData' finished.
  36717. if (option.type === 'category') {
  36718. if (rawData) {
  36719. return option.data;
  36720. }
  36721. return this.__ordinalMeta.categories;
  36722. }
  36723. };
  36724. AxisModel.prototype.getOrdinalMeta = function () {
  36725. return this.__ordinalMeta;
  36726. };
  36727. AxisModel.type = axisName + 'Axis.' + axisType;
  36728. AxisModel.defaultOption = defaultOption;
  36729. return AxisModel;
  36730. }(BaseAxisModelClass);
  36731. registers.registerComponentModel(AxisModel);
  36732. });
  36733. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  36734. }
  36735. function getAxisType(option) {
  36736. // Default axis with data is category axis
  36737. return option.type || (option.data ? 'category' : 'value');
  36738. }
  36739. var Cartesian =
  36740. /** @class */
  36741. function () {
  36742. function Cartesian(name) {
  36743. this.type = 'cartesian';
  36744. this._dimList = [];
  36745. this._axes = {};
  36746. this.name = name || '';
  36747. }
  36748. Cartesian.prototype.getAxis = function (dim) {
  36749. return this._axes[dim];
  36750. };
  36751. Cartesian.prototype.getAxes = function () {
  36752. return map(this._dimList, function (dim) {
  36753. return this._axes[dim];
  36754. }, this);
  36755. };
  36756. Cartesian.prototype.getAxesByScale = function (scaleType) {
  36757. scaleType = scaleType.toLowerCase();
  36758. return filter(this.getAxes(), function (axis) {
  36759. return axis.scale.type === scaleType;
  36760. });
  36761. };
  36762. Cartesian.prototype.addAxis = function (axis) {
  36763. var dim = axis.dim;
  36764. this._axes[dim] = axis;
  36765. this._dimList.push(dim);
  36766. };
  36767. return Cartesian;
  36768. }();
  36769. var cartesian2DDimensions = ['x', 'y'];
  36770. function canCalculateAffineTransform(scale) {
  36771. return scale.type === 'interval' || scale.type === 'time';
  36772. }
  36773. var Cartesian2D =
  36774. /** @class */
  36775. function (_super) {
  36776. __extends(Cartesian2D, _super);
  36777. function Cartesian2D() {
  36778. var _this = _super !== null && _super.apply(this, arguments) || this;
  36779. _this.type = 'cartesian2d';
  36780. _this.dimensions = cartesian2DDimensions;
  36781. return _this;
  36782. }
  36783. /**
  36784. * Calculate an affine transform matrix if two axes are time or value.
  36785. * It's mainly for accelartion on the large time series data.
  36786. */
  36787. Cartesian2D.prototype.calcAffineTransform = function () {
  36788. this._transform = this._invTransform = null;
  36789. var xAxisScale = this.getAxis('x').scale;
  36790. var yAxisScale = this.getAxis('y').scale;
  36791. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  36792. return;
  36793. }
  36794. var xScaleExtent = xAxisScale.getExtent();
  36795. var yScaleExtent = yAxisScale.getExtent();
  36796. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  36797. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  36798. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  36799. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  36800. if (!xScaleSpan || !yScaleSpan) {
  36801. return;
  36802. } // Accelerate data to point calculation on the special large time series data.
  36803. var scaleX = (end[0] - start[0]) / xScaleSpan;
  36804. var scaleY = (end[1] - start[1]) / yScaleSpan;
  36805. var translateX = start[0] - xScaleExtent[0] * scaleX;
  36806. var translateY = start[1] - yScaleExtent[0] * scaleY;
  36807. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  36808. this._invTransform = invert([], m);
  36809. };
  36810. /**
  36811. * Base axis will be used on stacking.
  36812. */
  36813. Cartesian2D.prototype.getBaseAxis = function () {
  36814. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  36815. };
  36816. Cartesian2D.prototype.containPoint = function (point) {
  36817. var axisX = this.getAxis('x');
  36818. var axisY = this.getAxis('y');
  36819. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  36820. };
  36821. Cartesian2D.prototype.containData = function (data) {
  36822. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  36823. };
  36824. Cartesian2D.prototype.dataToPoint = function (data, reserved, out) {
  36825. out = out || [];
  36826. var xVal = data[0];
  36827. var yVal = data[1]; // Fast path
  36828. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  36829. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  36830. return applyTransform(out, data, this._transform);
  36831. }
  36832. var xAxis = this.getAxis('x');
  36833. var yAxis = this.getAxis('y');
  36834. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));
  36835. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));
  36836. return out;
  36837. };
  36838. Cartesian2D.prototype.clampData = function (data, out) {
  36839. var xScale = this.getAxis('x').scale;
  36840. var yScale = this.getAxis('y').scale;
  36841. var xAxisExtent = xScale.getExtent();
  36842. var yAxisExtent = yScale.getExtent();
  36843. var x = xScale.parse(data[0]);
  36844. var y = yScale.parse(data[1]);
  36845. out = out || [];
  36846. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  36847. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  36848. return out;
  36849. };
  36850. Cartesian2D.prototype.pointToData = function (point, out) {
  36851. out = out || [];
  36852. if (this._invTransform) {
  36853. return applyTransform(out, point, this._invTransform);
  36854. }
  36855. var xAxis = this.getAxis('x');
  36856. var yAxis = this.getAxis('y');
  36857. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  36858. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  36859. return out;
  36860. };
  36861. Cartesian2D.prototype.getOtherAxis = function (axis) {
  36862. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  36863. };
  36864. /**
  36865. * Get rect area of cartesian.
  36866. * Area will have a contain function to determine if a point is in the coordinate system.
  36867. */
  36868. Cartesian2D.prototype.getArea = function () {
  36869. var xExtent = this.getAxis('x').getGlobalExtent();
  36870. var yExtent = this.getAxis('y').getGlobalExtent();
  36871. var x = Math.min(xExtent[0], xExtent[1]);
  36872. var y = Math.min(yExtent[0], yExtent[1]);
  36873. var width = Math.max(xExtent[0], xExtent[1]) - x;
  36874. var height = Math.max(yExtent[0], yExtent[1]) - y;
  36875. return new BoundingRect(x, y, width, height);
  36876. };
  36877. return Cartesian2D;
  36878. }(Cartesian);
  36879. var Axis2D =
  36880. /** @class */
  36881. function (_super) {
  36882. __extends(Axis2D, _super);
  36883. function Axis2D(dim, scale, coordExtent, axisType, position) {
  36884. var _this = _super.call(this, dim, scale, coordExtent) || this;
  36885. /**
  36886. * Index of axis, can be used as key
  36887. * Injected outside.
  36888. */
  36889. _this.index = 0;
  36890. _this.type = axisType || 'value';
  36891. _this.position = position || 'bottom';
  36892. return _this;
  36893. }
  36894. Axis2D.prototype.isHorizontal = function () {
  36895. var position = this.position;
  36896. return position === 'top' || position === 'bottom';
  36897. };
  36898. /**
  36899. * Each item cooresponds to this.getExtent(), which
  36900. * means globalExtent[0] may greater than globalExtent[1],
  36901. * unless `asc` is input.
  36902. *
  36903. * @param {boolean} [asc]
  36904. * @return {Array.<number>}
  36905. */
  36906. Axis2D.prototype.getGlobalExtent = function (asc) {
  36907. var ret = this.getExtent();
  36908. ret[0] = this.toGlobalCoord(ret[0]);
  36909. ret[1] = this.toGlobalCoord(ret[1]);
  36910. asc && ret[0] > ret[1] && ret.reverse();
  36911. return ret;
  36912. };
  36913. Axis2D.prototype.pointToData = function (point, clamp) {
  36914. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  36915. };
  36916. /**
  36917. * Set ordinalSortInfo
  36918. * @param info new OrdinalSortInfo
  36919. */
  36920. Axis2D.prototype.setCategorySortInfo = function (info) {
  36921. if (this.type !== 'category') {
  36922. return false;
  36923. }
  36924. this.model.option.categorySortInfo = info;
  36925. this.scale.setSortInfo(info);
  36926. };
  36927. return Axis2D;
  36928. }(Axis);
  36929. /**
  36930. * Can only be called after coordinate system creation stage.
  36931. * (Can be called before coordinate system update stage).
  36932. */
  36933. function layout$1(gridModel, axisModel, opt) {
  36934. opt = opt || {};
  36935. var grid = gridModel.coordinateSystem;
  36936. var axis = axisModel.axis;
  36937. var layout = {};
  36938. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  36939. var rawAxisPosition = axis.position;
  36940. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  36941. var axisDim = axis.dim;
  36942. var rect = grid.getRect();
  36943. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  36944. var idx = {
  36945. left: 0,
  36946. right: 1,
  36947. top: 0,
  36948. bottom: 1,
  36949. onZero: 2
  36950. };
  36951. var axisOffset = axisModel.get('offset') || 0;
  36952. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  36953. if (otherAxisOnZeroOf) {
  36954. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  36955. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  36956. } // Axis position
  36957. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  36958. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  36959. var dirMap = {
  36960. top: -1,
  36961. bottom: 1,
  36962. left: -1,
  36963. right: 1
  36964. };
  36965. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  36966. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  36967. if (axisModel.get(['axisTick', 'inside'])) {
  36968. layout.tickDirection = -layout.tickDirection;
  36969. }
  36970. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  36971. layout.labelDirection = -layout.labelDirection;
  36972. } // Special label rotation
  36973. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  36974. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  36975. layout.z2 = 1;
  36976. return layout;
  36977. }
  36978. function isCartesian2DSeries(seriesModel) {
  36979. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  36980. }
  36981. function findAxisModels(seriesModel) {
  36982. var axisModelMap = {
  36983. xAxisModel: null,
  36984. yAxisModel: null
  36985. };
  36986. each(axisModelMap, function (v, key) {
  36987. var axisType = key.replace(/Model$/, '');
  36988. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  36989. if ("development" !== 'production') {
  36990. if (!axisModel) {
  36991. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  36992. }
  36993. }
  36994. axisModelMap[key] = axisModel;
  36995. });
  36996. return axisModelMap;
  36997. }
  36998. var Grid =
  36999. /** @class */
  37000. function () {
  37001. function Grid(gridModel, ecModel, api) {
  37002. // FIXME:TS where used (different from registered type 'cartesian2d')?
  37003. this.type = 'grid';
  37004. this._coordsMap = {};
  37005. this._coordsList = [];
  37006. this._axesMap = {};
  37007. this._axesList = [];
  37008. this.axisPointerEnabled = true;
  37009. this.dimensions = cartesian2DDimensions;
  37010. this._initCartesian(gridModel, ecModel, api);
  37011. this.model = gridModel;
  37012. }
  37013. Grid.prototype.getRect = function () {
  37014. return this._rect;
  37015. };
  37016. Grid.prototype.update = function (ecModel, api) {
  37017. var axesMap = this._axesMap;
  37018. this._updateScale(ecModel, this.model);
  37019. each(axesMap.x, function (xAxis) {
  37020. niceScaleExtent(xAxis.scale, xAxis.model);
  37021. });
  37022. each(axesMap.y, function (yAxis) {
  37023. niceScaleExtent(yAxis.scale, yAxis.model);
  37024. }); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  37025. var onZeroRecords = {};
  37026. each(axesMap.x, function (xAxis) {
  37027. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  37028. });
  37029. each(axesMap.y, function (yAxis) {
  37030. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  37031. }); // Resize again if containLabel is enabled
  37032. // FIXME It may cause getting wrong grid size in data processing stage
  37033. this.resize(this.model, api);
  37034. };
  37035. /**
  37036. * Resize the grid
  37037. */
  37038. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  37039. var boxLayoutParams = gridModel.getBoxLayoutParams();
  37040. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  37041. var gridRect = getLayoutRect(boxLayoutParams, {
  37042. width: api.getWidth(),
  37043. height: api.getHeight()
  37044. });
  37045. this._rect = gridRect;
  37046. var axesList = this._axesList;
  37047. adjustAxes(); // Minus label size
  37048. if (isContainLabel) {
  37049. each(axesList, function (axis) {
  37050. if (!axis.model.get(['axisLabel', 'inside'])) {
  37051. var labelUnionRect = estimateLabelUnionRect(axis);
  37052. if (labelUnionRect) {
  37053. var dim = axis.isHorizontal() ? 'height' : 'width';
  37054. var margin = axis.model.get(['axisLabel', 'margin']);
  37055. gridRect[dim] -= labelUnionRect[dim] + margin;
  37056. if (axis.position === 'top') {
  37057. gridRect.y += labelUnionRect.height + margin;
  37058. } else if (axis.position === 'left') {
  37059. gridRect.x += labelUnionRect.width + margin;
  37060. }
  37061. }
  37062. }
  37063. });
  37064. adjustAxes();
  37065. }
  37066. each(this._coordsList, function (coord) {
  37067. // Calculate affine matrix to accelerate the data to point transform.
  37068. // If all the axes scales are time or value.
  37069. coord.calcAffineTransform();
  37070. });
  37071. function adjustAxes() {
  37072. each(axesList, function (axis) {
  37073. var isHorizontal = axis.isHorizontal();
  37074. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  37075. var idx = axis.inverse ? 1 : 0;
  37076. axis.setExtent(extent[idx], extent[1 - idx]);
  37077. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  37078. });
  37079. }
  37080. };
  37081. Grid.prototype.getAxis = function (dim, axisIndex) {
  37082. var axesMapOnDim = this._axesMap[dim];
  37083. if (axesMapOnDim != null) {
  37084. return axesMapOnDim[axisIndex || 0]; // if (axisIndex == null) {
  37085. // Find first axis
  37086. // for (let name in axesMapOnDim) {
  37087. // if (axesMapOnDim.hasOwnProperty(name)) {
  37088. // return axesMapOnDim[name];
  37089. // }
  37090. // }
  37091. // }
  37092. // return axesMapOnDim[axisIndex];
  37093. }
  37094. };
  37095. Grid.prototype.getAxes = function () {
  37096. return this._axesList.slice();
  37097. };
  37098. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  37099. if (xAxisIndex != null && yAxisIndex != null) {
  37100. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  37101. return this._coordsMap[key];
  37102. }
  37103. if (isObject(xAxisIndex)) {
  37104. yAxisIndex = xAxisIndex.yAxisIndex;
  37105. xAxisIndex = xAxisIndex.xAxisIndex;
  37106. }
  37107. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  37108. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  37109. return coordList[i];
  37110. }
  37111. }
  37112. };
  37113. Grid.prototype.getCartesians = function () {
  37114. return this._coordsList.slice();
  37115. };
  37116. /**
  37117. * @implements
  37118. */
  37119. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  37120. var target = this._findConvertTarget(finder);
  37121. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  37122. };
  37123. /**
  37124. * @implements
  37125. */
  37126. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  37127. var target = this._findConvertTarget(finder);
  37128. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  37129. };
  37130. Grid.prototype._findConvertTarget = function (finder) {
  37131. var seriesModel = finder.seriesModel;
  37132. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  37133. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  37134. var gridModel = finder.gridModel;
  37135. var coordsList = this._coordsList;
  37136. var cartesian;
  37137. var axis;
  37138. if (seriesModel) {
  37139. cartesian = seriesModel.coordinateSystem;
  37140. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  37141. } else if (xAxisModel && yAxisModel) {
  37142. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  37143. } else if (xAxisModel) {
  37144. axis = this.getAxis('x', xAxisModel.componentIndex);
  37145. } else if (yAxisModel) {
  37146. axis = this.getAxis('y', yAxisModel.componentIndex);
  37147. } // Lowest priority.
  37148. else if (gridModel) {
  37149. var grid = gridModel.coordinateSystem;
  37150. if (grid === this) {
  37151. cartesian = this._coordsList[0];
  37152. }
  37153. }
  37154. return {
  37155. cartesian: cartesian,
  37156. axis: axis
  37157. };
  37158. };
  37159. /**
  37160. * @implements
  37161. */
  37162. Grid.prototype.containPoint = function (point) {
  37163. var coord = this._coordsList[0];
  37164. if (coord) {
  37165. return coord.containPoint(point);
  37166. }
  37167. };
  37168. /**
  37169. * Initialize cartesian coordinate systems
  37170. */
  37171. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  37172. var _this = this;
  37173. var grid = this;
  37174. var axisPositionUsed = {
  37175. left: false,
  37176. right: false,
  37177. top: false,
  37178. bottom: false
  37179. };
  37180. var axesMap = {
  37181. x: {},
  37182. y: {}
  37183. };
  37184. var axesCount = {
  37185. x: 0,
  37186. y: 0
  37187. }; /// Create axis
  37188. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  37189. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  37190. if (!axesCount.x || !axesCount.y) {
  37191. // Roll back when there no either x or y axis
  37192. this._axesMap = {};
  37193. this._axesList = [];
  37194. return;
  37195. }
  37196. this._axesMap = axesMap; /// Create cartesian2d
  37197. each(axesMap.x, function (xAxis, xAxisIndex) {
  37198. each(axesMap.y, function (yAxis, yAxisIndex) {
  37199. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  37200. var cartesian = new Cartesian2D(key);
  37201. cartesian.master = _this;
  37202. cartesian.model = gridModel;
  37203. _this._coordsMap[key] = cartesian;
  37204. _this._coordsList.push(cartesian);
  37205. cartesian.addAxis(xAxis);
  37206. cartesian.addAxis(yAxis);
  37207. });
  37208. });
  37209. function createAxisCreator(dimName) {
  37210. return function (axisModel, idx) {
  37211. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  37212. return;
  37213. }
  37214. var axisPosition = axisModel.get('position');
  37215. if (dimName === 'x') {
  37216. // Fix position
  37217. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  37218. // Default bottom of X
  37219. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  37220. }
  37221. } else {
  37222. // Fix position
  37223. if (axisPosition !== 'left' && axisPosition !== 'right') {
  37224. // Default left of Y
  37225. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  37226. }
  37227. }
  37228. axisPositionUsed[axisPosition] = true;
  37229. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  37230. var isCategory = axis.type === 'category';
  37231. axis.onBand = isCategory && axisModel.get('boundaryGap');
  37232. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  37233. axisModel.axis = axis; // Inject axisModel into axis
  37234. axis.model = axisModel; // Inject grid info axis
  37235. axis.grid = grid; // Index of axis, can be used as key
  37236. axis.index = idx;
  37237. grid._axesList.push(axis);
  37238. axesMap[dimName][idx] = axis;
  37239. axesCount[dimName]++;
  37240. };
  37241. }
  37242. };
  37243. /**
  37244. * Update cartesian properties from series.
  37245. */
  37246. Grid.prototype._updateScale = function (ecModel, gridModel) {
  37247. // Reset scale
  37248. each(this._axesList, function (axis) {
  37249. axis.scale.setExtent(Infinity, -Infinity);
  37250. if (axis.type === 'category') {
  37251. var categorySortInfo = axis.model.get('categorySortInfo');
  37252. axis.scale.setSortInfo(categorySortInfo);
  37253. }
  37254. });
  37255. ecModel.eachSeries(function (seriesModel) {
  37256. if (isCartesian2DSeries(seriesModel)) {
  37257. var axesModelMap = findAxisModels(seriesModel);
  37258. var xAxisModel = axesModelMap.xAxisModel;
  37259. var yAxisModel = axesModelMap.yAxisModel;
  37260. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  37261. return;
  37262. }
  37263. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  37264. var data = seriesModel.getData();
  37265. var xAxis = cartesian.getAxis('x');
  37266. var yAxis = cartesian.getAxis('y');
  37267. if (data.type === 'list') {
  37268. unionExtent(data, xAxis);
  37269. unionExtent(data, yAxis);
  37270. }
  37271. }
  37272. }, this);
  37273. function unionExtent(data, axis) {
  37274. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  37275. axis.scale.unionExtentFromData(data, dim);
  37276. });
  37277. }
  37278. };
  37279. /**
  37280. * @param dim 'x' or 'y' or 'auto' or null/undefined
  37281. */
  37282. Grid.prototype.getTooltipAxes = function (dim) {
  37283. var baseAxes = [];
  37284. var otherAxes = [];
  37285. each(this.getCartesians(), function (cartesian) {
  37286. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  37287. var otherAxis = cartesian.getOtherAxis(baseAxis);
  37288. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  37289. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  37290. });
  37291. return {
  37292. baseAxes: baseAxes,
  37293. otherAxes: otherAxes
  37294. };
  37295. };
  37296. Grid.create = function (ecModel, api) {
  37297. var grids = [];
  37298. ecModel.eachComponent('grid', function (gridModel, idx) {
  37299. var grid = new Grid(gridModel, ecModel, api);
  37300. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  37301. // should be performed in create stage.
  37302. grid.resize(gridModel, api, true);
  37303. gridModel.coordinateSystem = grid;
  37304. grids.push(grid);
  37305. }); // Inject the coordinateSystems into seriesModel
  37306. ecModel.eachSeries(function (seriesModel) {
  37307. if (!isCartesian2DSeries(seriesModel)) {
  37308. return;
  37309. }
  37310. var axesModelMap = findAxisModels(seriesModel);
  37311. var xAxisModel = axesModelMap.xAxisModel;
  37312. var yAxisModel = axesModelMap.yAxisModel;
  37313. var gridModel = xAxisModel.getCoordSysModel();
  37314. if ("development" !== 'production') {
  37315. if (!gridModel) {
  37316. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  37317. }
  37318. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  37319. throw new Error('xAxis and yAxis must use the same grid');
  37320. }
  37321. }
  37322. var grid = gridModel.coordinateSystem;
  37323. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  37324. });
  37325. return grids;
  37326. }; // For deciding which dimensions to use when creating list data
  37327. Grid.dimensions = cartesian2DDimensions;
  37328. return Grid;
  37329. }();
  37330. /**
  37331. * Check if the axis is used in the specified grid.
  37332. */
  37333. function isAxisUsedInTheGrid(axisModel, gridModel) {
  37334. return axisModel.getCoordSysModel() === gridModel;
  37335. }
  37336. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  37337. onZeroRecords) {
  37338. axis.getAxesOnZeroOf = function () {
  37339. // TODO: onZero of multiple axes.
  37340. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  37341. }; // onZero can not be enabled in these two situations:
  37342. // 1. When any other axis is a category axis.
  37343. // 2. When no axis is cross 0 point.
  37344. var otherAxes = axesMap[otherAxisDim];
  37345. var otherAxisOnZeroOf;
  37346. var axisModel = axis.model;
  37347. var onZero = axisModel.get(['axisLine', 'onZero']);
  37348. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  37349. if (!onZero) {
  37350. return;
  37351. } // If target axis is specified.
  37352. if (onZeroAxisIndex != null) {
  37353. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  37354. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  37355. }
  37356. } else {
  37357. // Find the first available other axis.
  37358. for (var idx in otherAxes) {
  37359. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  37360. // if both onZero, the two Y axes overlap.
  37361. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  37362. otherAxisOnZeroOf = otherAxes[idx];
  37363. break;
  37364. }
  37365. }
  37366. }
  37367. if (otherAxisOnZeroOf) {
  37368. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  37369. }
  37370. function getOnZeroRecordKey(axis) {
  37371. return axis.dim + '_' + axis.index;
  37372. }
  37373. }
  37374. function canOnZeroToAxis(axis) {
  37375. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  37376. }
  37377. function updateAxisTransform(axis, coordBase) {
  37378. var axisExtent = axis.getExtent();
  37379. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  37380. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  37381. return coord + coordBase;
  37382. } : function (coord) {
  37383. return axisExtentSum - coord + coordBase;
  37384. };
  37385. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  37386. return coord - coordBase;
  37387. } : function (coord) {
  37388. return axisExtentSum - coord + coordBase;
  37389. };
  37390. }
  37391. var PI$4 = Math.PI;
  37392. /**
  37393. * A final axis is translated and rotated from a "standard axis".
  37394. * So opt.position and opt.rotation is required.
  37395. *
  37396. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  37397. * for example: (0, 0) ------------> (0, 50)
  37398. *
  37399. * nameDirection or tickDirection or labelDirection is 1 means tick
  37400. * or label is below the standard axis, whereas is -1 means above
  37401. * the standard axis. labelOffset means offset between label and axis,
  37402. * which is useful when 'onZero', where axisLabel is in the grid and
  37403. * label in outside grid.
  37404. *
  37405. * Tips: like always,
  37406. * positive rotation represents anticlockwise, and negative rotation
  37407. * represents clockwise.
  37408. * The direction of position coordinate is the same as the direction
  37409. * of screen coordinate.
  37410. *
  37411. * Do not need to consider axis 'inverse', which is auto processed by
  37412. * axis extent.
  37413. */
  37414. var AxisBuilder =
  37415. /** @class */
  37416. function () {
  37417. function AxisBuilder(axisModel, opt) {
  37418. this.group = new Group();
  37419. this.opt = opt;
  37420. this.axisModel = axisModel; // Default value
  37421. defaults(opt, {
  37422. labelOffset: 0,
  37423. nameDirection: 1,
  37424. tickDirection: 1,
  37425. labelDirection: 1,
  37426. silent: true,
  37427. handleAutoShown: function () {
  37428. return true;
  37429. }
  37430. }); // FIXME Not use a seperate text group?
  37431. var transformGroup = new Group({
  37432. x: opt.position[0],
  37433. y: opt.position[1],
  37434. rotation: opt.rotation
  37435. }); // this.group.add(transformGroup);
  37436. // this._transformGroup = transformGroup;
  37437. transformGroup.updateTransform();
  37438. this._transformGroup = transformGroup;
  37439. }
  37440. AxisBuilder.prototype.hasBuilder = function (name) {
  37441. return !!builders[name];
  37442. };
  37443. AxisBuilder.prototype.add = function (name) {
  37444. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  37445. };
  37446. AxisBuilder.prototype.getGroup = function () {
  37447. return this.group;
  37448. };
  37449. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  37450. var rotationDiff = remRadian(textRotation - axisRotation);
  37451. var textAlign;
  37452. var textVerticalAlign;
  37453. if (isRadianAroundZero(rotationDiff)) {
  37454. // Label is parallel with axis line.
  37455. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  37456. textAlign = 'center';
  37457. } else if (isRadianAroundZero(rotationDiff - PI$4)) {
  37458. // Label is inverse parallel with axis line.
  37459. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  37460. textAlign = 'center';
  37461. } else {
  37462. textVerticalAlign = 'middle';
  37463. if (rotationDiff > 0 && rotationDiff < PI$4) {
  37464. textAlign = direction > 0 ? 'right' : 'left';
  37465. } else {
  37466. textAlign = direction > 0 ? 'left' : 'right';
  37467. }
  37468. }
  37469. return {
  37470. rotation: rotationDiff,
  37471. textAlign: textAlign,
  37472. textVerticalAlign: textVerticalAlign
  37473. };
  37474. };
  37475. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  37476. var eventData = {
  37477. componentType: axisModel.mainType,
  37478. componentIndex: axisModel.componentIndex
  37479. };
  37480. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  37481. return eventData;
  37482. };
  37483. AxisBuilder.isLabelSilent = function (axisModel) {
  37484. var tooltipOpt = axisModel.get('tooltip');
  37485. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  37486. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  37487. };
  37488. return AxisBuilder;
  37489. }();
  37490. var builders = {
  37491. axisLine: function (opt, axisModel, group, transformGroup) {
  37492. var shown = axisModel.get(['axisLine', 'show']);
  37493. if (shown === 'auto' && opt.handleAutoShown) {
  37494. shown = opt.handleAutoShown('axisLine');
  37495. }
  37496. if (!shown) {
  37497. return;
  37498. }
  37499. var extent = axisModel.axis.getExtent();
  37500. var matrix = transformGroup.transform;
  37501. var pt1 = [extent[0], 0];
  37502. var pt2 = [extent[1], 0];
  37503. if (matrix) {
  37504. applyTransform(pt1, pt1, matrix);
  37505. applyTransform(pt2, pt2, matrix);
  37506. }
  37507. var lineStyle = extend({
  37508. lineCap: 'round'
  37509. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  37510. var line = new Line({
  37511. // Id for animation
  37512. subPixelOptimize: true,
  37513. shape: {
  37514. x1: pt1[0],
  37515. y1: pt1[1],
  37516. x2: pt2[0],
  37517. y2: pt2[1]
  37518. },
  37519. style: lineStyle,
  37520. strokeContainThreshold: opt.strokeContainThreshold || 5,
  37521. silent: true,
  37522. z2: 1
  37523. });
  37524. line.anid = 'line';
  37525. group.add(line);
  37526. var arrows = axisModel.get(['axisLine', 'symbol']);
  37527. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  37528. var arrowOffset = axisModel.get(['axisLine', 'symbolOffset']) || 0;
  37529. if (typeof arrowOffset === 'number') {
  37530. arrowOffset = [arrowOffset, arrowOffset];
  37531. }
  37532. if (arrows != null) {
  37533. if (typeof arrows === 'string') {
  37534. // Use the same arrow for start and end point
  37535. arrows = [arrows, arrows];
  37536. }
  37537. if (typeof arrowSize === 'string' || typeof arrowSize === 'number') {
  37538. // Use the same size for width and height
  37539. arrowSize = [arrowSize, arrowSize];
  37540. }
  37541. var symbolWidth_1 = arrowSize[0];
  37542. var symbolHeight_1 = arrowSize[1];
  37543. each([{
  37544. rotate: opt.rotation + Math.PI / 2,
  37545. offset: arrowOffset[0],
  37546. r: 0
  37547. }, {
  37548. rotate: opt.rotation - Math.PI / 2,
  37549. offset: arrowOffset[1],
  37550. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  37551. }], function (point, index) {
  37552. if (arrows[index] !== 'none' && arrows[index] != null) {
  37553. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  37554. var r = point.r + point.offset;
  37555. symbol.attr({
  37556. rotation: point.rotate,
  37557. x: pt1[0] + r * Math.cos(opt.rotation),
  37558. y: pt1[1] - r * Math.sin(opt.rotation),
  37559. silent: true,
  37560. z2: 11
  37561. });
  37562. group.add(symbol);
  37563. }
  37564. });
  37565. }
  37566. },
  37567. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  37568. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  37569. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  37570. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  37571. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection);
  37572. },
  37573. axisName: function (opt, axisModel, group, transformGroup) {
  37574. var name = retrieve(opt.axisName, axisModel.get('name'));
  37575. if (!name) {
  37576. return;
  37577. }
  37578. var nameLocation = axisModel.get('nameLocation');
  37579. var nameDirection = opt.nameDirection;
  37580. var textStyleModel = axisModel.getModel('nameTextStyle');
  37581. var gap = axisModel.get('nameGap') || 0;
  37582. var extent = axisModel.axis.getExtent();
  37583. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  37584. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  37585. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  37586. var labelLayout;
  37587. var nameRotation = axisModel.get('nameRotate');
  37588. if (nameRotation != null) {
  37589. nameRotation = nameRotation * PI$4 / 180; // To radian.
  37590. }
  37591. var axisNameAvailableWidth;
  37592. if (isNameLocationCenter(nameLocation)) {
  37593. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  37594. nameDirection);
  37595. } else {
  37596. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  37597. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  37598. if (axisNameAvailableWidth != null) {
  37599. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  37600. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  37601. }
  37602. }
  37603. var textFont = textStyleModel.getFont();
  37604. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  37605. var ellipsis = truncateOpt.ellipsis;
  37606. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  37607. var tooltipOpt = axisModel.get('tooltip', true);
  37608. var mainType = axisModel.mainType;
  37609. var formatterParams = {
  37610. componentType: mainType,
  37611. name: name,
  37612. $vars: ['name']
  37613. };
  37614. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  37615. var textEl = new ZRText({
  37616. x: pos[0],
  37617. y: pos[1],
  37618. rotation: labelLayout.rotation,
  37619. silent: AxisBuilder.isLabelSilent(axisModel),
  37620. style: createTextStyle(textStyleModel, {
  37621. text: name,
  37622. font: textFont,
  37623. overflow: 'truncate',
  37624. width: maxWidth,
  37625. ellipsis: ellipsis,
  37626. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  37627. align: textStyleModel.get('align') || labelLayout.textAlign,
  37628. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  37629. }),
  37630. z2: 1
  37631. });
  37632. textEl.tooltip = tooltipOpt && tooltipOpt.show ? extend({
  37633. content: name,
  37634. formatter: function () {
  37635. return name;
  37636. },
  37637. formatterParams: formatterParams
  37638. }, tooltipOpt) : null;
  37639. textEl.__fullText = name; // Id for animation
  37640. textEl.anid = 'name';
  37641. if (axisModel.get('triggerEvent')) {
  37642. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  37643. eventData.targetType = 'axisName';
  37644. eventData.name = name;
  37645. getECData(textEl).eventData = eventData;
  37646. } // FIXME
  37647. transformGroup.add(textEl);
  37648. textEl.updateTransform();
  37649. group.add(textEl);
  37650. textEl.decomposeTransform();
  37651. }
  37652. };
  37653. function endTextLayout(rotation, textPosition, textRotate, extent) {
  37654. var rotationDiff = remRadian(textRotate - rotation);
  37655. var textAlign;
  37656. var textVerticalAlign;
  37657. var inverse = extent[0] > extent[1];
  37658. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  37659. if (isRadianAroundZero(rotationDiff - PI$4 / 2)) {
  37660. textVerticalAlign = onLeft ? 'bottom' : 'top';
  37661. textAlign = 'center';
  37662. } else if (isRadianAroundZero(rotationDiff - PI$4 * 1.5)) {
  37663. textVerticalAlign = onLeft ? 'top' : 'bottom';
  37664. textAlign = 'center';
  37665. } else {
  37666. textVerticalAlign = 'middle';
  37667. if (rotationDiff < PI$4 * 1.5 && rotationDiff > PI$4 / 2) {
  37668. textAlign = onLeft ? 'left' : 'right';
  37669. } else {
  37670. textAlign = onLeft ? 'right' : 'left';
  37671. }
  37672. }
  37673. return {
  37674. rotation: rotationDiff,
  37675. textAlign: textAlign,
  37676. textVerticalAlign: textVerticalAlign
  37677. };
  37678. }
  37679. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  37680. if (shouldShowAllLabels(axisModel.axis)) {
  37681. return;
  37682. } // If min or max are user set, we need to check
  37683. // If the tick on min(max) are overlap on their neighbour tick
  37684. // If they are overlapped, we need to hide the min(max) tick label
  37685. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  37686. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  37687. // Have not consider onBand yet, where tick els is more than label els.
  37688. labelEls = labelEls || [];
  37689. tickEls = tickEls || [];
  37690. var firstLabel = labelEls[0];
  37691. var nextLabel = labelEls[1];
  37692. var lastLabel = labelEls[labelEls.length - 1];
  37693. var prevLabel = labelEls[labelEls.length - 2];
  37694. var firstTick = tickEls[0];
  37695. var nextTick = tickEls[1];
  37696. var lastTick = tickEls[tickEls.length - 1];
  37697. var prevTick = tickEls[tickEls.length - 2];
  37698. if (showMinLabel === false) {
  37699. ignoreEl(firstLabel);
  37700. ignoreEl(firstTick);
  37701. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  37702. if (showMinLabel) {
  37703. ignoreEl(nextLabel);
  37704. ignoreEl(nextTick);
  37705. } else {
  37706. ignoreEl(firstLabel);
  37707. ignoreEl(firstTick);
  37708. }
  37709. }
  37710. if (showMaxLabel === false) {
  37711. ignoreEl(lastLabel);
  37712. ignoreEl(lastTick);
  37713. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  37714. if (showMaxLabel) {
  37715. ignoreEl(prevLabel);
  37716. ignoreEl(prevTick);
  37717. } else {
  37718. ignoreEl(lastLabel);
  37719. ignoreEl(lastTick);
  37720. }
  37721. }
  37722. }
  37723. function ignoreEl(el) {
  37724. el && (el.ignore = true);
  37725. }
  37726. function isTwoLabelOverlapped(current, next) {
  37727. // current and next has the same rotation.
  37728. var firstRect = current && current.getBoundingRect().clone();
  37729. var nextRect = next && next.getBoundingRect().clone();
  37730. if (!firstRect || !nextRect) {
  37731. return;
  37732. } // When checking intersect of two rotated labels, we use mRotationBack
  37733. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  37734. var mRotationBack = identity([]);
  37735. rotate(mRotationBack, mRotationBack, -current.rotation);
  37736. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  37737. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  37738. return firstRect.intersect(nextRect);
  37739. }
  37740. function isNameLocationCenter(nameLocation) {
  37741. return nameLocation === 'middle' || nameLocation === 'center';
  37742. }
  37743. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  37744. var tickEls = [];
  37745. var pt1 = [];
  37746. var pt2 = [];
  37747. for (var i = 0; i < ticksCoords.length; i++) {
  37748. var tickCoord = ticksCoords[i].coord;
  37749. pt1[0] = tickCoord;
  37750. pt1[1] = 0;
  37751. pt2[0] = tickCoord;
  37752. pt2[1] = tickEndCoord;
  37753. if (tickTransform) {
  37754. applyTransform(pt1, pt1, tickTransform);
  37755. applyTransform(pt2, pt2, tickTransform);
  37756. } // Tick line, Not use group transform to have better line draw
  37757. var tickEl = new Line({
  37758. subPixelOptimize: true,
  37759. shape: {
  37760. x1: pt1[0],
  37761. y1: pt1[1],
  37762. x2: pt2[0],
  37763. y2: pt2[1]
  37764. },
  37765. style: tickLineStyle,
  37766. z2: 2,
  37767. autoBatch: true,
  37768. silent: true
  37769. });
  37770. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  37771. tickEls.push(tickEl);
  37772. }
  37773. return tickEls;
  37774. }
  37775. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  37776. var axis = axisModel.axis;
  37777. var tickModel = axisModel.getModel('axisTick');
  37778. var shown = tickModel.get('show');
  37779. if (shown === 'auto' && opt.handleAutoShown) {
  37780. shown = opt.handleAutoShown('axisTick');
  37781. }
  37782. if (!shown || axis.scale.isBlank()) {
  37783. return;
  37784. }
  37785. var lineStyleModel = tickModel.getModel('lineStyle');
  37786. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  37787. var ticksCoords = axis.getTicksCoords();
  37788. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  37789. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  37790. }), 'ticks');
  37791. for (var i = 0; i < ticksEls.length; i++) {
  37792. group.add(ticksEls[i]);
  37793. }
  37794. return ticksEls;
  37795. }
  37796. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  37797. var axis = axisModel.axis;
  37798. var minorTickModel = axisModel.getModel('minorTick');
  37799. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  37800. return;
  37801. }
  37802. var minorTicksCoords = axis.getMinorTicksCoords();
  37803. if (!minorTicksCoords.length) {
  37804. return;
  37805. }
  37806. var lineStyleModel = minorTickModel.getModel('lineStyle');
  37807. var tickEndCoord = tickDirection * minorTickModel.get('length');
  37808. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  37809. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  37810. }));
  37811. for (var i = 0; i < minorTicksCoords.length; i++) {
  37812. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  37813. for (var k = 0; k < minorTicksEls.length; k++) {
  37814. group.add(minorTicksEls[k]);
  37815. }
  37816. }
  37817. }
  37818. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  37819. var axis = axisModel.axis;
  37820. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  37821. if (!show || axis.scale.isBlank()) {
  37822. return;
  37823. }
  37824. var labelModel = axisModel.getModel('axisLabel');
  37825. var labelMargin = labelModel.get('margin');
  37826. var labels = axis.getViewLabels(); // Special label rotate.
  37827. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$4 / 180;
  37828. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  37829. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  37830. var labelEls = [];
  37831. var silent = AxisBuilder.isLabelSilent(axisModel);
  37832. var triggerEvent = axisModel.get('triggerEvent');
  37833. each(labels, function (labelItem, index) {
  37834. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  37835. var formattedLabel = labelItem.formattedLabel;
  37836. var rawLabel = labelItem.rawLabel;
  37837. var itemLabelModel = labelModel;
  37838. if (rawCategoryData && rawCategoryData[tickValue]) {
  37839. var rawCategoryItem = rawCategoryData[tickValue];
  37840. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  37841. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  37842. }
  37843. }
  37844. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  37845. var tickCoord = axis.dataToCoord(tickValue);
  37846. var textEl = new ZRText({
  37847. x: tickCoord,
  37848. y: opt.labelOffset + opt.labelDirection * labelMargin,
  37849. rotation: labelLayout.rotation,
  37850. silent: silent,
  37851. z2: 10,
  37852. style: createTextStyle(itemLabelModel, {
  37853. text: formattedLabel,
  37854. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  37855. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  37856. fill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original
  37857. // index of axis.data. So tick should not be exposed to user
  37858. // in category axis.
  37859. // (2) Compatible with previous version, which always use formatted label as
  37860. // input. But in interval scale the formatted label is like '223,445', which
  37861. // maked user repalce ','. So we modify it to return original val but remain
  37862. // it as 'string' to avoid error in replacing.
  37863. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  37864. })
  37865. });
  37866. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  37867. if (triggerEvent) {
  37868. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  37869. eventData.targetType = 'axisLabel';
  37870. eventData.value = rawLabel;
  37871. getECData(textEl).eventData = eventData;
  37872. } // FIXME
  37873. transformGroup.add(textEl);
  37874. textEl.updateTransform();
  37875. labelEls.push(textEl);
  37876. group.add(textEl);
  37877. textEl.decomposeTransform();
  37878. });
  37879. return labelEls;
  37880. }
  37881. function fixValue(axisModel) {
  37882. var axisInfo = getAxisInfo(axisModel);
  37883. if (!axisInfo) {
  37884. return;
  37885. }
  37886. var axisPointerModel = axisInfo.axisPointerModel;
  37887. var scale = axisInfo.axis.scale;
  37888. var option = axisPointerModel.option;
  37889. var status = axisPointerModel.get('status');
  37890. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  37891. if (value != null) {
  37892. value = scale.parse(value);
  37893. }
  37894. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  37895. // and status should be initialized.
  37896. if (status == null) {
  37897. option.status = useHandle ? 'show' : 'hide';
  37898. }
  37899. var extent = scale.getExtent().slice();
  37900. extent[0] > extent[1] && extent.reverse();
  37901. if ( // Pick a value on axis when initializing.
  37902. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  37903. // where we should re-pick a value to keep `handle` displaying normally.
  37904. || value > extent[1]) {
  37905. // Make handle displayed on the end of the axis when init, which looks better.
  37906. value = extent[1];
  37907. }
  37908. if (value < extent[0]) {
  37909. value = extent[0];
  37910. }
  37911. option.value = value;
  37912. if (useHandle) {
  37913. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  37914. }
  37915. }
  37916. function getAxisInfo(axisModel) {
  37917. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  37918. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  37919. }
  37920. function getAxisPointerModel(axisModel) {
  37921. var axisInfo = getAxisInfo(axisModel);
  37922. return axisInfo && axisInfo.axisPointerModel;
  37923. }
  37924. function isHandleTrigger(axisPointerModel) {
  37925. return !!axisPointerModel.get(['handle', 'show']);
  37926. }
  37927. /**
  37928. * @param {module:echarts/model/Model} model
  37929. * @return {string} unique key
  37930. */
  37931. function makeKey(model) {
  37932. return model.type + '||' + model.id;
  37933. }
  37934. var axisPointerClazz = {};
  37935. /**
  37936. * Base class of AxisView.
  37937. */
  37938. var AxisView =
  37939. /** @class */
  37940. function (_super) {
  37941. __extends(AxisView, _super);
  37942. function AxisView() {
  37943. var _this = _super !== null && _super.apply(this, arguments) || this;
  37944. _this.type = AxisView.type;
  37945. return _this;
  37946. }
  37947. /**
  37948. * @override
  37949. */
  37950. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  37951. // FIXME
  37952. // This process should proformed after coordinate systems updated
  37953. // (axis scale updated), and should be performed each time update.
  37954. // So put it here temporarily, although it is not appropriate to
  37955. // put a model-writing procedure in `view`.
  37956. this.axisPointerClass && fixValue(axisModel);
  37957. _super.prototype.render.apply(this, arguments);
  37958. this._doUpdateAxisPointerClass(axisModel, api, true);
  37959. };
  37960. /**
  37961. * Action handler.
  37962. */
  37963. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  37964. this._doUpdateAxisPointerClass(axisModel, api, false);
  37965. };
  37966. /**
  37967. * @override
  37968. */
  37969. AxisView.prototype.remove = function (ecModel, api) {
  37970. var axisPointer = this._axisPointer;
  37971. axisPointer && axisPointer.remove(api);
  37972. };
  37973. /**
  37974. * @override
  37975. */
  37976. AxisView.prototype.dispose = function (ecModel, api) {
  37977. this._disposeAxisPointer(api);
  37978. _super.prototype.dispose.apply(this, arguments);
  37979. };
  37980. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  37981. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  37982. if (!Clazz) {
  37983. return;
  37984. }
  37985. var axisPointerModel = getAxisPointerModel(axisModel);
  37986. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  37987. };
  37988. AxisView.prototype._disposeAxisPointer = function (api) {
  37989. this._axisPointer && this._axisPointer.dispose(api);
  37990. this._axisPointer = null;
  37991. };
  37992. AxisView.registerAxisPointerClass = function (type, clazz) {
  37993. if ("development" !== 'production') {
  37994. if (axisPointerClazz[type]) {
  37995. throw new Error('axisPointer ' + type + ' exists');
  37996. }
  37997. }
  37998. axisPointerClazz[type] = clazz;
  37999. };
  38000. AxisView.getAxisPointerClass = function (type) {
  38001. return type && axisPointerClazz[type];
  38002. };
  38003. AxisView.type = 'axis';
  38004. return AxisView;
  38005. }(ComponentView);
  38006. var inner$5 = makeInner();
  38007. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  38008. var axis = axisModel.axis;
  38009. if (axis.scale.isBlank()) {
  38010. return;
  38011. } // TODO: TYPE
  38012. var splitAreaModel = axisModel.getModel('splitArea');
  38013. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  38014. var areaColors = areaStyleModel.get('color');
  38015. var gridRect = gridModel.coordinateSystem.getRect();
  38016. var ticksCoords = axis.getTicksCoords({
  38017. tickModel: splitAreaModel,
  38018. clamp: true
  38019. });
  38020. if (!ticksCoords.length) {
  38021. return;
  38022. } // For Making appropriate splitArea animation, the color and anid
  38023. // should be corresponding to previous one if possible.
  38024. var areaColorsLen = areaColors.length;
  38025. var lastSplitAreaColors = inner$5(axisView).splitAreaColors;
  38026. var newSplitAreaColors = createHashMap();
  38027. var colorIndex = 0;
  38028. if (lastSplitAreaColors) {
  38029. for (var i = 0; i < ticksCoords.length; i++) {
  38030. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  38031. if (cIndex != null) {
  38032. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  38033. break;
  38034. }
  38035. }
  38036. }
  38037. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  38038. var areaStyle = areaStyleModel.getAreaStyle();
  38039. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  38040. for (var i = 1; i < ticksCoords.length; i++) {
  38041. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  38042. var x = void 0;
  38043. var y = void 0;
  38044. var width = void 0;
  38045. var height = void 0;
  38046. if (axis.isHorizontal()) {
  38047. x = prev;
  38048. y = gridRect.y;
  38049. width = tickCoord - x;
  38050. height = gridRect.height;
  38051. prev = x + width;
  38052. } else {
  38053. x = gridRect.x;
  38054. y = prev;
  38055. width = gridRect.width;
  38056. height = tickCoord - y;
  38057. prev = y + height;
  38058. }
  38059. var tickValue = ticksCoords[i - 1].tickValue;
  38060. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  38061. axisGroup.add(new Rect({
  38062. anid: tickValue != null ? 'area_' + tickValue : null,
  38063. shape: {
  38064. x: x,
  38065. y: y,
  38066. width: width,
  38067. height: height
  38068. },
  38069. style: defaults({
  38070. fill: areaColors[colorIndex]
  38071. }, areaStyle),
  38072. autoBatch: true,
  38073. silent: true
  38074. }));
  38075. colorIndex = (colorIndex + 1) % areaColorsLen;
  38076. }
  38077. inner$5(axisView).splitAreaColors = newSplitAreaColors;
  38078. }
  38079. function rectCoordAxisHandleRemove(axisView) {
  38080. inner$5(axisView).splitAreaColors = null;
  38081. }
  38082. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  38083. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  38084. var CartesianAxisView =
  38085. /** @class */
  38086. function (_super) {
  38087. __extends(CartesianAxisView, _super);
  38088. function CartesianAxisView() {
  38089. var _this = _super !== null && _super.apply(this, arguments) || this;
  38090. _this.type = CartesianAxisView.type;
  38091. _this.axisPointerClass = 'CartesianAxisPointer';
  38092. return _this;
  38093. }
  38094. /**
  38095. * @override
  38096. */
  38097. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  38098. this.group.removeAll();
  38099. var oldAxisGroup = this._axisGroup;
  38100. this._axisGroup = new Group();
  38101. this.group.add(this._axisGroup);
  38102. if (!axisModel.get('show')) {
  38103. return;
  38104. }
  38105. var gridModel = axisModel.getCoordSysModel();
  38106. var layout = layout$1(gridModel, axisModel);
  38107. var axisBuilder = new AxisBuilder(axisModel, extend({
  38108. handleAutoShown: function (elementType) {
  38109. var cartesians = gridModel.coordinateSystem.getCartesians();
  38110. for (var i = 0; i < cartesians.length; i++) {
  38111. var otherAxisType = cartesians[i].getOtherAxis(axisModel.axis).type;
  38112. if (otherAxisType === 'value' || otherAxisType === 'log') {
  38113. // Still show axis tick or axisLine if other axis is value / log
  38114. return true;
  38115. }
  38116. } // Not show axisTick or axisLine if other axis is category / time
  38117. return false;
  38118. }
  38119. }, layout));
  38120. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  38121. this._axisGroup.add(axisBuilder.getGroup());
  38122. each(selfBuilderAttrs, function (name) {
  38123. if (axisModel.get([name, 'show'])) {
  38124. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  38125. }
  38126. }, this);
  38127. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  38128. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  38129. };
  38130. CartesianAxisView.prototype.remove = function () {
  38131. rectCoordAxisHandleRemove(this);
  38132. };
  38133. CartesianAxisView.type = 'cartesianAxis';
  38134. return CartesianAxisView;
  38135. }(AxisView);
  38136. var axisElementBuilders = {
  38137. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  38138. var axis = axisModel.axis;
  38139. if (axis.scale.isBlank()) {
  38140. return;
  38141. }
  38142. var splitLineModel = axisModel.getModel('splitLine');
  38143. var lineStyleModel = splitLineModel.getModel('lineStyle');
  38144. var lineColors = lineStyleModel.get('color');
  38145. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  38146. var gridRect = gridModel.coordinateSystem.getRect();
  38147. var isHorizontal = axis.isHorizontal();
  38148. var lineCount = 0;
  38149. var ticksCoords = axis.getTicksCoords({
  38150. tickModel: splitLineModel
  38151. });
  38152. var p1 = [];
  38153. var p2 = [];
  38154. var lineStyle = lineStyleModel.getLineStyle();
  38155. for (var i = 0; i < ticksCoords.length; i++) {
  38156. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  38157. if (isHorizontal) {
  38158. p1[0] = tickCoord;
  38159. p1[1] = gridRect.y;
  38160. p2[0] = tickCoord;
  38161. p2[1] = gridRect.y + gridRect.height;
  38162. } else {
  38163. p1[0] = gridRect.x;
  38164. p1[1] = tickCoord;
  38165. p2[0] = gridRect.x + gridRect.width;
  38166. p2[1] = tickCoord;
  38167. }
  38168. var colorIndex = lineCount++ % lineColors.length;
  38169. var tickValue = ticksCoords[i].tickValue;
  38170. axisGroup.add(new Line({
  38171. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  38172. subPixelOptimize: true,
  38173. autoBatch: true,
  38174. shape: {
  38175. x1: p1[0],
  38176. y1: p1[1],
  38177. x2: p2[0],
  38178. y2: p2[1]
  38179. },
  38180. style: defaults({
  38181. stroke: lineColors[colorIndex]
  38182. }, lineStyle),
  38183. silent: true
  38184. }));
  38185. }
  38186. },
  38187. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  38188. var axis = axisModel.axis;
  38189. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  38190. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  38191. var gridRect = gridModel.coordinateSystem.getRect();
  38192. var isHorizontal = axis.isHorizontal();
  38193. var minorTicksCoords = axis.getMinorTicksCoords();
  38194. if (!minorTicksCoords.length) {
  38195. return;
  38196. }
  38197. var p1 = [];
  38198. var p2 = [];
  38199. var lineStyle = lineStyleModel.getLineStyle();
  38200. for (var i = 0; i < minorTicksCoords.length; i++) {
  38201. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  38202. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  38203. if (isHorizontal) {
  38204. p1[0] = tickCoord;
  38205. p1[1] = gridRect.y;
  38206. p2[0] = tickCoord;
  38207. p2[1] = gridRect.y + gridRect.height;
  38208. } else {
  38209. p1[0] = gridRect.x;
  38210. p1[1] = tickCoord;
  38211. p2[0] = gridRect.x + gridRect.width;
  38212. p2[1] = tickCoord;
  38213. }
  38214. axisGroup.add(new Line({
  38215. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  38216. subPixelOptimize: true,
  38217. autoBatch: true,
  38218. shape: {
  38219. x1: p1[0],
  38220. y1: p1[1],
  38221. x2: p2[0],
  38222. y2: p2[1]
  38223. },
  38224. style: lineStyle,
  38225. silent: true
  38226. }));
  38227. }
  38228. }
  38229. },
  38230. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  38231. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  38232. }
  38233. };
  38234. var CartesianXAxisView =
  38235. /** @class */
  38236. function (_super) {
  38237. __extends(CartesianXAxisView, _super);
  38238. function CartesianXAxisView() {
  38239. var _this = _super !== null && _super.apply(this, arguments) || this;
  38240. _this.type = CartesianXAxisView.type;
  38241. return _this;
  38242. }
  38243. CartesianXAxisView.type = 'xAxis';
  38244. return CartesianXAxisView;
  38245. }(CartesianAxisView);
  38246. var CartesianYAxisView =
  38247. /** @class */
  38248. function (_super) {
  38249. __extends(CartesianYAxisView, _super);
  38250. function CartesianYAxisView() {
  38251. var _this = _super !== null && _super.apply(this, arguments) || this;
  38252. _this.type = CartesianXAxisView.type;
  38253. return _this;
  38254. }
  38255. CartesianYAxisView.type = 'yAxis';
  38256. return CartesianYAxisView;
  38257. }(CartesianAxisView);
  38258. var GridView =
  38259. /** @class */
  38260. function (_super) {
  38261. __extends(GridView, _super);
  38262. function GridView() {
  38263. var _this = _super !== null && _super.apply(this, arguments) || this;
  38264. _this.type = 'grid';
  38265. return _this;
  38266. }
  38267. GridView.prototype.render = function (gridModel, ecModel) {
  38268. this.group.removeAll();
  38269. if (gridModel.get('show')) {
  38270. this.group.add(new Rect({
  38271. shape: gridModel.coordinateSystem.getRect(),
  38272. style: defaults({
  38273. fill: gridModel.get('backgroundColor')
  38274. }, gridModel.getItemStyle()),
  38275. silent: true,
  38276. z2: -1
  38277. }));
  38278. }
  38279. };
  38280. GridView.type = 'grid';
  38281. return GridView;
  38282. }(ComponentView);
  38283. var extraOption = {
  38284. // gridIndex: 0,
  38285. // gridId: '',
  38286. offset: 0
  38287. };
  38288. function install$4(registers) {
  38289. registers.registerComponentView(GridView);
  38290. registers.registerComponentModel(GridModel);
  38291. registers.registerCoordinateSystem('cartesian2d', Grid);
  38292. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  38293. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  38294. registers.registerComponentView(CartesianXAxisView);
  38295. registers.registerComponentView(CartesianYAxisView);
  38296. registers.registerPreprocessor(function (option) {
  38297. // Only create grid when need
  38298. if (option.xAxis && option.yAxis && !option.grid) {
  38299. option.grid = {};
  38300. }
  38301. });
  38302. }
  38303. var DEFAULT_OPTION = {
  38304. label: {
  38305. enabled: true
  38306. },
  38307. decal: {
  38308. show: false
  38309. }
  38310. };
  38311. var inner$6 = makeInner();
  38312. var decalPaletteScope = {};
  38313. function ariaVisual(ecModel, api) {
  38314. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  38315. if (!ariaModel.get('enabled')) {
  38316. return;
  38317. }
  38318. var defaultOption = clone(DEFAULT_OPTION);
  38319. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  38320. merge(ariaModel.option, defaultOption, false);
  38321. setDecal();
  38322. setLabel();
  38323. function setDecal() {
  38324. var decalModel = ariaModel.getModel('decal');
  38325. var useDecal = decalModel.get('show');
  38326. if (useDecal) {
  38327. // Each type of series use one scope.
  38328. // Pie and funnel are using diferrent scopes
  38329. var paletteScopeGroupByType_1 = createHashMap();
  38330. ecModel.eachSeries(function (seriesModel) {
  38331. if (!seriesModel.useColorPaletteOnData) {
  38332. return;
  38333. }
  38334. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  38335. if (!decalScope) {
  38336. decalScope = {};
  38337. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  38338. }
  38339. inner$6(seriesModel).scope = decalScope;
  38340. });
  38341. ecModel.eachRawSeries(function (seriesModel) {
  38342. if (ecModel.isSeriesFiltered(seriesModel)) {
  38343. return;
  38344. }
  38345. if (typeof seriesModel.enableAriaDecal === 'function') {
  38346. // Let series define how to use decal palette on data
  38347. seriesModel.enableAriaDecal();
  38348. return;
  38349. }
  38350. var data = seriesModel.getData();
  38351. if (seriesModel.useColorPaletteOnData) {
  38352. var dataAll_1 = seriesModel.getRawData();
  38353. var idxMap_1 = {};
  38354. var decalScope_1 = inner$6(seriesModel).scope;
  38355. data.each(function (idx) {
  38356. var rawIdx = data.getRawIndex(idx);
  38357. idxMap_1[rawIdx] = idx;
  38358. });
  38359. var dataCount_1 = dataAll_1.count();
  38360. dataAll_1.each(function (rawIdx) {
  38361. var idx = idxMap_1[rawIdx];
  38362. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  38363. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  38364. var specifiedDecal = data.getItemVisual(idx, 'decal');
  38365. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  38366. });
  38367. } else {
  38368. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  38369. var specifiedDecal = data.getVisual('decal');
  38370. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  38371. }
  38372. function mergeDecal(specifiedDecal, paletteDecal) {
  38373. // Merge decal from palette to decal from itemStyle.
  38374. // User do not need to specify all of the decal props.
  38375. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  38376. resultDecal.dirty = true;
  38377. return resultDecal;
  38378. }
  38379. });
  38380. }
  38381. }
  38382. function setLabel() {
  38383. var labelLocale = ecModel.getLocaleModel().get('aria');
  38384. var labelModel = ariaModel.getModel('label');
  38385. labelModel.option = defaults(labelModel.option, labelLocale);
  38386. if (!labelModel.get('enabled')) {
  38387. return;
  38388. }
  38389. var dom = api.getZr().dom;
  38390. if (labelModel.get('description')) {
  38391. dom.setAttribute('aria-label', labelModel.get('description'));
  38392. return;
  38393. }
  38394. var seriesCnt = ecModel.getSeriesCount();
  38395. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  38396. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  38397. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  38398. var ariaLabel;
  38399. if (seriesCnt < 1) {
  38400. // No series, no aria label
  38401. return;
  38402. } else {
  38403. var title = getTitle();
  38404. if (title) {
  38405. var withTitle = labelModel.get(['general', 'withTitle']);
  38406. ariaLabel = replace(withTitle, {
  38407. title: title
  38408. });
  38409. } else {
  38410. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  38411. }
  38412. var seriesLabels_1 = [];
  38413. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  38414. ariaLabel += replace(prefix, {
  38415. seriesCount: seriesCnt
  38416. });
  38417. ecModel.eachSeries(function (seriesModel, idx) {
  38418. if (idx < displaySeriesCnt) {
  38419. var seriesLabel = void 0;
  38420. var seriesName = seriesModel.get('name');
  38421. var withName = seriesName ? 'withName' : 'withoutName';
  38422. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  38423. seriesLabel = replace(seriesLabel, {
  38424. seriesId: seriesModel.seriesIndex,
  38425. seriesName: seriesModel.get('name'),
  38426. seriesType: getSeriesTypeName(seriesModel.subType)
  38427. });
  38428. var data = seriesModel.getData();
  38429. if (data.count() > maxDataCnt) {
  38430. // Show part of data
  38431. var partialLabel = labelModel.get(['data', 'partialData']);
  38432. seriesLabel += replace(partialLabel, {
  38433. displayCnt: maxDataCnt
  38434. });
  38435. } else {
  38436. seriesLabel += labelModel.get(['data', 'allData']);
  38437. }
  38438. var dataLabels = [];
  38439. for (var i = 0; i < data.count(); i++) {
  38440. if (i < maxDataCnt) {
  38441. var name_1 = data.getName(i);
  38442. var value = retrieveRawValue(data, i);
  38443. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  38444. dataLabels.push(replace(dataLabel, {
  38445. name: name_1,
  38446. value: value
  38447. }));
  38448. }
  38449. }
  38450. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  38451. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  38452. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  38453. seriesLabels_1.push(seriesLabel);
  38454. }
  38455. });
  38456. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  38457. var middleSeparator = separatorModel.get('middle');
  38458. var endSeparator = separatorModel.get('end');
  38459. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  38460. dom.setAttribute('aria-label', ariaLabel);
  38461. }
  38462. }
  38463. function replace(str, keyValues) {
  38464. if (typeof str !== 'string') {
  38465. return str;
  38466. }
  38467. var result = str;
  38468. each(keyValues, function (value, key) {
  38469. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  38470. });
  38471. return result;
  38472. }
  38473. function getTitle() {
  38474. var title = ecModel.get('title');
  38475. if (title && title.length) {
  38476. title = title[0];
  38477. }
  38478. return title && title.text;
  38479. }
  38480. function getSeriesTypeName(type) {
  38481. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  38482. }
  38483. }
  38484. function ariaPreprocessor(option) {
  38485. if (!option || !option.aria) {
  38486. return;
  38487. }
  38488. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  38489. if (aria.show != null) {
  38490. aria.enabled = aria.show;
  38491. }
  38492. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  38493. each(['description', 'general', 'series', 'data'], function (name) {
  38494. if (aria[name] != null) {
  38495. aria.label[name] = aria[name];
  38496. }
  38497. });
  38498. }
  38499. function install$5(registers) {
  38500. registers.registerPreprocessor(ariaPreprocessor);
  38501. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  38502. }
  38503. var DatasetModel =
  38504. /** @class */
  38505. function (_super) {
  38506. __extends(DatasetModel, _super);
  38507. function DatasetModel() {
  38508. var _this = _super !== null && _super.apply(this, arguments) || this;
  38509. _this.type = 'dataset';
  38510. return _this;
  38511. }
  38512. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  38513. _super.prototype.init.call(this, option, parentModel, ecModel);
  38514. this._sourceManager = new SourceManager(this);
  38515. disableTransformOptionMerge(this);
  38516. };
  38517. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  38518. _super.prototype.mergeOption.call(this, newOption, ecModel);
  38519. disableTransformOptionMerge(this);
  38520. };
  38521. DatasetModel.prototype.optionUpdated = function () {
  38522. this._sourceManager.dirty();
  38523. };
  38524. DatasetModel.prototype.getSourceManager = function () {
  38525. return this._sourceManager;
  38526. };
  38527. DatasetModel.type = 'dataset';
  38528. DatasetModel.defaultOption = {
  38529. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  38530. };
  38531. return DatasetModel;
  38532. }(ComponentModel);
  38533. var DatasetView =
  38534. /** @class */
  38535. function (_super) {
  38536. __extends(DatasetView, _super);
  38537. function DatasetView() {
  38538. var _this = _super !== null && _super.apply(this, arguments) || this;
  38539. _this.type = 'dataset';
  38540. return _this;
  38541. }
  38542. DatasetView.type = 'dataset';
  38543. return DatasetView;
  38544. }(ComponentView);
  38545. function install$6(registers) {
  38546. registers.registerComponentModel(DatasetModel);
  38547. registers.registerComponentView(DatasetView);
  38548. }
  38549. use([install]);
  38550. use([install$1, install$2, install$3]);
  38551. use([install$4, install$5, install$6]);
  38552. exports.Axis = Axis;
  38553. exports.ChartView = ChartView;
  38554. exports.ComponentModel = ComponentModel;
  38555. exports.ComponentView = ComponentView;
  38556. exports.List = List;
  38557. exports.Model = Model;
  38558. exports.PRIORITY = PRIORITY;
  38559. exports.SeriesModel = SeriesModel;
  38560. exports.color = color;
  38561. exports.connect = connect;
  38562. exports.dataTool = dataTool;
  38563. exports.dependencies = dependencies;
  38564. exports.disConnect = disConnect;
  38565. exports.disconnect = disconnect;
  38566. exports.dispose = dispose$1;
  38567. exports.env = env;
  38568. exports.extendChartView = extendChartView;
  38569. exports.extendComponentModel = extendComponentModel;
  38570. exports.extendComponentView = extendComponentView;
  38571. exports.extendSeriesModel = extendSeriesModel;
  38572. exports.format = format$1;
  38573. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  38574. exports.getInstanceByDom = getInstanceByDom;
  38575. exports.getInstanceById = getInstanceById;
  38576. exports.getMap = getMap;
  38577. exports.graphic = graphic;
  38578. exports.helper = helper;
  38579. exports.init = init$1;
  38580. exports.innerDrawElementOnCanvas = brushSingle;
  38581. exports.matrix = matrix;
  38582. exports.number = number;
  38583. exports.parseGeoJSON = parseGeoJSON;
  38584. exports.parseGeoJson = parseGeoJSON;
  38585. exports.registerAction = registerAction;
  38586. exports.registerCoordinateSystem = registerCoordinateSystem;
  38587. exports.registerLayout = registerLayout;
  38588. exports.registerLoading = registerLoading;
  38589. exports.registerLocale = registerLocale;
  38590. exports.registerMap = registerMap;
  38591. exports.registerPostInit = registerPostInit;
  38592. exports.registerPostUpdate = registerPostUpdate;
  38593. exports.registerPreprocessor = registerPreprocessor;
  38594. exports.registerProcessor = registerProcessor;
  38595. exports.registerTheme = registerTheme;
  38596. exports.registerTransform = registerTransform;
  38597. exports.registerVisual = registerVisual;
  38598. exports.setCanvasCreator = setCanvasCreator;
  38599. exports.throttle = throttle;
  38600. exports.time = time;
  38601. exports.use = use;
  38602. exports.util = util$1;
  38603. exports.vector = vector;
  38604. exports.version = version$1;
  38605. exports.zrUtil = util;
  38606. exports.zrender = zrender;
  38607. Object.defineProperty(exports, '__esModule', { value: true });
  38608. })));
  38609. //# sourceMappingURL=echarts.simple.js.map